Update OOjs UI to v0.8.2
[mediawiki.git] / resources / lib / oojs-ui / oojs-ui.js
blob8bb14ecb442582dda134f03c32c1c1af6b6116e3
1 /*!
2 * OOjs UI v0.8.2
3 * https://www.mediawiki.org/wiki/OOjs_UI
5 * Copyright 2011–2015 OOjs Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
9 * Date: 2015-02-27T18:02:31Z
11 ( function ( OO ) {
13 'use strict';
15 /**
16 * Namespace for all classes, static methods and static properties.
18 * @class
19 * @singleton
21 OO.ui = {};
23 OO.ui.bind = $.proxy;
25 /**
26 * @property {Object}
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
47 /**
48 * Get the user's language and any fallback languages.
50 * These language codes are used to localize user interface elements in the user's language.
52 * In environments that provide a localization system, this function should be overridden to
53 * return the user's language(s). The default implementation returns English (en) only.
55 * @return {string[]} Language codes, in descending order of priority
57 OO.ui.getUserLanguages = function () {
58 return [ 'en' ];
61 /**
62 * Get a value in an object keyed by language code.
64 * @param {Object.<string,Mixed>} obj Object keyed by language code
65 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
66 * @param {string} [fallback] Fallback code, used if no matching language can be found
67 * @return {Mixed} Local value
69 OO.ui.getLocalValue = function ( obj, lang, fallback ) {
70 var i, len, langs;
72 // Requested language
73 if ( obj[ lang ] ) {
74 return obj[ lang ];
76 // Known user language
77 langs = OO.ui.getUserLanguages();
78 for ( i = 0, len = langs.length; i < len; i++ ) {
79 lang = langs[ i ];
80 if ( obj[ lang ] ) {
81 return obj[ lang ];
84 // Fallback language
85 if ( obj[ fallback ] ) {
86 return obj[ fallback ];
88 // First existing language
89 for ( lang in obj ) {
90 return obj[ lang ];
93 return undefined;
96 /**
97 * Check if a node is contained within another node
99 * Similar to jQuery#contains except a list of containers can be supplied
100 * and a boolean argument allows you to include the container in the match list
102 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
103 * @param {HTMLElement} contained Node to find
104 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
105 * @return {boolean} The node is in the list of target nodes
107 OO.ui.contains = function ( containers, contained, matchContainers ) {
108 var i;
109 if ( !Array.isArray( containers ) ) {
110 containers = [ containers ];
112 for ( i = containers.length - 1; i >= 0; i-- ) {
113 if ( ( matchContainers && contained === containers[ i ] ) || $.contains( containers[ i ], contained ) ) {
114 return true;
117 return false;
120 ( function () {
122 * Message store for the default implementation of OO.ui.msg
124 * Environments that provide a localization system should not use this, but should override
125 * OO.ui.msg altogether.
127 * @private
129 var messages = {
130 // Tool tip for a button that moves items in a list down one place
131 'ooui-outline-control-move-down': 'Move item down',
132 // Tool tip for a button that moves items in a list up one place
133 'ooui-outline-control-move-up': 'Move item up',
134 // Tool tip for a button that removes items from a list
135 'ooui-outline-control-remove': 'Remove item',
136 // Label for the toolbar group that contains a list of all other available tools
137 'ooui-toolbar-more': 'More',
138 // Label for the fake tool that expands the full list of tools in a toolbar group
139 'ooui-toolgroup-expand': 'More',
140 // Label for the fake tool that collapses the full list of tools in a toolbar group
141 'ooui-toolgroup-collapse': 'Fewer',
142 // Default label for the accept button of a confirmation dialog
143 'ooui-dialog-message-accept': 'OK',
144 // Default label for the reject button of a confirmation dialog
145 'ooui-dialog-message-reject': 'Cancel',
146 // Title for process dialog error description
147 'ooui-dialog-process-error': 'Something went wrong',
148 // Label for process dialog dismiss error button, visible when describing errors
149 'ooui-dialog-process-dismiss': 'Dismiss',
150 // Label for process dialog retry action button, visible when describing only recoverable errors
151 'ooui-dialog-process-retry': 'Try again',
152 // Label for process dialog retry action button, visible when describing only warnings
153 'ooui-dialog-process-continue': 'Continue'
157 * Get a localized message.
159 * In environments that provide a localization system, this function should be overridden to
160 * return the message translated in the user's language. The default implementation always returns
161 * English messages.
163 * After the message key, message parameters may optionally be passed. In the default implementation,
164 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
165 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
166 * they support unnamed, ordered message parameters.
168 * @abstract
169 * @param {string} key Message key
170 * @param {Mixed...} [params] Message parameters
171 * @return {string} Translated message with parameters substituted
173 OO.ui.msg = function ( key ) {
174 var message = messages[ key ],
175 params = Array.prototype.slice.call( arguments, 1 );
176 if ( typeof message === 'string' ) {
177 // Perform $1 substitution
178 message = message.replace( /\$(\d+)/g, function ( unused, n ) {
179 var i = parseInt( n, 10 );
180 return params[ i - 1 ] !== undefined ? params[ i - 1 ] : '$' + n;
181 } );
182 } else {
183 // Return placeholder if message not found
184 message = '[' + key + ']';
186 return message;
190 * Package a message and arguments for deferred resolution.
192 * Use this when you are statically specifying a message and the message may not yet be present.
194 * @param {string} key Message key
195 * @param {Mixed...} [params] Message parameters
196 * @return {Function} Function that returns the resolved message when executed
198 OO.ui.deferMsg = function () {
199 var args = arguments;
200 return function () {
201 return OO.ui.msg.apply( OO.ui, args );
206 * Resolve a message.
208 * If the message is a function it will be executed, otherwise it will pass through directly.
210 * @param {Function|string} msg Deferred message, or message text
211 * @return {string} Resolved message
213 OO.ui.resolveMsg = function ( msg ) {
214 if ( $.isFunction( msg ) ) {
215 return msg();
217 return msg;
220 } )();
223 * Element that can be marked as pending.
225 * @abstract
226 * @class
228 * @constructor
229 * @param {Object} [config] Configuration options
230 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
232 OO.ui.PendingElement = function OoUiPendingElement( config ) {
233 // Configuration initialization
234 config = config || {};
236 // Properties
237 this.pending = 0;
238 this.$pending = null;
240 // Initialisation
241 this.setPendingElement( config.$pending || this.$element );
244 /* Setup */
246 OO.initClass( OO.ui.PendingElement );
248 /* Methods */
251 * Set the pending element (and clean up any existing one).
253 * @param {jQuery} $pending The element to set to pending.
255 OO.ui.PendingElement.prototype.setPendingElement = function ( $pending ) {
256 if ( this.$pending ) {
257 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
260 this.$pending = $pending;
261 if ( this.pending > 0 ) {
262 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
267 * Check if input is pending.
269 * @return {boolean}
271 OO.ui.PendingElement.prototype.isPending = function () {
272 return !!this.pending;
276 * Increase the pending stack.
278 * @chainable
280 OO.ui.PendingElement.prototype.pushPending = function () {
281 if ( this.pending === 0 ) {
282 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
283 this.updateThemeClasses();
285 this.pending++;
287 return this;
291 * Reduce the pending stack.
293 * Clamped at zero.
295 * @chainable
297 OO.ui.PendingElement.prototype.popPending = function () {
298 if ( this.pending === 1 ) {
299 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
300 this.updateThemeClasses();
302 this.pending = Math.max( 0, this.pending - 1 );
304 return this;
308 * ActionSets manage the behavior of the {@link OO.ui.ActionWidget Action widgets} that comprise them.
309 * Actions can be made available for specific contexts (modes) and circumstances
310 * (abilities). Please see the [OOjs UI documentation on MediaWiki][1] for more information.
312 * @example
313 * // Example: An action set used in a process dialog
314 * function ProcessDialog( config ) {
315 * ProcessDialog.super.call( this, config );
317 * OO.inheritClass( ProcessDialog, OO.ui.ProcessDialog );
318 * ProcessDialog.static.title = 'An action set in a process dialog';
319 * // An action set that uses modes ('edit' and 'help' mode, in this example).
320 * ProcessDialog.static.actions = [
321 * { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] },
322 * { action: 'help', modes: 'edit', label: 'Help' },
323 * { modes: 'edit', label: 'Cancel', flags: 'safe' },
324 * { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
325 * ];
327 * ProcessDialog.prototype.initialize = function () {
328 * ProcessDialog.super.prototype.initialize.apply( this, arguments );
329 * this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
330 * 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>' );
331 * this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
332 * 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>' );
333 * this.stackLayout= new OO.ui.StackLayout( {
334 * items: [ this.panel1, this.panel2 ]
335 * });
336 * this.$body.append( this.stackLayout.$element );
337 * };
338 * ProcessDialog.prototype.getSetupProcess = function ( data ) {
339 * return ProcessDialog.super.prototype.getSetupProcess.call( this, data )
340 * .next( function () {
341 * this.actions.setMode('edit');
342 * }, this );
343 * };
344 * ProcessDialog.prototype.getActionProcess = function ( action ) {
345 * if ( action === 'help' ) {
346 * this.actions.setMode( 'help' );
347 * this.stackLayout.setItem( this.panel2 );
348 * } else if ( action === 'back' ) {
349 * this.actions.setMode( 'edit' );
350 * this.stackLayout.setItem( this.panel1 );
351 * } else if ( action === 'continue' ) {
352 * var dialog = this;
353 * return new OO.ui.Process( function () {
354 * dialog.close();
355 * } );
357 * return ProcessDialog.super.prototype.getActionProcess.call( this, action );
358 * };
359 * ProcessDialog.prototype.getBodyHeight = function () {
360 * return this.panel1.$element.outerHeight( true );
361 * };
362 * var windowManager = new OO.ui.WindowManager();
363 * $( 'body' ).append( windowManager.$element );
364 * var processDialog = new ProcessDialog({
365 * size: 'medium'});
366 * windowManager.addWindows( [ processDialog ] );
367 * windowManager.openWindow( processDialog );
369 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
371 * @abstract
372 * @class
373 * @mixins OO.EventEmitter
375 * @constructor
376 * @param {Object} [config] Configuration options
378 OO.ui.ActionSet = function OoUiActionSet( config ) {
379 // Configuration initialization
380 config = config || {};
382 // Mixin constructors
383 OO.EventEmitter.call( this );
385 // Properties
386 this.list = [];
387 this.categories = {
388 actions: 'getAction',
389 flags: 'getFlags',
390 modes: 'getModes'
392 this.categorized = {};
393 this.special = {};
394 this.others = [];
395 this.organized = false;
396 this.changing = false;
397 this.changed = false;
400 /* Setup */
402 OO.mixinClass( OO.ui.ActionSet, OO.EventEmitter );
404 /* Static Properties */
407 * Symbolic name of the flags used to identify special actions. Special actions are displayed in the
408 * header of a {@link OO.ui.ProcessDialog process dialog}.
409 * See the [OOjs UI documentation on MediaWiki][2] for more information and examples.
411 * [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
413 * @abstract
414 * @static
415 * @inheritable
416 * @property {string}
418 OO.ui.ActionSet.static.specialFlags = [ 'safe', 'primary' ];
420 /* Events */
423 * @event click
424 * @param {OO.ui.ActionWidget} action Action that was clicked
428 * @event resize
429 * @param {OO.ui.ActionWidget} action Action that was resized
433 * @event add
434 * @param {OO.ui.ActionWidget[]} added Actions added
438 * @event remove
439 * @param {OO.ui.ActionWidget[]} added Actions removed
443 * @event change
446 /* Methods */
449 * Handle action change events.
451 * @private
452 * @fires change
454 OO.ui.ActionSet.prototype.onActionChange = function () {
455 this.organized = false;
456 if ( this.changing ) {
457 this.changed = true;
458 } else {
459 this.emit( 'change' );
464 * Check if a action is one of the special actions.
466 * @param {OO.ui.ActionWidget} action Action to check
467 * @return {boolean} Action is special
469 OO.ui.ActionSet.prototype.isSpecial = function ( action ) {
470 var flag;
472 for ( flag in this.special ) {
473 if ( action === this.special[ flag ] ) {
474 return true;
478 return false;
482 * Get actions.
484 * @param {Object} [filters] Filters to use, omit to get all actions
485 * @param {string|string[]} [filters.actions] Actions that actions must have
486 * @param {string|string[]} [filters.flags] Flags that actions must have
487 * @param {string|string[]} [filters.modes] Modes that actions must have
488 * @param {boolean} [filters.visible] Actions must be visible
489 * @param {boolean} [filters.disabled] Actions must be disabled
490 * @return {OO.ui.ActionWidget[]} Actions matching all criteria
492 OO.ui.ActionSet.prototype.get = function ( filters ) {
493 var i, len, list, category, actions, index, match, matches;
495 if ( filters ) {
496 this.organize();
498 // Collect category candidates
499 matches = [];
500 for ( category in this.categorized ) {
501 list = filters[ category ];
502 if ( list ) {
503 if ( !Array.isArray( list ) ) {
504 list = [ list ];
506 for ( i = 0, len = list.length; i < len; i++ ) {
507 actions = this.categorized[ category ][ list[ i ] ];
508 if ( Array.isArray( actions ) ) {
509 matches.push.apply( matches, actions );
514 // Remove by boolean filters
515 for ( i = 0, len = matches.length; i < len; i++ ) {
516 match = matches[ i ];
517 if (
518 ( filters.visible !== undefined && match.isVisible() !== filters.visible ) ||
519 ( filters.disabled !== undefined && match.isDisabled() !== filters.disabled )
521 matches.splice( i, 1 );
522 len--;
523 i--;
526 // Remove duplicates
527 for ( i = 0, len = matches.length; i < len; i++ ) {
528 match = matches[ i ];
529 index = matches.lastIndexOf( match );
530 while ( index !== i ) {
531 matches.splice( index, 1 );
532 len--;
533 index = matches.lastIndexOf( match );
536 return matches;
538 return this.list.slice();
542 * Get special actions.
544 * Special actions are the first visible actions with special flags, such as 'safe' and 'primary'.
545 * Special flags can be configured by changing #static-specialFlags in a subclass.
547 * @return {OO.ui.ActionWidget|null} Safe action
549 OO.ui.ActionSet.prototype.getSpecial = function () {
550 this.organize();
551 return $.extend( {}, this.special );
555 * Get other actions.
557 * Other actions include all non-special visible actions.
559 * @return {OO.ui.ActionWidget[]} Other actions
561 OO.ui.ActionSet.prototype.getOthers = function () {
562 this.organize();
563 return this.others.slice();
567 * Toggle actions based on their modes.
569 * Unlike calling toggle on actions with matching flags, this will enforce mutually exclusive
570 * visibility; matching actions will be shown, non-matching actions will be hidden.
572 * @param {string} mode Mode actions must have
573 * @chainable
574 * @fires toggle
575 * @fires change
577 OO.ui.ActionSet.prototype.setMode = function ( mode ) {
578 var i, len, action;
580 this.changing = true;
581 for ( i = 0, len = this.list.length; i < len; i++ ) {
582 action = this.list[ i ];
583 action.toggle( action.hasMode( mode ) );
586 this.organized = false;
587 this.changing = false;
588 this.emit( 'change' );
590 return this;
594 * Change which actions are able to be performed.
596 * Actions with matching actions will be disabled/enabled. Other actions will not be changed.
598 * @param {Object.<string,boolean>} actions List of abilities, keyed by action name, values
599 * indicate actions are able to be performed
600 * @chainable
602 OO.ui.ActionSet.prototype.setAbilities = function ( actions ) {
603 var i, len, action, item;
605 for ( i = 0, len = this.list.length; i < len; i++ ) {
606 item = this.list[ i ];
607 action = item.getAction();
608 if ( actions[ action ] !== undefined ) {
609 item.setDisabled( !actions[ action ] );
613 return this;
617 * Executes a function once per action.
619 * When making changes to multiple actions, use this method instead of iterating over the actions
620 * manually to defer emitting a change event until after all actions have been changed.
622 * @param {Object|null} actions Filters to use for which actions to iterate over; see #get
623 * @param {Function} callback Callback to run for each action; callback is invoked with three
624 * arguments: the action, the action's index, the list of actions being iterated over
625 * @chainable
627 OO.ui.ActionSet.prototype.forEach = function ( filter, callback ) {
628 this.changed = false;
629 this.changing = true;
630 this.get( filter ).forEach( callback );
631 this.changing = false;
632 if ( this.changed ) {
633 this.emit( 'change' );
636 return this;
640 * Add actions.
642 * @param {OO.ui.ActionWidget[]} actions Actions to add
643 * @chainable
644 * @fires add
645 * @fires change
647 OO.ui.ActionSet.prototype.add = function ( actions ) {
648 var i, len, action;
650 this.changing = true;
651 for ( i = 0, len = actions.length; i < len; i++ ) {
652 action = actions[ i ];
653 action.connect( this, {
654 click: [ 'emit', 'click', action ],
655 resize: [ 'emit', 'resize', action ],
656 toggle: [ 'onActionChange' ]
657 } );
658 this.list.push( action );
660 this.organized = false;
661 this.emit( 'add', actions );
662 this.changing = false;
663 this.emit( 'change' );
665 return this;
669 * Remove actions.
671 * @param {OO.ui.ActionWidget[]} actions Actions to remove
672 * @chainable
673 * @fires remove
674 * @fires change
676 OO.ui.ActionSet.prototype.remove = function ( actions ) {
677 var i, len, index, action;
679 this.changing = true;
680 for ( i = 0, len = actions.length; i < len; i++ ) {
681 action = actions[ i ];
682 index = this.list.indexOf( action );
683 if ( index !== -1 ) {
684 action.disconnect( this );
685 this.list.splice( index, 1 );
688 this.organized = false;
689 this.emit( 'remove', actions );
690 this.changing = false;
691 this.emit( 'change' );
693 return this;
697 * Remove all actions.
699 * @chainable
700 * @fires remove
701 * @fires change
703 OO.ui.ActionSet.prototype.clear = function () {
704 var i, len, action,
705 removed = this.list.slice();
707 this.changing = true;
708 for ( i = 0, len = this.list.length; i < len; i++ ) {
709 action = this.list[ i ];
710 action.disconnect( this );
713 this.list = [];
715 this.organized = false;
716 this.emit( 'remove', removed );
717 this.changing = false;
718 this.emit( 'change' );
720 return this;
724 * Organize actions.
726 * This is called whenever organized information is requested. It will only reorganize the actions
727 * if something has changed since the last time it ran.
729 * @private
730 * @chainable
732 OO.ui.ActionSet.prototype.organize = function () {
733 var i, iLen, j, jLen, flag, action, category, list, item, special,
734 specialFlags = this.constructor.static.specialFlags;
736 if ( !this.organized ) {
737 this.categorized = {};
738 this.special = {};
739 this.others = [];
740 for ( i = 0, iLen = this.list.length; i < iLen; i++ ) {
741 action = this.list[ i ];
742 if ( action.isVisible() ) {
743 // Populate categories
744 for ( category in this.categories ) {
745 if ( !this.categorized[ category ] ) {
746 this.categorized[ category ] = {};
748 list = action[ this.categories[ category ] ]();
749 if ( !Array.isArray( list ) ) {
750 list = [ list ];
752 for ( j = 0, jLen = list.length; j < jLen; j++ ) {
753 item = list[ j ];
754 if ( !this.categorized[ category ][ item ] ) {
755 this.categorized[ category ][ item ] = [];
757 this.categorized[ category ][ item ].push( action );
760 // Populate special/others
761 special = false;
762 for ( j = 0, jLen = specialFlags.length; j < jLen; j++ ) {
763 flag = specialFlags[ j ];
764 if ( !this.special[ flag ] && action.hasFlag( flag ) ) {
765 this.special[ flag ] = action;
766 special = true;
767 break;
770 if ( !special ) {
771 this.others.push( action );
775 this.organized = true;
778 return this;
782 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
783 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
784 * connected to them and can't be interacted with.
786 * @abstract
787 * @class
789 * @constructor
790 * @param {Object} [config] Configuration options
791 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
792 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
793 * for an example.
794 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
795 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
796 * @cfg {string} [text] Text to insert
797 * @cfg {Array} [content] An array of content elements to append (after #text).
798 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
799 * Instances of OO.ui.Element will have their $element appended.
800 * @cfg {jQuery} [$content] Content elements to append (after #text)
801 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
802 * Data can also be specified with the #setData method.
804 OO.ui.Element = function OoUiElement( config ) {
805 // Configuration initialization
806 config = config || {};
808 // Properties
809 this.$ = $;
810 this.visible = true;
811 this.data = config.data;
812 this.$element = config.$element ||
813 $( document.createElement( this.getTagName() ) );
814 this.elementGroup = null;
815 this.debouncedUpdateThemeClassesHandler = this.debouncedUpdateThemeClasses.bind( this );
816 this.updateThemeClassesPending = false;
818 // Initialization
819 if ( Array.isArray( config.classes ) ) {
820 this.$element.addClass( config.classes.join( ' ' ) );
822 if ( config.id ) {
823 this.$element.attr( 'id', config.id );
825 if ( config.text ) {
826 this.$element.text( config.text );
828 if ( config.content ) {
829 // The `content` property treats plain strings as text; use an
830 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
831 // appropriate $element appended.
832 this.$element.append( config.content.map( function ( v ) {
833 if ( typeof v === 'string' ) {
834 // Escape string so it is properly represented in HTML.
835 return document.createTextNode( v );
836 } else if ( v instanceof OO.ui.HtmlSnippet ) {
837 // Bypass escaping.
838 return v.toString();
839 } else if ( v instanceof OO.ui.Element ) {
840 return v.$element;
842 return v;
843 } ) );
845 if ( config.$content ) {
846 // The `$content` property treats plain strings as HTML.
847 this.$element.append( config.$content );
851 /* Setup */
853 OO.initClass( OO.ui.Element );
855 /* Static Properties */
858 * The name of the HTML tag used by the element.
860 * The static value may be ignored if the #getTagName method is overridden.
862 * @static
863 * @inheritable
864 * @property {string}
866 OO.ui.Element.static.tagName = 'div';
868 /* Static Methods */
871 * Get a jQuery function within a specific document.
873 * @static
874 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
875 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
876 * not in an iframe
877 * @return {Function} Bound jQuery function
879 OO.ui.Element.static.getJQuery = function ( context, $iframe ) {
880 function wrapper( selector ) {
881 return $( selector, wrapper.context );
884 wrapper.context = this.getDocument( context );
886 if ( $iframe ) {
887 wrapper.$iframe = $iframe;
890 return wrapper;
894 * Get the document of an element.
896 * @static
897 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
898 * @return {HTMLDocument|null} Document object
900 OO.ui.Element.static.getDocument = function ( obj ) {
901 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
902 return ( obj[ 0 ] && obj[ 0 ].ownerDocument ) ||
903 // Empty jQuery selections might have a context
904 obj.context ||
905 // HTMLElement
906 obj.ownerDocument ||
907 // Window
908 obj.document ||
909 // HTMLDocument
910 ( obj.nodeType === 9 && obj ) ||
911 null;
915 * Get the window of an element or document.
917 * @static
918 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
919 * @return {Window} Window object
921 OO.ui.Element.static.getWindow = function ( obj ) {
922 var doc = this.getDocument( obj );
923 return doc.parentWindow || doc.defaultView;
927 * Get the direction of an element or document.
929 * @static
930 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
931 * @return {string} Text direction, either 'ltr' or 'rtl'
933 OO.ui.Element.static.getDir = function ( obj ) {
934 var isDoc, isWin;
936 if ( obj instanceof jQuery ) {
937 obj = obj[ 0 ];
939 isDoc = obj.nodeType === 9;
940 isWin = obj.document !== undefined;
941 if ( isDoc || isWin ) {
942 if ( isWin ) {
943 obj = obj.document;
945 obj = obj.body;
947 return $( obj ).css( 'direction' );
951 * Get the offset between two frames.
953 * TODO: Make this function not use recursion.
955 * @static
956 * @param {Window} from Window of the child frame
957 * @param {Window} [to=window] Window of the parent frame
958 * @param {Object} [offset] Offset to start with, used internally
959 * @return {Object} Offset object, containing left and top properties
961 OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) {
962 var i, len, frames, frame, rect;
964 if ( !to ) {
965 to = window;
967 if ( !offset ) {
968 offset = { top: 0, left: 0 };
970 if ( from.parent === from ) {
971 return offset;
974 // Get iframe element
975 frames = from.parent.document.getElementsByTagName( 'iframe' );
976 for ( i = 0, len = frames.length; i < len; i++ ) {
977 if ( frames[ i ].contentWindow === from ) {
978 frame = frames[ i ];
979 break;
983 // Recursively accumulate offset values
984 if ( frame ) {
985 rect = frame.getBoundingClientRect();
986 offset.left += rect.left;
987 offset.top += rect.top;
988 if ( from !== to ) {
989 this.getFrameOffset( from.parent, offset );
992 return offset;
996 * Get the offset between two elements.
998 * The two elements may be in a different frame, but in that case the frame $element is in must
999 * be contained in the frame $anchor is in.
1001 * @static
1002 * @param {jQuery} $element Element whose position to get
1003 * @param {jQuery} $anchor Element to get $element's position relative to
1004 * @return {Object} Translated position coordinates, containing top and left properties
1006 OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) {
1007 var iframe, iframePos,
1008 pos = $element.offset(),
1009 anchorPos = $anchor.offset(),
1010 elementDocument = this.getDocument( $element ),
1011 anchorDocument = this.getDocument( $anchor );
1013 // If $element isn't in the same document as $anchor, traverse up
1014 while ( elementDocument !== anchorDocument ) {
1015 iframe = elementDocument.defaultView.frameElement;
1016 if ( !iframe ) {
1017 throw new Error( '$element frame is not contained in $anchor frame' );
1019 iframePos = $( iframe ).offset();
1020 pos.left += iframePos.left;
1021 pos.top += iframePos.top;
1022 elementDocument = iframe.ownerDocument;
1024 pos.left -= anchorPos.left;
1025 pos.top -= anchorPos.top;
1026 return pos;
1030 * Get element border sizes.
1032 * @static
1033 * @param {HTMLElement} el Element to measure
1034 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1036 OO.ui.Element.static.getBorders = function ( el ) {
1037 var doc = el.ownerDocument,
1038 win = doc.parentWindow || doc.defaultView,
1039 style = win && win.getComputedStyle ?
1040 win.getComputedStyle( el, null ) :
1041 el.currentStyle,
1042 $el = $( el ),
1043 top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
1044 left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
1045 bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
1046 right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
1048 return {
1049 top: top,
1050 left: left,
1051 bottom: bottom,
1052 right: right
1057 * Get dimensions of an element or window.
1059 * @static
1060 * @param {HTMLElement|Window} el Element to measure
1061 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1063 OO.ui.Element.static.getDimensions = function ( el ) {
1064 var $el, $win,
1065 doc = el.ownerDocument || el.document,
1066 win = doc.parentWindow || doc.defaultView;
1068 if ( win === el || el === doc.documentElement ) {
1069 $win = $( win );
1070 return {
1071 borders: { top: 0, left: 0, bottom: 0, right: 0 },
1072 scroll: {
1073 top: $win.scrollTop(),
1074 left: $win.scrollLeft()
1076 scrollbar: { right: 0, bottom: 0 },
1077 rect: {
1078 top: 0,
1079 left: 0,
1080 bottom: $win.innerHeight(),
1081 right: $win.innerWidth()
1084 } else {
1085 $el = $( el );
1086 return {
1087 borders: this.getBorders( el ),
1088 scroll: {
1089 top: $el.scrollTop(),
1090 left: $el.scrollLeft()
1092 scrollbar: {
1093 right: $el.innerWidth() - el.clientWidth,
1094 bottom: $el.innerHeight() - el.clientHeight
1096 rect: el.getBoundingClientRect()
1102 * Get scrollable object parent
1104 * documentElement can't be used to get or set the scrollTop
1105 * property on Blink. Changing and testing its value lets us
1106 * use 'body' or 'documentElement' based on what is working.
1108 * https://code.google.com/p/chromium/issues/detail?id=303131
1110 * @static
1111 * @param {HTMLElement} el Element to find scrollable parent for
1112 * @return {HTMLElement} Scrollable parent
1114 OO.ui.Element.static.getRootScrollableElement = function ( el ) {
1115 var scrollTop, body;
1117 if ( OO.ui.scrollableElement === undefined ) {
1118 body = el.ownerDocument.body;
1119 scrollTop = body.scrollTop;
1120 body.scrollTop = 1;
1122 if ( body.scrollTop === 1 ) {
1123 body.scrollTop = scrollTop;
1124 OO.ui.scrollableElement = 'body';
1125 } else {
1126 OO.ui.scrollableElement = 'documentElement';
1130 return el.ownerDocument[ OO.ui.scrollableElement ];
1134 * Get closest scrollable container.
1136 * Traverses up until either a scrollable element or the root is reached, in which case the window
1137 * will be returned.
1139 * @static
1140 * @param {HTMLElement} el Element to find scrollable container for
1141 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1142 * @return {HTMLElement} Closest scrollable container
1144 OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) {
1145 var i, val,
1146 props = [ 'overflow' ],
1147 $parent = $( el ).parent();
1149 if ( dimension === 'x' || dimension === 'y' ) {
1150 props.push( 'overflow-' + dimension );
1153 while ( $parent.length ) {
1154 if ( $parent[ 0 ] === this.getRootScrollableElement( el ) ) {
1155 return $parent[ 0 ];
1157 i = props.length;
1158 while ( i-- ) {
1159 val = $parent.css( props[ i ] );
1160 if ( val === 'auto' || val === 'scroll' ) {
1161 return $parent[ 0 ];
1164 $parent = $parent.parent();
1166 return this.getDocument( el ).body;
1170 * Scroll element into view.
1172 * @static
1173 * @param {HTMLElement} el Element to scroll into view
1174 * @param {Object} [config] Configuration options
1175 * @param {string} [config.duration] jQuery animation duration value
1176 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1177 * to scroll in both directions
1178 * @param {Function} [config.complete] Function to call when scrolling completes
1180 OO.ui.Element.static.scrollIntoView = function ( el, config ) {
1181 // Configuration initialization
1182 config = config || {};
1184 var rel, anim = {},
1185 callback = typeof config.complete === 'function' && config.complete,
1186 sc = this.getClosestScrollableContainer( el, config.direction ),
1187 $sc = $( sc ),
1188 eld = this.getDimensions( el ),
1189 scd = this.getDimensions( sc ),
1190 $win = $( this.getWindow( el ) );
1192 // Compute the distances between the edges of el and the edges of the scroll viewport
1193 if ( $sc.is( 'html, body' ) ) {
1194 // If the scrollable container is the root, this is easy
1195 rel = {
1196 top: eld.rect.top,
1197 bottom: $win.innerHeight() - eld.rect.bottom,
1198 left: eld.rect.left,
1199 right: $win.innerWidth() - eld.rect.right
1201 } else {
1202 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1203 rel = {
1204 top: eld.rect.top - ( scd.rect.top + scd.borders.top ),
1205 bottom: scd.rect.bottom - scd.borders.bottom - scd.scrollbar.bottom - eld.rect.bottom,
1206 left: eld.rect.left - ( scd.rect.left + scd.borders.left ),
1207 right: scd.rect.right - scd.borders.right - scd.scrollbar.right - eld.rect.right
1211 if ( !config.direction || config.direction === 'y' ) {
1212 if ( rel.top < 0 ) {
1213 anim.scrollTop = scd.scroll.top + rel.top;
1214 } else if ( rel.top > 0 && rel.bottom < 0 ) {
1215 anim.scrollTop = scd.scroll.top + Math.min( rel.top, -rel.bottom );
1218 if ( !config.direction || config.direction === 'x' ) {
1219 if ( rel.left < 0 ) {
1220 anim.scrollLeft = scd.scroll.left + rel.left;
1221 } else if ( rel.left > 0 && rel.right < 0 ) {
1222 anim.scrollLeft = scd.scroll.left + Math.min( rel.left, -rel.right );
1225 if ( !$.isEmptyObject( anim ) ) {
1226 $sc.stop( true ).animate( anim, config.duration || 'fast' );
1227 if ( callback ) {
1228 $sc.queue( function ( next ) {
1229 callback();
1230 next();
1231 } );
1233 } else {
1234 if ( callback ) {
1235 callback();
1241 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1242 * and reserve space for them, because it probably doesn't.
1244 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1245 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1246 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1247 * and then reattach (or show) them back.
1249 * @static
1250 * @param {HTMLElement} el Element to reconsider the scrollbars on
1252 OO.ui.Element.static.reconsiderScrollbars = function ( el ) {
1253 var i, len, nodes = [];
1254 // Detach all children
1255 while ( el.firstChild ) {
1256 nodes.push( el.firstChild );
1257 el.removeChild( el.firstChild );
1259 // Force reflow
1260 void el.offsetHeight;
1261 // Reattach all children
1262 for ( i = 0, len = nodes.length; i < len; i++ ) {
1263 el.appendChild( nodes[ i ] );
1267 /* Methods */
1270 * Toggle visibility of an element.
1272 * @param {boolean} [show] Make element visible, omit to toggle visibility
1273 * @fires visible
1274 * @chainable
1276 OO.ui.Element.prototype.toggle = function ( show ) {
1277 show = show === undefined ? !this.visible : !!show;
1279 if ( show !== this.isVisible() ) {
1280 this.visible = show;
1281 this.$element.toggleClass( 'oo-ui-element-hidden', !this.visible );
1282 this.emit( 'toggle', show );
1285 return this;
1289 * Check if element is visible.
1291 * @return {boolean} element is visible
1293 OO.ui.Element.prototype.isVisible = function () {
1294 return this.visible;
1298 * Get element data.
1300 * @return {Mixed} Element data
1302 OO.ui.Element.prototype.getData = function () {
1303 return this.data;
1307 * Set element data.
1309 * @param {Mixed} Element data
1310 * @chainable
1312 OO.ui.Element.prototype.setData = function ( data ) {
1313 this.data = data;
1314 return this;
1318 * Check if element supports one or more methods.
1320 * @param {string|string[]} methods Method or list of methods to check
1321 * @return {boolean} All methods are supported
1323 OO.ui.Element.prototype.supports = function ( methods ) {
1324 var i, len,
1325 support = 0;
1327 methods = Array.isArray( methods ) ? methods : [ methods ];
1328 for ( i = 0, len = methods.length; i < len; i++ ) {
1329 if ( $.isFunction( this[ methods[ i ] ] ) ) {
1330 support++;
1334 return methods.length === support;
1338 * Update the theme-provided classes.
1340 * @localdoc This is called in element mixins and widget classes any time state changes.
1341 * Updating is debounced, minimizing overhead of changing multiple attributes and
1342 * guaranteeing that theme updates do not occur within an element's constructor
1344 OO.ui.Element.prototype.updateThemeClasses = function () {
1345 if ( !this.updateThemeClassesPending ) {
1346 this.updateThemeClassesPending = true;
1347 setTimeout( this.debouncedUpdateThemeClassesHandler );
1352 * @private
1354 OO.ui.Element.prototype.debouncedUpdateThemeClasses = function () {
1355 OO.ui.theme.updateElementClasses( this );
1356 this.updateThemeClassesPending = false;
1360 * Get the HTML tag name.
1362 * Override this method to base the result on instance information.
1364 * @return {string} HTML tag name
1366 OO.ui.Element.prototype.getTagName = function () {
1367 return this.constructor.static.tagName;
1371 * Check if the element is attached to the DOM
1372 * @return {boolean} The element is attached to the DOM
1374 OO.ui.Element.prototype.isElementAttached = function () {
1375 return $.contains( this.getElementDocument(), this.$element[ 0 ] );
1379 * Get the DOM document.
1381 * @return {HTMLDocument} Document object
1383 OO.ui.Element.prototype.getElementDocument = function () {
1384 // Don't cache this in other ways either because subclasses could can change this.$element
1385 return OO.ui.Element.static.getDocument( this.$element );
1389 * Get the DOM window.
1391 * @return {Window} Window object
1393 OO.ui.Element.prototype.getElementWindow = function () {
1394 return OO.ui.Element.static.getWindow( this.$element );
1398 * Get closest scrollable container.
1400 OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
1401 return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] );
1405 * Get group element is in.
1407 * @return {OO.ui.GroupElement|null} Group element, null if none
1409 OO.ui.Element.prototype.getElementGroup = function () {
1410 return this.elementGroup;
1414 * Set group element is in.
1416 * @param {OO.ui.GroupElement|null} group Group element, null if none
1417 * @chainable
1419 OO.ui.Element.prototype.setElementGroup = function ( group ) {
1420 this.elementGroup = group;
1421 return this;
1425 * Scroll element into view.
1427 * @param {Object} [config] Configuration options
1429 OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
1430 return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config );
1434 * Container for elements.
1436 * @abstract
1437 * @class
1438 * @extends OO.ui.Element
1439 * @mixins OO.EventEmitter
1441 * @constructor
1442 * @param {Object} [config] Configuration options
1444 OO.ui.Layout = function OoUiLayout( config ) {
1445 // Configuration initialization
1446 config = config || {};
1448 // Parent constructor
1449 OO.ui.Layout.super.call( this, config );
1451 // Mixin constructors
1452 OO.EventEmitter.call( this );
1454 // Initialization
1455 this.$element.addClass( 'oo-ui-layout' );
1458 /* Setup */
1460 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
1461 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
1464 * Widgets are compositions of one or more OOjs UI elements that users can both view
1465 * and interact with. All widgets can be configured and modified via a standard API,
1466 * and their state can change dynamically according to a model.
1468 * @abstract
1469 * @class
1470 * @extends OO.ui.Element
1471 * @mixins OO.EventEmitter
1473 * @constructor
1474 * @param {Object} [config] Configuration options
1475 * @cfg {boolean} [disabled=false] Disable
1477 OO.ui.Widget = function OoUiWidget( config ) {
1478 // Initialize config
1479 config = $.extend( { disabled: false }, config );
1481 // Parent constructor
1482 OO.ui.Widget.super.call( this, config );
1484 // Mixin constructors
1485 OO.EventEmitter.call( this );
1487 // Properties
1488 this.disabled = null;
1489 this.wasDisabled = null;
1491 // Initialization
1492 this.$element.addClass( 'oo-ui-widget' );
1493 this.setDisabled( !!config.disabled );
1496 /* Setup */
1498 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
1499 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
1501 /* Events */
1504 * @event disable
1505 * @param {boolean} disabled Widget is disabled
1509 * @event toggle
1510 * @param {boolean} visible Widget is visible
1513 /* Methods */
1516 * Check if the widget is disabled.
1518 * @return {boolean} Button is disabled
1520 OO.ui.Widget.prototype.isDisabled = function () {
1521 return this.disabled;
1525 * Set the disabled state of the widget.
1527 * This should probably change the widgets' appearance and prevent it from being used.
1529 * @param {boolean} disabled Disable widget
1530 * @chainable
1532 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
1533 var isDisabled;
1535 this.disabled = !!disabled;
1536 isDisabled = this.isDisabled();
1537 if ( isDisabled !== this.wasDisabled ) {
1538 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
1539 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
1540 this.$element.attr( 'aria-disabled', isDisabled.toString() );
1541 this.emit( 'disable', isDisabled );
1542 this.updateThemeClasses();
1544 this.wasDisabled = isDisabled;
1546 return this;
1550 * Update the disabled state, in case of changes in parent widget.
1552 * @chainable
1554 OO.ui.Widget.prototype.updateDisabled = function () {
1555 this.setDisabled( this.disabled );
1556 return this;
1560 * A window is a container for elements that are in a child frame. They are used with
1561 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
1562 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
1563 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
1564 * the window manager will choose a sensible fallback.
1566 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
1567 * different processes are executed:
1569 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
1570 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
1571 * the window.
1573 * - {@link #getSetupProcess} method is called and its result executed
1574 * - {@link #getReadyProcess} method is called and its result executed
1576 * **opened**: The window is now open
1578 * **closing**: The closing stage begins when the window manager's
1579 * {@link OO.ui.WindowManager#closeWindow closeWindow}
1580 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
1582 * - {@link #getHoldProcess} method is called and its result executed
1583 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
1585 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
1586 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
1587 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
1588 * processing can complete. Always assume window processes are executed asynchronously.
1590 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
1592 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
1594 * @abstract
1595 * @class
1596 * @extends OO.ui.Element
1597 * @mixins OO.EventEmitter
1599 * @constructor
1600 * @param {Object} [config] Configuration options
1601 * @cfg {string} [size] Symbolic name of dialog size, `small`, `medium`, `large`, `larger` or
1602 * `full`; omit to use #static-size
1604 OO.ui.Window = function OoUiWindow( config ) {
1605 // Configuration initialization
1606 config = config || {};
1608 // Parent constructor
1609 OO.ui.Window.super.call( this, config );
1611 // Mixin constructors
1612 OO.EventEmitter.call( this );
1614 // Properties
1615 this.manager = null;
1616 this.size = config.size || this.constructor.static.size;
1617 this.$frame = $( '<div>' );
1618 this.$overlay = $( '<div>' );
1619 this.$content = $( '<div>' );
1621 // Initialization
1622 this.$overlay.addClass( 'oo-ui-window-overlay' );
1623 this.$content
1624 .addClass( 'oo-ui-window-content' )
1625 .attr( 'tabIndex', 0 );
1626 this.$frame
1627 .addClass( 'oo-ui-window-frame' )
1628 .append( this.$content );
1630 this.$element
1631 .addClass( 'oo-ui-window' )
1632 .append( this.$frame, this.$overlay );
1634 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
1635 // that reference properties not initialized at that time of parent class construction
1636 // TODO: Find a better way to handle post-constructor setup
1637 this.visible = false;
1638 this.$element.addClass( 'oo-ui-element-hidden' );
1641 /* Setup */
1643 OO.inheritClass( OO.ui.Window, OO.ui.Element );
1644 OO.mixinClass( OO.ui.Window, OO.EventEmitter );
1646 /* Static Properties */
1649 * Symbolic name of size.
1651 * Size is used if no size is configured during construction.
1653 * @static
1654 * @inheritable
1655 * @property {string}
1657 OO.ui.Window.static.size = 'medium';
1659 /* Methods */
1662 * Handle mouse down events.
1664 * @param {jQuery.Event} e Mouse down event
1666 OO.ui.Window.prototype.onMouseDown = function ( e ) {
1667 // Prevent clicking on the click-block from stealing focus
1668 if ( e.target === this.$element[ 0 ] ) {
1669 return false;
1674 * Check if window has been initialized.
1676 * Initialization occurs when a window is added to a manager.
1678 * @return {boolean} Window has been initialized
1680 OO.ui.Window.prototype.isInitialized = function () {
1681 return !!this.manager;
1685 * Check if window is visible.
1687 * @return {boolean} Window is visible
1689 OO.ui.Window.prototype.isVisible = function () {
1690 return this.visible;
1694 * Check if window is opening.
1696 * This is a wrapper around OO.ui.WindowManager#isOpening.
1698 * @return {boolean} Window is opening
1700 OO.ui.Window.prototype.isOpening = function () {
1701 return this.manager.isOpening( this );
1705 * Check if window is closing.
1707 * This is a wrapper around OO.ui.WindowManager#isClosing.
1709 * @return {boolean} Window is closing
1711 OO.ui.Window.prototype.isClosing = function () {
1712 return this.manager.isClosing( this );
1716 * Check if window is opened.
1718 * This is a wrapper around OO.ui.WindowManager#isOpened.
1720 * @return {boolean} Window is opened
1722 OO.ui.Window.prototype.isOpened = function () {
1723 return this.manager.isOpened( this );
1727 * Get the window manager.
1729 * @return {OO.ui.WindowManager} Manager of window
1731 OO.ui.Window.prototype.getManager = function () {
1732 return this.manager;
1736 * Get the window size.
1738 * @return {string} Symbolic size name, e.g. `small`, `medium`, `large`, `larger`, `full`
1740 OO.ui.Window.prototype.getSize = function () {
1741 return this.size;
1745 * Disable transitions on window's frame for the duration of the callback function, then enable them
1746 * back.
1748 * @private
1749 * @param {Function} callback Function to call while transitions are disabled
1751 OO.ui.Window.prototype.withoutSizeTransitions = function ( callback ) {
1752 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
1753 // Disable transitions first, otherwise we'll get values from when the window was animating.
1754 var oldTransition,
1755 styleObj = this.$frame[ 0 ].style;
1756 oldTransition = styleObj.transition || styleObj.OTransition || styleObj.MsTransition ||
1757 styleObj.MozTransition || styleObj.WebkitTransition;
1758 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
1759 styleObj.MozTransition = styleObj.WebkitTransition = 'none';
1760 callback();
1761 // Force reflow to make sure the style changes done inside callback really are not transitioned
1762 this.$frame.height();
1763 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
1764 styleObj.MozTransition = styleObj.WebkitTransition = oldTransition;
1768 * Get the height of the dialog contents.
1770 * @return {number} Content height
1772 OO.ui.Window.prototype.getContentHeight = function () {
1773 var bodyHeight,
1774 win = this,
1775 bodyStyleObj = this.$body[ 0 ].style,
1776 frameStyleObj = this.$frame[ 0 ].style;
1778 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
1779 // Disable transitions first, otherwise we'll get values from when the window was animating.
1780 this.withoutSizeTransitions( function () {
1781 var oldHeight = frameStyleObj.height,
1782 oldPosition = bodyStyleObj.position;
1783 frameStyleObj.height = '1px';
1784 // Force body to resize to new width
1785 bodyStyleObj.position = 'relative';
1786 bodyHeight = win.getBodyHeight();
1787 frameStyleObj.height = oldHeight;
1788 bodyStyleObj.position = oldPosition;
1789 } );
1791 return (
1792 // Add buffer for border
1793 ( this.$frame.outerHeight() - this.$frame.innerHeight() ) +
1794 // Use combined heights of children
1795 ( this.$head.outerHeight( true ) + bodyHeight + this.$foot.outerHeight( true ) )
1800 * Get the height of the dialog contents.
1802 * When this function is called, the dialog will temporarily have been resized
1803 * to height=1px, so .scrollHeight measurements can be taken accurately.
1805 * @return {number} Height of content
1807 OO.ui.Window.prototype.getBodyHeight = function () {
1808 return this.$body[ 0 ].scrollHeight;
1812 * Get the directionality of the frame
1814 * @return {string} Directionality, 'ltr' or 'rtl'
1816 OO.ui.Window.prototype.getDir = function () {
1817 return this.dir;
1821 * Get a process for setting up a window for use.
1823 * Each time the window is opened this process will set it up for use in a particular context, based
1824 * on the `data` argument.
1826 * When you override this method, you can add additional setup steps to the process the parent
1827 * method provides using the 'first' and 'next' methods.
1829 * @abstract
1830 * @param {Object} [data] Window opening data
1831 * @return {OO.ui.Process} Setup process
1833 OO.ui.Window.prototype.getSetupProcess = function () {
1834 return new OO.ui.Process();
1838 * Get a process for readying a window for use.
1840 * Each time the window is open and setup, this process will ready it up for use in a particular
1841 * context, based on the `data` argument.
1843 * When you override this method, you can add additional setup steps to the process the parent
1844 * method provides using the 'first' and 'next' methods.
1846 * @abstract
1847 * @param {Object} [data] Window opening data
1848 * @return {OO.ui.Process} Setup process
1850 OO.ui.Window.prototype.getReadyProcess = function () {
1851 return new OO.ui.Process();
1855 * Get a process for holding a window from use.
1857 * Each time the window is closed, this process will hold it from use in a particular context, based
1858 * on the `data` argument.
1860 * When you override this method, you can add additional setup steps to the process the parent
1861 * method provides using the 'first' and 'next' methods.
1863 * @abstract
1864 * @param {Object} [data] Window closing data
1865 * @return {OO.ui.Process} Hold process
1867 OO.ui.Window.prototype.getHoldProcess = function () {
1868 return new OO.ui.Process();
1872 * Get a process for tearing down a window after use.
1874 * Each time the window is closed this process will tear it down and do something with the user's
1875 * interactions within the window, based on the `data` argument.
1877 * When you override this method, you can add additional teardown steps to the process the parent
1878 * method provides using the 'first' and 'next' methods.
1880 * @abstract
1881 * @param {Object} [data] Window closing data
1882 * @return {OO.ui.Process} Teardown process
1884 OO.ui.Window.prototype.getTeardownProcess = function () {
1885 return new OO.ui.Process();
1889 * Set the window manager.
1891 * This will cause the window to initialize. Calling it more than once will cause an error.
1893 * @param {OO.ui.WindowManager} manager Manager for this window
1894 * @throws {Error} If called more than once
1895 * @chainable
1897 OO.ui.Window.prototype.setManager = function ( manager ) {
1898 if ( this.manager ) {
1899 throw new Error( 'Cannot set window manager, window already has a manager' );
1902 this.manager = manager;
1903 this.initialize();
1905 return this;
1909 * Set the window size.
1911 * @param {string} size Symbolic size name, e.g. 'small', 'medium', 'large', 'full'
1912 * @chainable
1914 OO.ui.Window.prototype.setSize = function ( size ) {
1915 this.size = size;
1916 this.updateSize();
1917 return this;
1921 * Update the window size.
1923 * @throws {Error} If not attached to a manager
1924 * @chainable
1926 OO.ui.Window.prototype.updateSize = function () {
1927 if ( !this.manager ) {
1928 throw new Error( 'Cannot update window size, must be attached to a manager' );
1931 this.manager.updateWindowSize( this );
1933 return this;
1937 * Set window dimensions.
1939 * Properties are applied to the frame container.
1941 * @param {Object} dim CSS dimension properties
1942 * @param {string|number} [dim.width] Width
1943 * @param {string|number} [dim.minWidth] Minimum width
1944 * @param {string|number} [dim.maxWidth] Maximum width
1945 * @param {string|number} [dim.width] Height, omit to set based on height of contents
1946 * @param {string|number} [dim.minWidth] Minimum height
1947 * @param {string|number} [dim.maxWidth] Maximum height
1948 * @chainable
1950 OO.ui.Window.prototype.setDimensions = function ( dim ) {
1951 var height,
1952 win = this,
1953 styleObj = this.$frame[ 0 ].style;
1955 // Calculate the height we need to set using the correct width
1956 if ( dim.height === undefined ) {
1957 this.withoutSizeTransitions( function () {
1958 var oldWidth = styleObj.width;
1959 win.$frame.css( 'width', dim.width || '' );
1960 height = win.getContentHeight();
1961 styleObj.width = oldWidth;
1962 } );
1963 } else {
1964 height = dim.height;
1967 this.$frame.css( {
1968 width: dim.width || '',
1969 minWidth: dim.minWidth || '',
1970 maxWidth: dim.maxWidth || '',
1971 height: height || '',
1972 minHeight: dim.minHeight || '',
1973 maxHeight: dim.maxHeight || ''
1974 } );
1976 return this;
1980 * Initialize window contents.
1982 * The first time the window is opened, #initialize is called so that changes to the window that
1983 * will persist between openings can be made. See #getSetupProcess for a way to make changes each
1984 * time the window opens.
1986 * @throws {Error} If not attached to a manager
1987 * @chainable
1989 OO.ui.Window.prototype.initialize = function () {
1990 if ( !this.manager ) {
1991 throw new Error( 'Cannot initialize window, must be attached to a manager' );
1994 // Properties
1995 this.$head = $( '<div>' );
1996 this.$body = $( '<div>' );
1997 this.$foot = $( '<div>' );
1998 this.$innerOverlay = $( '<div>' );
1999 this.dir = OO.ui.Element.static.getDir( this.$content ) || 'ltr';
2000 this.$document = $( this.getElementDocument() );
2002 // Events
2003 this.$element.on( 'mousedown', this.onMouseDown.bind( this ) );
2005 // Initialization
2006 this.$head.addClass( 'oo-ui-window-head' );
2007 this.$body.addClass( 'oo-ui-window-body' );
2008 this.$foot.addClass( 'oo-ui-window-foot' );
2009 this.$innerOverlay.addClass( 'oo-ui-window-inner-overlay' );
2010 this.$content.append( this.$head, this.$body, this.$foot, this.$innerOverlay );
2012 return this;
2016 * Open window.
2018 * This is a wrapper around calling {@link OO.ui.WindowManager#openWindow} on the window manager.
2019 * To do something each time the window opens, use #getSetupProcess or #getReadyProcess.
2021 * @param {Object} [data] Window opening data
2022 * @return {jQuery.Promise} Promise resolved when window is opened; when the promise is resolved the
2023 * first argument will be a promise which will be resolved when the window begins closing
2024 * @throws {Error} If not attached to a manager
2026 OO.ui.Window.prototype.open = function ( data ) {
2027 if ( !this.manager ) {
2028 throw new Error( 'Cannot open window, must be attached to a manager' );
2031 return this.manager.openWindow( this, data );
2035 * Close window.
2037 * This is a wrapper around calling OO.ui.WindowManager#closeWindow on the window manager.
2038 * To do something each time the window closes, use #getHoldProcess or #getTeardownProcess.
2040 * @param {Object} [data] Window closing data
2041 * @return {jQuery.Promise} Promise resolved when window is closed
2042 * @throws {Error} If not attached to a manager
2044 OO.ui.Window.prototype.close = function ( data ) {
2045 if ( !this.manager ) {
2046 throw new Error( 'Cannot close window, must be attached to a manager' );
2049 return this.manager.closeWindow( this, data );
2053 * Setup window.
2055 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2056 * by other systems.
2058 * @param {Object} [data] Window opening data
2059 * @return {jQuery.Promise} Promise resolved when window is setup
2061 OO.ui.Window.prototype.setup = function ( data ) {
2062 var win = this,
2063 deferred = $.Deferred();
2065 this.toggle( true );
2067 this.getSetupProcess( data ).execute().done( function () {
2068 // Force redraw by asking the browser to measure the elements' widths
2069 win.$element.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2070 win.$content.addClass( 'oo-ui-window-content-setup' ).width();
2071 deferred.resolve();
2072 } );
2074 return deferred.promise();
2078 * Ready window.
2080 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2081 * by other systems.
2083 * @param {Object} [data] Window opening data
2084 * @return {jQuery.Promise} Promise resolved when window is ready
2086 OO.ui.Window.prototype.ready = function ( data ) {
2087 var win = this,
2088 deferred = $.Deferred();
2090 this.$content.focus();
2091 this.getReadyProcess( data ).execute().done( function () {
2092 // Force redraw by asking the browser to measure the elements' widths
2093 win.$element.addClass( 'oo-ui-window-ready' ).width();
2094 win.$content.addClass( 'oo-ui-window-content-ready' ).width();
2095 deferred.resolve();
2096 } );
2098 return deferred.promise();
2102 * Hold window.
2104 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2105 * by other systems.
2107 * @param {Object} [data] Window closing data
2108 * @return {jQuery.Promise} Promise resolved when window is held
2110 OO.ui.Window.prototype.hold = function ( data ) {
2111 var win = this,
2112 deferred = $.Deferred();
2114 this.getHoldProcess( data ).execute().done( function () {
2115 // Get the focused element within the window's content
2116 var $focus = win.$content.find( OO.ui.Element.static.getDocument( win.$content ).activeElement );
2118 // Blur the focused element
2119 if ( $focus.length ) {
2120 $focus[ 0 ].blur();
2123 // Force redraw by asking the browser to measure the elements' widths
2124 win.$element.removeClass( 'oo-ui-window-ready' ).width();
2125 win.$content.removeClass( 'oo-ui-window-content-ready' ).width();
2126 deferred.resolve();
2127 } );
2129 return deferred.promise();
2133 * Teardown window.
2135 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2136 * by other systems.
2138 * @param {Object} [data] Window closing data
2139 * @return {jQuery.Promise} Promise resolved when window is torn down
2141 OO.ui.Window.prototype.teardown = function ( data ) {
2142 var win = this;
2144 return this.getTeardownProcess( data ).execute()
2145 .done( function () {
2146 // Force redraw by asking the browser to measure the elements' widths
2147 win.$element.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2148 win.$content.removeClass( 'oo-ui-window-content-setup' ).width();
2149 win.toggle( false );
2150 } );
2154 * The Dialog class serves as the base class for the other types of dialogs.
2155 * Unless extended to include controls, the rendered dialog box is a simple window
2156 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2157 * which opens, closes, and controls the presentation of the window. See the
2158 * [OOjs UI documentation on MediaWiki] [1] for more information.
2160 * @example
2161 * // A simple dialog window.
2162 * function MyDialog( config ) {
2163 * MyDialog.super.call( this, config );
2165 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2166 * MyDialog.prototype.initialize = function () {
2167 * MyDialog.super.prototype.initialize.call( this );
2168 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2169 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2170 * this.$body.append( this.content.$element );
2171 * };
2172 * MyDialog.prototype.getBodyHeight = function () {
2173 * return this.content.$element.outerHeight( true );
2174 * };
2175 * var myDialog = new MyDialog( {
2176 * size: 'medium'
2177 * } );
2178 * // Create and append a window manager, which opens and closes the window.
2179 * var windowManager = new OO.ui.WindowManager();
2180 * $( 'body' ).append( windowManager.$element );
2181 * windowManager.addWindows( [ myDialog ] );
2182 * // Open the window!
2183 * windowManager.openWindow( myDialog );
2185 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2187 * @abstract
2188 * @class
2189 * @extends OO.ui.Window
2190 * @mixins OO.ui.PendingElement
2192 * @constructor
2193 * @param {Object} [config] Configuration options
2195 OO.ui.Dialog = function OoUiDialog( config ) {
2196 // Parent constructor
2197 OO.ui.Dialog.super.call( this, config );
2199 // Mixin constructors
2200 OO.ui.PendingElement.call( this );
2202 // Properties
2203 this.actions = new OO.ui.ActionSet();
2204 this.attachedActions = [];
2205 this.currentAction = null;
2206 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
2208 // Events
2209 this.actions.connect( this, {
2210 click: 'onActionClick',
2211 resize: 'onActionResize',
2212 change: 'onActionsChange'
2213 } );
2215 // Initialization
2216 this.$element
2217 .addClass( 'oo-ui-dialog' )
2218 .attr( 'role', 'dialog' );
2221 /* Setup */
2223 OO.inheritClass( OO.ui.Dialog, OO.ui.Window );
2224 OO.mixinClass( OO.ui.Dialog, OO.ui.PendingElement );
2226 /* Static Properties */
2229 * Symbolic name of dialog.
2231 * @abstract
2232 * @static
2233 * @inheritable
2234 * @property {string}
2236 OO.ui.Dialog.static.name = '';
2239 * Dialog title.
2241 * @abstract
2242 * @static
2243 * @inheritable
2244 * @property {jQuery|string|Function} Label nodes, text or a function that returns nodes or text
2246 OO.ui.Dialog.static.title = '';
2249 * List of OO.ui.ActionWidget configuration options.
2251 * @static
2252 * inheritable
2253 * @property {Object[]}
2255 OO.ui.Dialog.static.actions = [];
2258 * Close dialog when the escape key is pressed.
2260 * @static
2261 * @abstract
2262 * @inheritable
2263 * @property {boolean}
2265 OO.ui.Dialog.static.escapable = true;
2267 /* Methods */
2270 * Handle frame document key down events.
2272 * @param {jQuery.Event} e Key down event
2274 OO.ui.Dialog.prototype.onDocumentKeyDown = function ( e ) {
2275 if ( e.which === OO.ui.Keys.ESCAPE ) {
2276 this.close();
2277 e.preventDefault();
2278 e.stopPropagation();
2283 * Handle action resized events.
2285 * @param {OO.ui.ActionWidget} action Action that was resized
2287 OO.ui.Dialog.prototype.onActionResize = function () {
2288 // Override in subclass
2292 * Handle action click events.
2294 * @param {OO.ui.ActionWidget} action Action that was clicked
2296 OO.ui.Dialog.prototype.onActionClick = function ( action ) {
2297 if ( !this.isPending() ) {
2298 this.currentAction = action;
2299 this.executeAction( action.getAction() );
2304 * Handle actions change event.
2306 OO.ui.Dialog.prototype.onActionsChange = function () {
2307 this.detachActions();
2308 if ( !this.isClosing() ) {
2309 this.attachActions();
2314 * Get set of actions.
2316 * @return {OO.ui.ActionSet}
2318 OO.ui.Dialog.prototype.getActions = function () {
2319 return this.actions;
2323 * Get a process for taking action.
2325 * When you override this method, you can add additional accept steps to the process the parent
2326 * method provides using the 'first' and 'next' methods.
2328 * @abstract
2329 * @param {string} [action] Symbolic name of action
2330 * @return {OO.ui.Process} Action process
2332 OO.ui.Dialog.prototype.getActionProcess = function ( action ) {
2333 return new OO.ui.Process()
2334 .next( function () {
2335 if ( !action ) {
2336 // An empty action always closes the dialog without data, which should always be
2337 // safe and make no changes
2338 this.close();
2340 }, this );
2344 * @inheritdoc
2346 * @param {Object} [data] Dialog opening data
2347 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use #static-title
2348 * @param {Object[]} [data.actions] List of OO.ui.ActionWidget configuration options for each
2349 * action item, omit to use #static-actions
2351 OO.ui.Dialog.prototype.getSetupProcess = function ( data ) {
2352 data = data || {};
2354 // Parent method
2355 return OO.ui.Dialog.super.prototype.getSetupProcess.call( this, data )
2356 .next( function () {
2357 var i, len,
2358 items = [],
2359 config = this.constructor.static,
2360 actions = data.actions !== undefined ? data.actions : config.actions;
2362 this.title.setLabel(
2363 data.title !== undefined ? data.title : this.constructor.static.title
2365 for ( i = 0, len = actions.length; i < len; i++ ) {
2366 items.push(
2367 new OO.ui.ActionWidget( actions[ i ] )
2370 this.actions.add( items );
2372 if ( this.constructor.static.escapable ) {
2373 this.$document.on( 'keydown', this.onDocumentKeyDownHandler );
2375 }, this );
2379 * @inheritdoc
2381 OO.ui.Dialog.prototype.getTeardownProcess = function ( data ) {
2382 // Parent method
2383 return OO.ui.Dialog.super.prototype.getTeardownProcess.call( this, data )
2384 .first( function () {
2385 if ( this.constructor.static.escapable ) {
2386 this.$document.off( 'keydown', this.onDocumentKeyDownHandler );
2389 this.actions.clear();
2390 this.currentAction = null;
2391 }, this );
2395 * @inheritdoc
2397 OO.ui.Dialog.prototype.initialize = function () {
2398 // Parent method
2399 OO.ui.Dialog.super.prototype.initialize.call( this );
2401 // Properties
2402 this.title = new OO.ui.LabelWidget();
2404 // Initialization
2405 this.$content.addClass( 'oo-ui-dialog-content' );
2406 this.setPendingElement( this.$head );
2410 * Attach action actions.
2412 OO.ui.Dialog.prototype.attachActions = function () {
2413 // Remember the list of potentially attached actions
2414 this.attachedActions = this.actions.get();
2418 * Detach action actions.
2420 * @chainable
2422 OO.ui.Dialog.prototype.detachActions = function () {
2423 var i, len;
2425 // Detach all actions that may have been previously attached
2426 for ( i = 0, len = this.attachedActions.length; i < len; i++ ) {
2427 this.attachedActions[ i ].$element.detach();
2429 this.attachedActions = [];
2433 * Execute an action.
2435 * @param {string} action Symbolic name of action to execute
2436 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
2438 OO.ui.Dialog.prototype.executeAction = function ( action ) {
2439 this.pushPending();
2440 return this.getActionProcess( action ).execute()
2441 .always( this.popPending.bind( this ) );
2445 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
2446 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
2447 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
2448 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
2449 * pertinent data and reused.
2451 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
2452 * `opened`, and `closing`, which represent the primary stages of the cycle:
2454 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
2455 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
2457 * - an `opening` event is emitted with an `opening` promise
2458 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
2459 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
2460 * window and its result executed
2461 * - a `setup` progress notification is emitted from the `opening` promise
2462 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
2463 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
2464 * window and its result executed
2465 * - a `ready` progress notification is emitted from the `opening` promise
2466 * - the `opening` promise is resolved with an `opened` promise
2468 * **Opened**: the window is now open.
2470 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
2471 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
2472 * to close the window.
2474 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
2475 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
2476 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
2477 * window and its result executed
2478 * - a `hold` progress notification is emitted from the `closing` promise
2479 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
2480 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
2481 * window and its result executed
2482 * - a `teardown` progress notification is emitted from the `closing` promise
2483 * - the `closing` promise is resolved. The window is now closed
2485 * See the [OOjs UI documentation on MediaWiki][1] for more information.
2487 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2489 * @class
2490 * @extends OO.ui.Element
2491 * @mixins OO.EventEmitter
2493 * @constructor
2494 * @param {Object} [config] Configuration options
2495 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
2496 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
2498 OO.ui.WindowManager = function OoUiWindowManager( config ) {
2499 // Configuration initialization
2500 config = config || {};
2502 // Parent constructor
2503 OO.ui.WindowManager.super.call( this, config );
2505 // Mixin constructors
2506 OO.EventEmitter.call( this );
2508 // Properties
2509 this.factory = config.factory;
2510 this.modal = config.modal === undefined || !!config.modal;
2511 this.windows = {};
2512 this.opening = null;
2513 this.opened = null;
2514 this.closing = null;
2515 this.preparingToOpen = null;
2516 this.preparingToClose = null;
2517 this.currentWindow = null;
2518 this.$ariaHidden = null;
2519 this.onWindowResizeTimeout = null;
2520 this.onWindowResizeHandler = this.onWindowResize.bind( this );
2521 this.afterWindowResizeHandler = this.afterWindowResize.bind( this );
2523 // Initialization
2524 this.$element
2525 .addClass( 'oo-ui-windowManager' )
2526 .toggleClass( 'oo-ui-windowManager-modal', this.modal );
2529 /* Setup */
2531 OO.inheritClass( OO.ui.WindowManager, OO.ui.Element );
2532 OO.mixinClass( OO.ui.WindowManager, OO.EventEmitter );
2534 /* Events */
2537 * Window is opening.
2539 * Fired when the window begins to be opened.
2541 * @event opening
2542 * @param {OO.ui.Window} win Window that's being opened
2543 * @param {jQuery.Promise} opening Promise resolved when window is opened; when the promise is
2544 * resolved the first argument will be a promise which will be resolved when the window begins
2545 * closing, the second argument will be the opening data; progress notifications will be fired on
2546 * the promise for `setup` and `ready` when those processes are completed respectively.
2547 * @param {Object} data Window opening data
2551 * Window is closing.
2553 * Fired when the window begins to be closed.
2555 * @event closing
2556 * @param {OO.ui.Window} win Window that's being closed
2557 * @param {jQuery.Promise} opening Promise resolved when window is closed; when the promise
2558 * is resolved the first argument will be a the closing data; progress notifications will be fired
2559 * on the promise for `hold` and `teardown` when those processes are completed respectively.
2560 * @param {Object} data Window closing data
2564 * Window was resized.
2566 * @event resize
2567 * @param {OO.ui.Window} win Window that was resized
2570 /* Static Properties */
2573 * Map of symbolic size names and CSS properties.
2575 * @static
2576 * @inheritable
2577 * @property {Object}
2579 OO.ui.WindowManager.static.sizes = {
2580 small: {
2581 width: 300
2583 medium: {
2584 width: 500
2586 large: {
2587 width: 700
2589 larger: {
2590 width: 900
2592 full: {
2593 // These can be non-numeric because they are never used in calculations
2594 width: '100%',
2595 height: '100%'
2600 * Symbolic name of default size.
2602 * Default size is used if the window's requested size is not recognized.
2604 * @static
2605 * @inheritable
2606 * @property {string}
2608 OO.ui.WindowManager.static.defaultSize = 'medium';
2610 /* Methods */
2613 * Handle window resize events.
2615 * @param {jQuery.Event} e Window resize event
2617 OO.ui.WindowManager.prototype.onWindowResize = function () {
2618 clearTimeout( this.onWindowResizeTimeout );
2619 this.onWindowResizeTimeout = setTimeout( this.afterWindowResizeHandler, 200 );
2623 * Handle window resize events.
2625 * @param {jQuery.Event} e Window resize event
2627 OO.ui.WindowManager.prototype.afterWindowResize = function () {
2628 if ( this.currentWindow ) {
2629 this.updateWindowSize( this.currentWindow );
2634 * Check if window is opening.
2636 * @return {boolean} Window is opening
2638 OO.ui.WindowManager.prototype.isOpening = function ( win ) {
2639 return win === this.currentWindow && !!this.opening && this.opening.state() === 'pending';
2643 * Check if window is closing.
2645 * @return {boolean} Window is closing
2647 OO.ui.WindowManager.prototype.isClosing = function ( win ) {
2648 return win === this.currentWindow && !!this.closing && this.closing.state() === 'pending';
2652 * Check if window is opened.
2654 * @return {boolean} Window is opened
2656 OO.ui.WindowManager.prototype.isOpened = function ( win ) {
2657 return win === this.currentWindow && !!this.opened && this.opened.state() === 'pending';
2661 * Check if a window is being managed.
2663 * @param {OO.ui.Window} win Window to check
2664 * @return {boolean} Window is being managed
2666 OO.ui.WindowManager.prototype.hasWindow = function ( win ) {
2667 var name;
2669 for ( name in this.windows ) {
2670 if ( this.windows[ name ] === win ) {
2671 return true;
2675 return false;
2679 * Get the number of milliseconds to wait between beginning opening and executing setup process.
2681 * @param {OO.ui.Window} win Window being opened
2682 * @param {Object} [data] Window opening data
2683 * @return {number} Milliseconds to wait
2685 OO.ui.WindowManager.prototype.getSetupDelay = function () {
2686 return 0;
2690 * Get the number of milliseconds to wait between finishing setup and executing ready process.
2692 * @param {OO.ui.Window} win Window being opened
2693 * @param {Object} [data] Window opening data
2694 * @return {number} Milliseconds to wait
2696 OO.ui.WindowManager.prototype.getReadyDelay = function () {
2697 return 0;
2701 * Get the number of milliseconds to wait between beginning closing and executing hold process.
2703 * @param {OO.ui.Window} win Window being closed
2704 * @param {Object} [data] Window closing data
2705 * @return {number} Milliseconds to wait
2707 OO.ui.WindowManager.prototype.getHoldDelay = function () {
2708 return 0;
2712 * Get the number of milliseconds to wait between finishing hold and executing teardown process.
2714 * @param {OO.ui.Window} win Window being closed
2715 * @param {Object} [data] Window closing data
2716 * @return {number} Milliseconds to wait
2718 OO.ui.WindowManager.prototype.getTeardownDelay = function () {
2719 return this.modal ? 250 : 0;
2723 * Get managed window by symbolic name.
2725 * If window is not yet instantiated, it will be instantiated and added automatically.
2727 * @param {string} name Symbolic window name
2728 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
2729 * @throws {Error} If the symbolic name is unrecognized by the factory
2730 * @throws {Error} If the symbolic name unrecognized as a managed window
2732 OO.ui.WindowManager.prototype.getWindow = function ( name ) {
2733 var deferred = $.Deferred(),
2734 win = this.windows[ name ];
2736 if ( !( win instanceof OO.ui.Window ) ) {
2737 if ( this.factory ) {
2738 if ( !this.factory.lookup( name ) ) {
2739 deferred.reject( new OO.ui.Error(
2740 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
2741 ) );
2742 } else {
2743 win = this.factory.create( name );
2744 this.addWindows( [ win ] );
2745 deferred.resolve( win );
2747 } else {
2748 deferred.reject( new OO.ui.Error(
2749 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
2750 ) );
2752 } else {
2753 deferred.resolve( win );
2756 return deferred.promise();
2760 * Get current window.
2762 * @return {OO.ui.Window|null} Currently opening/opened/closing window
2764 OO.ui.WindowManager.prototype.getCurrentWindow = function () {
2765 return this.currentWindow;
2769 * Open a window.
2771 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
2772 * @param {Object} [data] Window opening data
2773 * @return {jQuery.Promise} Promise resolved when window is done opening; see {@link #event-opening}
2774 * for more details about the `opening` promise
2775 * @fires opening
2777 OO.ui.WindowManager.prototype.openWindow = function ( win, data ) {
2778 var manager = this,
2779 opening = $.Deferred();
2781 // Argument handling
2782 if ( typeof win === 'string' ) {
2783 return this.getWindow( win ).then( function ( win ) {
2784 return manager.openWindow( win, data );
2785 } );
2788 // Error handling
2789 if ( !this.hasWindow( win ) ) {
2790 opening.reject( new OO.ui.Error(
2791 'Cannot open window: window is not attached to manager'
2792 ) );
2793 } else if ( this.preparingToOpen || this.opening || this.opened ) {
2794 opening.reject( new OO.ui.Error(
2795 'Cannot open window: another window is opening or open'
2796 ) );
2799 // Window opening
2800 if ( opening.state() !== 'rejected' ) {
2801 // If a window is currently closing, wait for it to complete
2802 this.preparingToOpen = $.when( this.closing );
2803 // Ensure handlers get called after preparingToOpen is set
2804 this.preparingToOpen.done( function () {
2805 if ( manager.modal ) {
2806 manager.toggleGlobalEvents( true );
2807 manager.toggleAriaIsolation( true );
2809 manager.currentWindow = win;
2810 manager.opening = opening;
2811 manager.preparingToOpen = null;
2812 manager.emit( 'opening', win, opening, data );
2813 setTimeout( function () {
2814 win.setup( data ).then( function () {
2815 manager.updateWindowSize( win );
2816 manager.opening.notify( { state: 'setup' } );
2817 setTimeout( function () {
2818 win.ready( data ).then( function () {
2819 manager.opening.notify( { state: 'ready' } );
2820 manager.opening = null;
2821 manager.opened = $.Deferred();
2822 opening.resolve( manager.opened.promise(), data );
2823 } );
2824 }, manager.getReadyDelay() );
2825 } );
2826 }, manager.getSetupDelay() );
2827 } );
2830 return opening.promise();
2834 * Close a window.
2836 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
2837 * @param {Object} [data] Window closing data
2838 * @return {jQuery.Promise} Promise resolved when window is done closing; see {@link #event-closing}
2839 * for more details about the `closing` promise
2840 * @throws {Error} If no window by that name is being managed
2841 * @fires closing
2843 OO.ui.WindowManager.prototype.closeWindow = function ( win, data ) {
2844 var manager = this,
2845 closing = $.Deferred(),
2846 opened;
2848 // Argument handling
2849 if ( typeof win === 'string' ) {
2850 win = this.windows[ win ];
2851 } else if ( !this.hasWindow( win ) ) {
2852 win = null;
2855 // Error handling
2856 if ( !win ) {
2857 closing.reject( new OO.ui.Error(
2858 'Cannot close window: window is not attached to manager'
2859 ) );
2860 } else if ( win !== this.currentWindow ) {
2861 closing.reject( new OO.ui.Error(
2862 'Cannot close window: window already closed with different data'
2863 ) );
2864 } else if ( this.preparingToClose || this.closing ) {
2865 closing.reject( new OO.ui.Error(
2866 'Cannot close window: window already closing with different data'
2867 ) );
2870 // Window closing
2871 if ( closing.state() !== 'rejected' ) {
2872 // If the window is currently opening, close it when it's done
2873 this.preparingToClose = $.when( this.opening );
2874 // Ensure handlers get called after preparingToClose is set
2875 this.preparingToClose.done( function () {
2876 manager.closing = closing;
2877 manager.preparingToClose = null;
2878 manager.emit( 'closing', win, closing, data );
2879 opened = manager.opened;
2880 manager.opened = null;
2881 opened.resolve( closing.promise(), data );
2882 setTimeout( function () {
2883 win.hold( data ).then( function () {
2884 closing.notify( { state: 'hold' } );
2885 setTimeout( function () {
2886 win.teardown( data ).then( function () {
2887 closing.notify( { state: 'teardown' } );
2888 if ( manager.modal ) {
2889 manager.toggleGlobalEvents( false );
2890 manager.toggleAriaIsolation( false );
2892 manager.closing = null;
2893 manager.currentWindow = null;
2894 closing.resolve( data );
2895 } );
2896 }, manager.getTeardownDelay() );
2897 } );
2898 }, manager.getHoldDelay() );
2899 } );
2902 return closing.promise();
2906 * Add windows.
2908 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows Windows to add
2909 * @throws {Error} If one of the windows being added without an explicit symbolic name does not have
2910 * a statically configured symbolic name
2912 OO.ui.WindowManager.prototype.addWindows = function ( windows ) {
2913 var i, len, win, name, list;
2915 if ( Array.isArray( windows ) ) {
2916 // Convert to map of windows by looking up symbolic names from static configuration
2917 list = {};
2918 for ( i = 0, len = windows.length; i < len; i++ ) {
2919 name = windows[ i ].constructor.static.name;
2920 if ( typeof name !== 'string' ) {
2921 throw new Error( 'Cannot add window' );
2923 list[ name ] = windows[ i ];
2925 } else if ( OO.isPlainObject( windows ) ) {
2926 list = windows;
2929 // Add windows
2930 for ( name in list ) {
2931 win = list[ name ];
2932 this.windows[ name ] = win.toggle( false );
2933 this.$element.append( win.$element );
2934 win.setManager( this );
2939 * Remove windows.
2941 * Windows will be closed before they are removed.
2943 * @param {string[]} names Symbolic names of windows to remove
2944 * @return {jQuery.Promise} Promise resolved when window is closed and removed
2945 * @throws {Error} If windows being removed are not being managed
2947 OO.ui.WindowManager.prototype.removeWindows = function ( names ) {
2948 var i, len, win, name, cleanupWindow,
2949 manager = this,
2950 promises = [],
2951 cleanup = function ( name, win ) {
2952 delete manager.windows[ name ];
2953 win.$element.detach();
2956 for ( i = 0, len = names.length; i < len; i++ ) {
2957 name = names[ i ];
2958 win = this.windows[ name ];
2959 if ( !win ) {
2960 throw new Error( 'Cannot remove window' );
2962 cleanupWindow = cleanup.bind( null, name, win );
2963 promises.push( this.closeWindow( name ).then( cleanupWindow, cleanupWindow ) );
2966 return $.when.apply( $, promises );
2970 * Remove all windows.
2972 * Windows will be closed before they are removed.
2974 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
2976 OO.ui.WindowManager.prototype.clearWindows = function () {
2977 return this.removeWindows( Object.keys( this.windows ) );
2981 * Set dialog size.
2983 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
2985 * @chainable
2987 OO.ui.WindowManager.prototype.updateWindowSize = function ( win ) {
2988 // Bypass for non-current, and thus invisible, windows
2989 if ( win !== this.currentWindow ) {
2990 return;
2993 var viewport = OO.ui.Element.static.getDimensions( win.getElementWindow() ),
2994 sizes = this.constructor.static.sizes,
2995 size = win.getSize();
2997 if ( !sizes[ size ] ) {
2998 size = this.constructor.static.defaultSize;
3000 if ( size !== 'full' && viewport.rect.right - viewport.rect.left < sizes[ size ].width ) {
3001 size = 'full';
3004 this.$element.toggleClass( 'oo-ui-windowManager-fullscreen', size === 'full' );
3005 this.$element.toggleClass( 'oo-ui-windowManager-floating', size !== 'full' );
3006 win.setDimensions( sizes[ size ] );
3008 this.emit( 'resize', win );
3010 return this;
3014 * Bind or unbind global events for scrolling.
3016 * @param {boolean} [on] Bind global events
3017 * @chainable
3019 OO.ui.WindowManager.prototype.toggleGlobalEvents = function ( on ) {
3020 on = on === undefined ? !!this.globalEvents : !!on;
3022 if ( on ) {
3023 if ( !this.globalEvents ) {
3024 $( this.getElementWindow() ).on( {
3025 // Start listening for top-level window dimension changes
3026 'orientationchange resize': this.onWindowResizeHandler
3027 } );
3028 $( this.getElementDocument().body ).css( 'overflow', 'hidden' );
3029 this.globalEvents = true;
3031 } else if ( this.globalEvents ) {
3032 $( this.getElementWindow() ).off( {
3033 // Stop listening for top-level window dimension changes
3034 'orientationchange resize': this.onWindowResizeHandler
3035 } );
3036 $( this.getElementDocument().body ).css( 'overflow', '' );
3037 this.globalEvents = false;
3040 return this;
3044 * Toggle screen reader visibility of content other than the window manager.
3046 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3047 * @chainable
3049 OO.ui.WindowManager.prototype.toggleAriaIsolation = function ( isolate ) {
3050 isolate = isolate === undefined ? !this.$ariaHidden : !!isolate;
3052 if ( isolate ) {
3053 if ( !this.$ariaHidden ) {
3054 // Hide everything other than the window manager from screen readers
3055 this.$ariaHidden = $( 'body' )
3056 .children()
3057 .not( this.$element.parentsUntil( 'body' ).last() )
3058 .attr( 'aria-hidden', '' );
3060 } else if ( this.$ariaHidden ) {
3061 // Restore screen reader visibility
3062 this.$ariaHidden.removeAttr( 'aria-hidden' );
3063 this.$ariaHidden = null;
3066 return this;
3070 * Destroy window manager.
3072 OO.ui.WindowManager.prototype.destroy = function () {
3073 this.toggleGlobalEvents( false );
3074 this.toggleAriaIsolation( false );
3075 this.clearWindows();
3076 this.$element.remove();
3080 * @class
3082 * @constructor
3083 * @param {string|jQuery} message Description of error
3084 * @param {Object} [config] Configuration options
3085 * @cfg {boolean} [recoverable=true] Error is recoverable
3086 * @cfg {boolean} [warning=false] Whether this error is a warning or not.
3088 OO.ui.Error = function OoUiError( message, config ) {
3089 // Allow passing positional parameters inside the config object
3090 if ( OO.isPlainObject( message ) && config === undefined ) {
3091 config = message;
3092 message = config.message;
3095 // Configuration initialization
3096 config = config || {};
3098 // Properties
3099 this.message = message instanceof jQuery ? message : String( message );
3100 this.recoverable = config.recoverable === undefined || !!config.recoverable;
3101 this.warning = !!config.warning;
3104 /* Setup */
3106 OO.initClass( OO.ui.Error );
3108 /* Methods */
3111 * Check if error can be recovered from.
3113 * @return {boolean} Error is recoverable
3115 OO.ui.Error.prototype.isRecoverable = function () {
3116 return this.recoverable;
3120 * Check if the error is a warning
3122 * @return {boolean} Error is warning
3124 OO.ui.Error.prototype.isWarning = function () {
3125 return this.warning;
3129 * Get error message as DOM nodes.
3131 * @return {jQuery} Error message in DOM nodes
3133 OO.ui.Error.prototype.getMessage = function () {
3134 return this.message instanceof jQuery ?
3135 this.message.clone() :
3136 $( '<div>' ).text( this.message ).contents();
3140 * Get error message as text.
3142 * @return {string} Error message
3144 OO.ui.Error.prototype.getMessageText = function () {
3145 return this.message instanceof jQuery ? this.message.text() : this.message;
3149 * Wraps an HTML snippet for use with configuration values which default
3150 * to strings. This bypasses the default html-escaping done to string
3151 * values.
3153 * @class
3155 * @constructor
3156 * @param {string} [content] HTML content
3158 OO.ui.HtmlSnippet = function OoUiHtmlSnippet( content ) {
3159 // Properties
3160 this.content = content;
3163 /* Setup */
3165 OO.initClass( OO.ui.HtmlSnippet );
3167 /* Methods */
3170 * Render into HTML.
3172 * @return {string} Unchanged HTML snippet.
3174 OO.ui.HtmlSnippet.prototype.toString = function () {
3175 return this.content;
3179 * Reconstitute a JavaScript object corresponding to a widget created
3180 * by the PHP implementation.
3182 * @member OO.ui
3183 * @param {string|HTMLElement|jQuery} idOrNode
3184 * A DOM id (if a string) or node for the widget to infuse.
3185 * @return {OO.ui.Element}
3186 * The `OO.ui.Element` corresponding to this (infusable) document node.
3187 * For `Tag` objects emitted on the HTML side (used occasionally for content)
3188 * the value returned is a newly-created Element wrapping around the existing
3189 * DOM node.
3191 OO.ui.infuse = function ( idOrNode, dontReplace ) {
3192 // look for a cached result of a previous infusion.
3193 var id, $elem, data, cls, obj;
3194 if ( typeof idOrNode === 'string' ) {
3195 id = idOrNode;
3196 $elem = $( document.getElementById( id ) );
3197 } else {
3198 $elem = $( idOrNode );
3199 id = $elem.attr( 'id' );
3201 data = $elem.data( 'ooui-infused' );
3202 if ( data ) {
3203 // cached!
3204 if ( data === true ) {
3205 throw new Error( 'Circular dependency! ' + id );
3207 return data;
3209 if ( !$elem.length ) {
3210 throw new Error( 'Widget not found: ' + id );
3212 data = $elem.attr( 'data-ooui' );
3213 if ( !data ) {
3214 throw new Error( 'No infusion data found: ' + id );
3216 try {
3217 data = $.parseJSON( data );
3218 } catch ( _ ) {
3219 data = null;
3221 if ( !( data && data._ ) ) {
3222 throw new Error( 'No valid infusion data found: ' + id );
3224 if ( data._ === 'Tag' ) {
3225 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
3226 return new OO.ui.Element( { $element: $elem } );
3228 cls = OO.ui[data._];
3229 if ( !cls ) {
3230 throw new Error( 'Unknown widget type: ' + id );
3232 $elem.data( 'ooui-infused', true ); // prevent loops
3233 data.id = id; // implicit
3234 data = OO.copy( data, null, function deserialize( value ) {
3235 if ( OO.isPlainObject( value ) ) {
3236 if ( value.tag ) {
3237 return OO.ui.infuse( value.tag, 'rebuilding' );
3239 if ( value.html ) {
3240 return new OO.ui.HtmlSnippet( value.html );
3243 } );
3244 // jscs:disable requireCapitalizedConstructors
3245 obj = new cls( data ); // rebuild widget
3246 // now replace old DOM with this new DOM.
3247 if ( !dontReplace ) {
3248 $elem.replaceWith( obj.$element );
3250 obj.$element.data( 'ooui-infused', obj );
3251 // set the 'data-ooui' attribute so we can identify infused widgets
3252 obj.$element.attr( 'data-ooui', '' );
3253 return obj;
3257 * A list of functions, called in sequence.
3259 * If a function added to a process returns boolean false the process will stop; if it returns an
3260 * object with a `promise` method the process will use the promise to either continue to the next
3261 * step when the promise is resolved or stop when the promise is rejected.
3263 * @class
3265 * @constructor
3266 * @param {number|jQuery.Promise|Function} step Time to wait, promise to wait for or function to
3267 * call, see #createStep for more information
3268 * @param {Object} [context=null] Context to call the step function in, ignored if step is a number
3269 * or a promise
3270 * @return {Object} Step object, with `callback` and `context` properties
3272 OO.ui.Process = function ( step, context ) {
3273 // Properties
3274 this.steps = [];
3276 // Initialization
3277 if ( step !== undefined ) {
3278 this.next( step, context );
3282 /* Setup */
3284 OO.initClass( OO.ui.Process );
3286 /* Methods */
3289 * Start the process.
3291 * @return {jQuery.Promise} Promise that is resolved when all steps have completed or rejected when
3292 * any of the steps return boolean false or a promise which gets rejected; upon stopping the
3293 * process, the remaining steps will not be taken
3295 OO.ui.Process.prototype.execute = function () {
3296 var i, len, promise;
3299 * Continue execution.
3301 * @ignore
3302 * @param {Array} step A function and the context it should be called in
3303 * @return {Function} Function that continues the process
3305 function proceed( step ) {
3306 return function () {
3307 // Execute step in the correct context
3308 var deferred,
3309 result = step.callback.call( step.context );
3311 if ( result === false ) {
3312 // Use rejected promise for boolean false results
3313 return $.Deferred().reject( [] ).promise();
3315 if ( typeof result === 'number' ) {
3316 if ( result < 0 ) {
3317 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3319 // Use a delayed promise for numbers, expecting them to be in milliseconds
3320 deferred = $.Deferred();
3321 setTimeout( deferred.resolve, result );
3322 return deferred.promise();
3324 if ( result instanceof OO.ui.Error ) {
3325 // Use rejected promise for error
3326 return $.Deferred().reject( [ result ] ).promise();
3328 if ( Array.isArray( result ) && result.length && result[ 0 ] instanceof OO.ui.Error ) {
3329 // Use rejected promise for list of errors
3330 return $.Deferred().reject( result ).promise();
3332 // Duck-type the object to see if it can produce a promise
3333 if ( result && $.isFunction( result.promise ) ) {
3334 // Use a promise generated from the result
3335 return result.promise();
3337 // Use resolved promise for other results
3338 return $.Deferred().resolve().promise();
3342 if ( this.steps.length ) {
3343 // Generate a chain reaction of promises
3344 promise = proceed( this.steps[ 0 ] )();
3345 for ( i = 1, len = this.steps.length; i < len; i++ ) {
3346 promise = promise.then( proceed( this.steps[ i ] ) );
3348 } else {
3349 promise = $.Deferred().resolve().promise();
3352 return promise;
3356 * Create a process step.
3358 * @private
3359 * @param {number|jQuery.Promise|Function} step
3361 * - Number of milliseconds to wait; or
3362 * - Promise to wait to be resolved; or
3363 * - Function to execute
3364 * - If it returns boolean false the process will stop
3365 * - If it returns an object with a `promise` method the process will use the promise to either
3366 * continue to the next step when the promise is resolved or stop when the promise is rejected
3367 * - If it returns a number, the process will wait for that number of milliseconds before
3368 * proceeding
3369 * @param {Object} [context=null] Context to call the step function in, ignored if step is a number
3370 * or a promise
3371 * @return {Object} Step object, with `callback` and `context` properties
3373 OO.ui.Process.prototype.createStep = function ( step, context ) {
3374 if ( typeof step === 'number' || $.isFunction( step.promise ) ) {
3375 return {
3376 callback: function () {
3377 return step;
3379 context: null
3382 if ( $.isFunction( step ) ) {
3383 return {
3384 callback: step,
3385 context: context
3388 throw new Error( 'Cannot create process step: number, promise or function expected' );
3392 * Add step to the beginning of the process.
3394 * @inheritdoc #createStep
3395 * @return {OO.ui.Process} this
3396 * @chainable
3398 OO.ui.Process.prototype.first = function ( step, context ) {
3399 this.steps.unshift( this.createStep( step, context ) );
3400 return this;
3404 * Add step to the end of the process.
3406 * @inheritdoc #createStep
3407 * @return {OO.ui.Process} this
3408 * @chainable
3410 OO.ui.Process.prototype.next = function ( step, context ) {
3411 this.steps.push( this.createStep( step, context ) );
3412 return this;
3416 * Factory for tools.
3418 * @class
3419 * @extends OO.Factory
3420 * @constructor
3422 OO.ui.ToolFactory = function OoUiToolFactory() {
3423 // Parent constructor
3424 OO.ui.ToolFactory.super.call( this );
3427 /* Setup */
3429 OO.inheritClass( OO.ui.ToolFactory, OO.Factory );
3431 /* Methods */
3434 * Get tools from the factory
3436 * @param {Array} include Included tools
3437 * @param {Array} exclude Excluded tools
3438 * @param {Array} promote Promoted tools
3439 * @param {Array} demote Demoted tools
3440 * @return {string[]} List of tools
3442 OO.ui.ToolFactory.prototype.getTools = function ( include, exclude, promote, demote ) {
3443 var i, len, included, promoted, demoted,
3444 auto = [],
3445 used = {};
3447 // Collect included and not excluded tools
3448 included = OO.simpleArrayDifference( this.extract( include ), this.extract( exclude ) );
3450 // Promotion
3451 promoted = this.extract( promote, used );
3452 demoted = this.extract( demote, used );
3454 // Auto
3455 for ( i = 0, len = included.length; i < len; i++ ) {
3456 if ( !used[ included[ i ] ] ) {
3457 auto.push( included[ i ] );
3461 return promoted.concat( auto ).concat( demoted );
3465 * Get a flat list of names from a list of names or groups.
3467 * Tools can be specified in the following ways:
3469 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
3470 * - All tools in a group: `{ group: 'group-name' }`
3471 * - All tools: `'*'`
3473 * @private
3474 * @param {Array|string} collection List of tools
3475 * @param {Object} [used] Object with names that should be skipped as properties; extracted
3476 * names will be added as properties
3477 * @return {string[]} List of extracted names
3479 OO.ui.ToolFactory.prototype.extract = function ( collection, used ) {
3480 var i, len, item, name, tool,
3481 names = [];
3483 if ( collection === '*' ) {
3484 for ( name in this.registry ) {
3485 tool = this.registry[ name ];
3486 if (
3487 // Only add tools by group name when auto-add is enabled
3488 tool.static.autoAddToCatchall &&
3489 // Exclude already used tools
3490 ( !used || !used[ name ] )
3492 names.push( name );
3493 if ( used ) {
3494 used[ name ] = true;
3498 } else if ( Array.isArray( collection ) ) {
3499 for ( i = 0, len = collection.length; i < len; i++ ) {
3500 item = collection[ i ];
3501 // Allow plain strings as shorthand for named tools
3502 if ( typeof item === 'string' ) {
3503 item = { name: item };
3505 if ( OO.isPlainObject( item ) ) {
3506 if ( item.group ) {
3507 for ( name in this.registry ) {
3508 tool = this.registry[ name ];
3509 if (
3510 // Include tools with matching group
3511 tool.static.group === item.group &&
3512 // Only add tools by group name when auto-add is enabled
3513 tool.static.autoAddToGroup &&
3514 // Exclude already used tools
3515 ( !used || !used[ name ] )
3517 names.push( name );
3518 if ( used ) {
3519 used[ name ] = true;
3523 // Include tools with matching name and exclude already used tools
3524 } else if ( item.name && ( !used || !used[ item.name ] ) ) {
3525 names.push( item.name );
3526 if ( used ) {
3527 used[ item.name ] = true;
3533 return names;
3537 * Factory for tool groups.
3539 * @class
3540 * @extends OO.Factory
3541 * @constructor
3543 OO.ui.ToolGroupFactory = function OoUiToolGroupFactory() {
3544 // Parent constructor
3545 OO.Factory.call( this );
3547 var i, l,
3548 defaultClasses = this.constructor.static.getDefaultClasses();
3550 // Register default toolgroups
3551 for ( i = 0, l = defaultClasses.length; i < l; i++ ) {
3552 this.register( defaultClasses[ i ] );
3556 /* Setup */
3558 OO.inheritClass( OO.ui.ToolGroupFactory, OO.Factory );
3560 /* Static Methods */
3563 * Get a default set of classes to be registered on construction
3565 * @return {Function[]} Default classes
3567 OO.ui.ToolGroupFactory.static.getDefaultClasses = function () {
3568 return [
3569 OO.ui.BarToolGroup,
3570 OO.ui.ListToolGroup,
3571 OO.ui.MenuToolGroup
3576 * Theme logic.
3578 * @abstract
3579 * @class
3581 * @constructor
3582 * @param {Object} [config] Configuration options
3584 OO.ui.Theme = function OoUiTheme( config ) {
3585 // Configuration initialization
3586 config = config || {};
3589 /* Setup */
3591 OO.initClass( OO.ui.Theme );
3593 /* Methods */
3596 * Get a list of classes to be applied to a widget.
3598 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
3599 * otherwise state transitions will not work properly.
3601 * @param {OO.ui.Element} element Element for which to get classes
3602 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
3604 OO.ui.Theme.prototype.getElementClasses = function ( /* element */ ) {
3605 return { on: [], off: [] };
3609 * Update CSS classes provided by the theme.
3611 * For elements with theme logic hooks, this should be called any time there's a state change.
3613 * @param {OO.ui.Element} element Element for which to update classes
3614 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
3616 OO.ui.Theme.prototype.updateElementClasses = function ( element ) {
3617 var classes = this.getElementClasses( element );
3619 element.$element
3620 .removeClass( classes.off.join( ' ' ) )
3621 .addClass( classes.on.join( ' ' ) );
3625 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
3626 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
3627 * order in which users will navigate through the focusable elements via the "tab" key.
3629 * @example
3630 * // TabIndexedElement is mixed into the ButtonWidget class
3631 * // to provide a tabIndex property.
3632 * var button1 = new OO.ui.ButtonWidget( {
3633 * label : 'fourth',
3634 * tabIndex : 4
3635 * } );
3636 * var button2 = new OO.ui.ButtonWidget( {
3637 * label : 'second',
3638 * tabIndex : 2
3639 * } );
3640 * var button3 = new OO.ui.ButtonWidget( {
3641 * label : 'third',
3642 * tabIndex : 3
3643 * } );
3644 * var button4 = new OO.ui.ButtonWidget( {
3645 * label : 'first',
3646 * tabIndex : 1
3647 * } );
3648 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
3650 * @abstract
3651 * @class
3653 * @constructor
3654 * @param {Object} [config] Configuration options
3655 * @cfg {jQuery} [$tabIndexed] tabIndexed node, assigned to #$tabIndexed, omit to use #$element
3656 * @cfg {number|null} [tabIndex=0] Tab index value. Use 0 to use default ordering, use -1 to
3657 * prevent tab focusing, use null to suppress the `tabindex` attribute.
3659 OO.ui.TabIndexedElement = function OoUiTabIndexedElement( config ) {
3660 // Configuration initialization
3661 config = $.extend( { tabIndex: 0 }, config );
3663 // Properties
3664 this.$tabIndexed = null;
3665 this.tabIndex = null;
3667 // Events
3668 this.connect( this, { disable: 'onDisable' } );
3670 // Initialization
3671 this.setTabIndex( config.tabIndex );
3672 this.setTabIndexedElement( config.$tabIndexed || this.$element );
3675 /* Setup */
3677 OO.initClass( OO.ui.TabIndexedElement );
3679 /* Methods */
3682 * Set the element with `tabindex` attribute.
3684 * If an element is already set, it will be cleaned up before setting up the new element.
3686 * @param {jQuery} $tabIndexed Element to set tab index on
3687 * @chainable
3689 OO.ui.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) {
3690 var tabIndex = this.tabIndex;
3691 // Remove attributes from old $tabIndexed
3692 this.setTabIndex( null );
3693 // Force update of new $tabIndexed
3694 this.$tabIndexed = $tabIndexed;
3695 this.tabIndex = tabIndex;
3696 return this.updateTabIndex();
3700 * Set tab index value.
3702 * @param {number|null} tabIndex Tab index value or null for no tab index
3703 * @chainable
3705 OO.ui.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) {
3706 tabIndex = typeof tabIndex === 'number' ? tabIndex : null;
3708 if ( this.tabIndex !== tabIndex ) {
3709 this.tabIndex = tabIndex;
3710 this.updateTabIndex();
3713 return this;
3717 * Update the `tabindex` attribute, in case of changes to tab index or
3718 * disabled state.
3720 * @chainable
3722 OO.ui.TabIndexedElement.prototype.updateTabIndex = function () {
3723 if ( this.$tabIndexed ) {
3724 if ( this.tabIndex !== null ) {
3725 // Do not index over disabled elements
3726 this.$tabIndexed.attr( {
3727 tabindex: this.isDisabled() ? -1 : this.tabIndex,
3728 // ChromeVox and NVDA do not seem to inherit this from parent elements
3729 'aria-disabled': this.isDisabled().toString()
3730 } );
3731 } else {
3732 this.$tabIndexed.removeAttr( 'tabindex aria-disabled' );
3735 return this;
3739 * Handle disable events.
3741 * @private
3742 * @param {boolean} disabled Element is disabled
3744 OO.ui.TabIndexedElement.prototype.onDisable = function () {
3745 this.updateTabIndex();
3749 * Get tab index value.
3751 * @return {number|null} Tab index value
3753 OO.ui.TabIndexedElement.prototype.getTabIndex = function () {
3754 return this.tabIndex;
3758 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
3759 * interface element that can be configured with access keys for accessibility.
3760 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
3762 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
3763 * @abstract
3764 * @class
3766 * @constructor
3767 * @param {Object} [config] Configuration options
3768 * @cfg {jQuery} [$button] Button node, assigned to #$button, omit to use a generated `<a>`
3769 * @cfg {boolean} [framed=true] Render button with a frame
3770 * @cfg {string} [accessKey] Button's access key
3772 OO.ui.ButtonElement = function OoUiButtonElement( config ) {
3773 // Configuration initialization
3774 config = config || {};
3776 // Properties
3777 this.$button = config.$button || $( '<a>' );
3778 this.framed = null;
3779 this.accessKey = null;
3780 this.active = false;
3781 this.onMouseUpHandler = this.onMouseUp.bind( this );
3782 this.onMouseDownHandler = this.onMouseDown.bind( this );
3783 this.onKeyDownHandler = this.onKeyDown.bind( this );
3784 this.onKeyUpHandler = this.onKeyUp.bind( this );
3785 this.onClickHandler = this.onClick.bind( this );
3786 this.onKeyPressHandler = this.onKeyPress.bind( this );
3788 // Initialization
3789 this.$element.addClass( 'oo-ui-buttonElement' );
3790 this.toggleFramed( config.framed === undefined || config.framed );
3791 this.setAccessKey( config.accessKey );
3792 this.setButtonElement( this.$button );
3795 /* Setup */
3797 OO.initClass( OO.ui.ButtonElement );
3799 /* Static Properties */
3802 * Cancel mouse down events.
3804 * @static
3805 * @inheritable
3806 * @property {boolean}
3808 OO.ui.ButtonElement.static.cancelButtonMouseDownEvents = true;
3810 /* Events */
3813 * @event click
3816 /* Methods */
3819 * Set the button element.
3821 * If an element is already set, it will be cleaned up before setting up the new element.
3823 * @param {jQuery} $button Element to use as button
3825 OO.ui.ButtonElement.prototype.setButtonElement = function ( $button ) {
3826 if ( this.$button ) {
3827 this.$button
3828 .removeClass( 'oo-ui-buttonElement-button' )
3829 .removeAttr( 'role accesskey' )
3830 .off( {
3831 mousedown: this.onMouseDownHandler,
3832 keydown: this.onKeyDownHandler,
3833 click: this.onClickHandler,
3834 keypress: this.onKeyPressHandler
3835 } );
3838 this.$button = $button
3839 .addClass( 'oo-ui-buttonElement-button' )
3840 .attr( { role: 'button', accesskey: this.accessKey } )
3841 .on( {
3842 mousedown: this.onMouseDownHandler,
3843 keydown: this.onKeyDownHandler,
3844 click: this.onClickHandler,
3845 keypress: this.onKeyPressHandler
3846 } );
3850 * Handles mouse down events.
3852 * @protected
3853 * @param {jQuery.Event} e Mouse down event
3855 OO.ui.ButtonElement.prototype.onMouseDown = function ( e ) {
3856 if ( this.isDisabled() || e.which !== 1 ) {
3857 return;
3859 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
3860 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
3861 // reliably remove the pressed class
3862 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler, true );
3863 // Prevent change of focus unless specifically configured otherwise
3864 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
3865 return false;
3870 * Handles mouse up events.
3872 * @protected
3873 * @param {jQuery.Event} e Mouse up event
3875 OO.ui.ButtonElement.prototype.onMouseUp = function ( e ) {
3876 if ( this.isDisabled() || e.which !== 1 ) {
3877 return;
3879 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
3880 // Stop listening for mouseup, since we only needed this once
3881 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler, true );
3885 * Handles mouse click events.
3887 * @protected
3888 * @param {jQuery.Event} e Mouse click event
3889 * @fires click
3891 OO.ui.ButtonElement.prototype.onClick = function ( e ) {
3892 if ( !this.isDisabled() && e.which === 1 ) {
3893 this.emit( 'click' );
3895 return false;
3899 * Handles key down events.
3901 * @protected
3902 * @param {jQuery.Event} e Key down event
3904 OO.ui.ButtonElement.prototype.onKeyDown = function ( e ) {
3905 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
3906 return;
3908 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
3909 // Run the keyup handler no matter where the key is when the button is let go, so we can
3910 // reliably remove the pressed class
3911 this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler, true );
3915 * Handles key up events.
3917 * @protected
3918 * @param {jQuery.Event} e Key up event
3920 OO.ui.ButtonElement.prototype.onKeyUp = function ( e ) {
3921 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
3922 return;
3924 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
3925 // Stop listening for keyup, since we only needed this once
3926 this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler, true );
3930 * Handles key press events.
3932 * @protected
3933 * @param {jQuery.Event} e Key press event
3934 * @fires click
3936 OO.ui.ButtonElement.prototype.onKeyPress = function ( e ) {
3937 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
3938 this.emit( 'click' );
3940 return false;
3944 * Check if button has a frame.
3946 * @return {boolean} Button is framed
3948 OO.ui.ButtonElement.prototype.isFramed = function () {
3949 return this.framed;
3953 * Toggle frame.
3955 * @param {boolean} [framed] Make button framed, omit to toggle
3956 * @chainable
3958 OO.ui.ButtonElement.prototype.toggleFramed = function ( framed ) {
3959 framed = framed === undefined ? !this.framed : !!framed;
3960 if ( framed !== this.framed ) {
3961 this.framed = framed;
3962 this.$element
3963 .toggleClass( 'oo-ui-buttonElement-frameless', !framed )
3964 .toggleClass( 'oo-ui-buttonElement-framed', framed );
3965 this.updateThemeClasses();
3968 return this;
3972 * Set access key.
3974 * @param {string} accessKey Button's access key, use empty string to remove
3975 * @chainable
3977 OO.ui.ButtonElement.prototype.setAccessKey = function ( accessKey ) {
3978 accessKey = typeof accessKey === 'string' && accessKey.length ? accessKey : null;
3980 if ( this.accessKey !== accessKey ) {
3981 if ( this.$button ) {
3982 if ( accessKey !== null ) {
3983 this.$button.attr( 'accesskey', accessKey );
3984 } else {
3985 this.$button.removeAttr( 'accesskey' );
3988 this.accessKey = accessKey;
3991 return this;
3995 * Set active state.
3997 * @param {boolean} [value] Make button active
3998 * @chainable
4000 OO.ui.ButtonElement.prototype.setActive = function ( value ) {
4001 this.$element.toggleClass( 'oo-ui-buttonElement-active', !!value );
4002 return this;
4006 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4007 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4008 * items from the group is done through the interface the class provides.
4009 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4011 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4013 * @abstract
4014 * @class
4016 * @constructor
4017 * @param {Object} [config] Configuration options
4018 * @cfg {jQuery} [$group] Container node, assigned to #$group, omit to use a generated `<div>`
4020 OO.ui.GroupElement = function OoUiGroupElement( config ) {
4021 // Configuration initialization
4022 config = config || {};
4024 // Properties
4025 this.$group = null;
4026 this.items = [];
4027 this.aggregateItemEvents = {};
4029 // Initialization
4030 this.setGroupElement( config.$group || $( '<div>' ) );
4033 /* Methods */
4036 * Set the group element.
4038 * If an element is already set, items will be moved to the new element.
4040 * @param {jQuery} $group Element to use as group
4042 OO.ui.GroupElement.prototype.setGroupElement = function ( $group ) {
4043 var i, len;
4045 this.$group = $group;
4046 for ( i = 0, len = this.items.length; i < len; i++ ) {
4047 this.$group.append( this.items[ i ].$element );
4052 * Check if there are no items.
4054 * @return {boolean} Group is empty
4056 OO.ui.GroupElement.prototype.isEmpty = function () {
4057 return !this.items.length;
4061 * Get items.
4063 * @return {OO.ui.Element[]} Items
4065 OO.ui.GroupElement.prototype.getItems = function () {
4066 return this.items.slice( 0 );
4070 * Get an item by its data.
4072 * Data is compared by a hash of its value. Only the first item with matching data will be returned.
4074 * @param {Object} data Item data to search for
4075 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4077 OO.ui.GroupElement.prototype.getItemFromData = function ( data ) {
4078 var i, len, item,
4079 hash = OO.getHash( data );
4081 for ( i = 0, len = this.items.length; i < len; i++ ) {
4082 item = this.items[ i ];
4083 if ( hash === OO.getHash( item.getData() ) ) {
4084 return item;
4088 return null;
4092 * Get items by their data.
4094 * Data is compared by a hash of its value. All items with matching data will be returned.
4096 * @param {Object} data Item data to search for
4097 * @return {OO.ui.Element[]} Items with equivalent data
4099 OO.ui.GroupElement.prototype.getItemsFromData = function ( data ) {
4100 var i, len, item,
4101 hash = OO.getHash( data ),
4102 items = [];
4104 for ( i = 0, len = this.items.length; i < len; i++ ) {
4105 item = this.items[ i ];
4106 if ( hash === OO.getHash( item.getData() ) ) {
4107 items.push( item );
4111 return items;
4115 * Add an aggregate item event.
4117 * Aggregated events are listened to on each item and then emitted by the group under a new name,
4118 * and with an additional leading parameter containing the item that emitted the original event.
4119 * Other arguments that were emitted from the original event are passed through.
4121 * @param {Object.<string,string|null>} events Aggregate events emitted by group, keyed by item
4122 * event, use null value to remove aggregation
4123 * @throws {Error} If aggregation already exists
4125 OO.ui.GroupElement.prototype.aggregate = function ( events ) {
4126 var i, len, item, add, remove, itemEvent, groupEvent;
4128 for ( itemEvent in events ) {
4129 groupEvent = events[ itemEvent ];
4131 // Remove existing aggregated event
4132 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4133 // Don't allow duplicate aggregations
4134 if ( groupEvent ) {
4135 throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
4137 // Remove event aggregation from existing items
4138 for ( i = 0, len = this.items.length; i < len; i++ ) {
4139 item = this.items[ i ];
4140 if ( item.connect && item.disconnect ) {
4141 remove = {};
4142 remove[ itemEvent ] = [ 'emit', groupEvent, item ];
4143 item.disconnect( this, remove );
4146 // Prevent future items from aggregating event
4147 delete this.aggregateItemEvents[ itemEvent ];
4150 // Add new aggregate event
4151 if ( groupEvent ) {
4152 // Make future items aggregate event
4153 this.aggregateItemEvents[ itemEvent ] = groupEvent;
4154 // Add event aggregation to existing items
4155 for ( i = 0, len = this.items.length; i < len; i++ ) {
4156 item = this.items[ i ];
4157 if ( item.connect && item.disconnect ) {
4158 add = {};
4159 add[ itemEvent ] = [ 'emit', groupEvent, item ];
4160 item.connect( this, add );
4168 * Add items.
4170 * Adding an existing item will move it.
4172 * @param {OO.ui.Element[]} items Items
4173 * @param {number} [index] Index to insert items at
4174 * @chainable
4176 OO.ui.GroupElement.prototype.addItems = function ( items, index ) {
4177 var i, len, item, event, events, currentIndex,
4178 itemElements = [];
4180 for ( i = 0, len = items.length; i < len; i++ ) {
4181 item = items[ i ];
4183 // Check if item exists then remove it first, effectively "moving" it
4184 currentIndex = $.inArray( item, this.items );
4185 if ( currentIndex >= 0 ) {
4186 this.removeItems( [ item ] );
4187 // Adjust index to compensate for removal
4188 if ( currentIndex < index ) {
4189 index--;
4192 // Add the item
4193 if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) {
4194 events = {};
4195 for ( event in this.aggregateItemEvents ) {
4196 events[ event ] = [ 'emit', this.aggregateItemEvents[ event ], item ];
4198 item.connect( this, events );
4200 item.setElementGroup( this );
4201 itemElements.push( item.$element.get( 0 ) );
4204 if ( index === undefined || index < 0 || index >= this.items.length ) {
4205 this.$group.append( itemElements );
4206 this.items.push.apply( this.items, items );
4207 } else if ( index === 0 ) {
4208 this.$group.prepend( itemElements );
4209 this.items.unshift.apply( this.items, items );
4210 } else {
4211 this.items[ index ].$element.before( itemElements );
4212 this.items.splice.apply( this.items, [ index, 0 ].concat( items ) );
4215 return this;
4219 * Remove items.
4221 * Items will be detached, not removed, so they can be used later.
4223 * @param {OO.ui.Element[]} items Items to remove
4224 * @chainable
4226 OO.ui.GroupElement.prototype.removeItems = function ( items ) {
4227 var i, len, item, index, remove, itemEvent;
4229 // Remove specific items
4230 for ( i = 0, len = items.length; i < len; i++ ) {
4231 item = items[ i ];
4232 index = $.inArray( item, this.items );
4233 if ( index !== -1 ) {
4234 if (
4235 item.connect && item.disconnect &&
4236 !$.isEmptyObject( this.aggregateItemEvents )
4238 remove = {};
4239 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4240 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4242 item.disconnect( this, remove );
4244 item.setElementGroup( null );
4245 this.items.splice( index, 1 );
4246 item.$element.detach();
4250 return this;
4254 * Clear all items.
4256 * Items will be detached, not removed, so they can be used later.
4258 * @chainable
4260 OO.ui.GroupElement.prototype.clearItems = function () {
4261 var i, len, item, remove, itemEvent;
4263 // Remove all items
4264 for ( i = 0, len = this.items.length; i < len; i++ ) {
4265 item = this.items[ i ];
4266 if (
4267 item.connect && item.disconnect &&
4268 !$.isEmptyObject( this.aggregateItemEvents )
4270 remove = {};
4271 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4272 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4274 item.disconnect( this, remove );
4276 item.setElementGroup( null );
4277 item.$element.detach();
4280 this.items = [];
4281 return this;
4285 * DraggableElement is a mixin class used to create elements that can be clicked
4286 * and dragged by a mouse to a new position within a group. This class must be used
4287 * in conjunction with OO.ui.DraggableGroupElement, which provides a container for
4288 * the draggable elements.
4290 * @abstract
4291 * @class
4293 * @constructor
4295 OO.ui.DraggableElement = function OoUiDraggableElement() {
4296 // Properties
4297 this.index = null;
4299 // Initialize and events
4300 this.$element
4301 .attr( 'draggable', true )
4302 .addClass( 'oo-ui-draggableElement' )
4303 .on( {
4304 dragstart: this.onDragStart.bind( this ),
4305 dragover: this.onDragOver.bind( this ),
4306 dragend: this.onDragEnd.bind( this ),
4307 drop: this.onDrop.bind( this )
4308 } );
4311 OO.initClass( OO.ui.DraggableElement );
4313 /* Events */
4316 * @event dragstart
4318 * A dragstart event is emitted when the user clicks and begins dragging an item.
4319 * @param {OO.ui.DraggableElement} item The item the user has clicked and is dragging with the mouse.
4323 * @event dragend
4324 * A dragend event is emitted when the user drags an item and releases the mouse,
4325 * thus terminating the drag operation.
4329 * @event drop
4330 * A drop event is emitted when the user drags an item and then releases the mouse button
4331 * over a valid target.
4334 /* Static Properties */
4337 * @inheritdoc OO.ui.ButtonElement
4339 OO.ui.DraggableElement.static.cancelButtonMouseDownEvents = false;
4341 /* Methods */
4344 * Respond to dragstart event.
4346 * @private
4347 * @param {jQuery.Event} event jQuery event
4348 * @fires dragstart
4350 OO.ui.DraggableElement.prototype.onDragStart = function ( e ) {
4351 var dataTransfer = e.originalEvent.dataTransfer;
4352 // Define drop effect
4353 dataTransfer.dropEffect = 'none';
4354 dataTransfer.effectAllowed = 'move';
4355 // We must set up a dataTransfer data property or Firefox seems to
4356 // ignore the fact the element is draggable.
4357 try {
4358 dataTransfer.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
4359 } catch ( err ) {
4360 // The above is only for firefox. No need to set a catch clause
4361 // if it fails, move on.
4363 // Add dragging class
4364 this.$element.addClass( 'oo-ui-draggableElement-dragging' );
4365 // Emit event
4366 this.emit( 'dragstart', this );
4367 return true;
4371 * Respond to dragend event.
4373 * @private
4374 * @fires dragend
4376 OO.ui.DraggableElement.prototype.onDragEnd = function () {
4377 this.$element.removeClass( 'oo-ui-draggableElement-dragging' );
4378 this.emit( 'dragend' );
4382 * Handle drop event.
4384 * @private
4385 * @param {jQuery.Event} event jQuery event
4386 * @fires drop
4388 OO.ui.DraggableElement.prototype.onDrop = function ( e ) {
4389 e.preventDefault();
4390 this.emit( 'drop', e );
4394 * In order for drag/drop to work, the dragover event must
4395 * return false and stop propogation.
4397 * @private
4399 OO.ui.DraggableElement.prototype.onDragOver = function ( e ) {
4400 e.preventDefault();
4404 * Set item index.
4405 * Store it in the DOM so we can access from the widget drag event
4407 * @private
4408 * @param {number} Item index
4410 OO.ui.DraggableElement.prototype.setIndex = function ( index ) {
4411 if ( this.index !== index ) {
4412 this.index = index;
4413 this.$element.data( 'index', index );
4418 * Get item index
4420 * @private
4421 * @return {number} Item index
4423 OO.ui.DraggableElement.prototype.getIndex = function () {
4424 return this.index;
4428 * DraggableGroupElement is a mixin class used to create a group element to
4429 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
4430 * The class is used with OO.ui.DraggableElement.
4432 * @abstract
4433 * @class
4435 * @constructor
4436 * @param {Object} [config] Configuration options
4437 * @cfg {jQuery} [$group] Container node, assigned to #$group, omit to use a generated `<div>`
4438 * @cfg {string} [orientation] Item orientation, 'horizontal' or 'vertical'. Defaults to 'vertical'
4440 OO.ui.DraggableGroupElement = function OoUiDraggableGroupElement( config ) {
4441 // Configuration initialization
4442 config = config || {};
4444 // Parent constructor
4445 OO.ui.GroupElement.call( this, config );
4447 // Properties
4448 this.orientation = config.orientation || 'vertical';
4449 this.dragItem = null;
4450 this.itemDragOver = null;
4451 this.itemKeys = {};
4452 this.sideInsertion = '';
4454 // Events
4455 this.aggregate( {
4456 dragstart: 'itemDragStart',
4457 dragend: 'itemDragEnd',
4458 drop: 'itemDrop'
4459 } );
4460 this.connect( this, {
4461 itemDragStart: 'onItemDragStart',
4462 itemDrop: 'onItemDrop',
4463 itemDragEnd: 'onItemDragEnd'
4464 } );
4465 this.$element.on( {
4466 dragover: $.proxy( this.onDragOver, this ),
4467 dragleave: $.proxy( this.onDragLeave, this )
4468 } );
4470 // Initialize
4471 if ( Array.isArray( config.items ) ) {
4472 this.addItems( config.items );
4474 this.$placeholder = $( '<div>' )
4475 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
4476 this.$element
4477 .addClass( 'oo-ui-draggableGroupElement' )
4478 .append( this.$status )
4479 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation === 'horizontal' )
4480 .prepend( this.$placeholder );
4483 /* Setup */
4484 OO.mixinClass( OO.ui.DraggableGroupElement, OO.ui.GroupElement );
4486 /* Events */
4489 * @event reorder
4490 * @param {OO.ui.DraggableElement} item Reordered item
4491 * @param {number} [newIndex] New index for the item
4494 /* Methods */
4497 * Respond to item drag start event
4498 * @param {OO.ui.DraggableElement} item Dragged item
4500 OO.ui.DraggableGroupElement.prototype.onItemDragStart = function ( item ) {
4501 var i, len;
4503 // Map the index of each object
4504 for ( i = 0, len = this.items.length; i < len; i++ ) {
4505 this.items[ i ].setIndex( i );
4508 if ( this.orientation === 'horizontal' ) {
4509 // Set the height of the indicator
4510 this.$placeholder.css( {
4511 height: item.$element.outerHeight(),
4512 width: 2
4513 } );
4514 } else {
4515 // Set the width of the indicator
4516 this.$placeholder.css( {
4517 height: 2,
4518 width: item.$element.outerWidth()
4519 } );
4521 this.setDragItem( item );
4525 * Respond to item drag end event
4527 OO.ui.DraggableGroupElement.prototype.onItemDragEnd = function () {
4528 this.unsetDragItem();
4529 return false;
4533 * Handle drop event and switch the order of the items accordingly
4534 * @param {OO.ui.DraggableElement} item Dropped item
4535 * @fires reorder
4537 OO.ui.DraggableGroupElement.prototype.onItemDrop = function ( item ) {
4538 var toIndex = item.getIndex();
4539 // Check if the dropped item is from the current group
4540 // TODO: Figure out a way to configure a list of legally droppable
4541 // elements even if they are not yet in the list
4542 if ( this.getDragItem() ) {
4543 // If the insertion point is 'after', the insertion index
4544 // is shifted to the right (or to the left in RTL, hence 'after')
4545 if ( this.sideInsertion === 'after' ) {
4546 toIndex++;
4548 // Emit change event
4549 this.emit( 'reorder', this.getDragItem(), toIndex );
4551 this.unsetDragItem();
4552 // Return false to prevent propogation
4553 return false;
4557 * Handle dragleave event.
4559 OO.ui.DraggableGroupElement.prototype.onDragLeave = function () {
4560 // This means the item was dragged outside the widget
4561 this.$placeholder
4562 .css( 'left', 0 )
4563 .addClass( 'oo-ui-element-hidden' );
4567 * Respond to dragover event
4568 * @param {jQuery.Event} event Event details
4570 OO.ui.DraggableGroupElement.prototype.onDragOver = function ( e ) {
4571 var dragOverObj, $optionWidget, itemOffset, itemMidpoint, itemBoundingRect,
4572 itemSize, cssOutput, dragPosition, itemIndex, itemPosition,
4573 clientX = e.originalEvent.clientX,
4574 clientY = e.originalEvent.clientY;
4576 // Get the OptionWidget item we are dragging over
4577 dragOverObj = this.getElementDocument().elementFromPoint( clientX, clientY );
4578 $optionWidget = $( dragOverObj ).closest( '.oo-ui-draggableElement' );
4579 if ( $optionWidget[ 0 ] ) {
4580 itemOffset = $optionWidget.offset();
4581 itemBoundingRect = $optionWidget[ 0 ].getBoundingClientRect();
4582 itemPosition = $optionWidget.position();
4583 itemIndex = $optionWidget.data( 'index' );
4586 if (
4587 itemOffset &&
4588 this.isDragging() &&
4589 itemIndex !== this.getDragItem().getIndex()
4591 if ( this.orientation === 'horizontal' ) {
4592 // Calculate where the mouse is relative to the item width
4593 itemSize = itemBoundingRect.width;
4594 itemMidpoint = itemBoundingRect.left + itemSize / 2;
4595 dragPosition = clientX;
4596 // Which side of the item we hover over will dictate
4597 // where the placeholder will appear, on the left or
4598 // on the right
4599 cssOutput = {
4600 left: dragPosition < itemMidpoint ? itemPosition.left : itemPosition.left + itemSize,
4601 top: itemPosition.top
4603 } else {
4604 // Calculate where the mouse is relative to the item height
4605 itemSize = itemBoundingRect.height;
4606 itemMidpoint = itemBoundingRect.top + itemSize / 2;
4607 dragPosition = clientY;
4608 // Which side of the item we hover over will dictate
4609 // where the placeholder will appear, on the top or
4610 // on the bottom
4611 cssOutput = {
4612 top: dragPosition < itemMidpoint ? itemPosition.top : itemPosition.top + itemSize,
4613 left: itemPosition.left
4616 // Store whether we are before or after an item to rearrange
4617 // For horizontal layout, we need to account for RTL, as this is flipped
4618 if ( this.orientation === 'horizontal' && this.$element.css( 'direction' ) === 'rtl' ) {
4619 this.sideInsertion = dragPosition < itemMidpoint ? 'after' : 'before';
4620 } else {
4621 this.sideInsertion = dragPosition < itemMidpoint ? 'before' : 'after';
4623 // Add drop indicator between objects
4624 this.$placeholder
4625 .css( cssOutput )
4626 .removeClass( 'oo-ui-element-hidden' );
4627 } else {
4628 // This means the item was dragged outside the widget
4629 this.$placeholder
4630 .css( 'left', 0 )
4631 .addClass( 'oo-ui-element-hidden' );
4633 // Prevent default
4634 e.preventDefault();
4638 * Set a dragged item
4639 * @param {OO.ui.DraggableElement} item Dragged item
4641 OO.ui.DraggableGroupElement.prototype.setDragItem = function ( item ) {
4642 this.dragItem = item;
4646 * Unset the current dragged item
4648 OO.ui.DraggableGroupElement.prototype.unsetDragItem = function () {
4649 this.dragItem = null;
4650 this.itemDragOver = null;
4651 this.$placeholder.addClass( 'oo-ui-element-hidden' );
4652 this.sideInsertion = '';
4656 * Get the current dragged item
4657 * @return {OO.ui.DraggableElement|null} item Dragged item or null if no item is dragged
4659 OO.ui.DraggableGroupElement.prototype.getDragItem = function () {
4660 return this.dragItem;
4664 * Check if there's an item being dragged.
4665 * @return {Boolean} Item is being dragged
4667 OO.ui.DraggableGroupElement.prototype.isDragging = function () {
4668 return this.getDragItem() !== null;
4672 * IconElement is often mixed into other classes to generate an icon.
4673 * Icons are graphics, about the size of normal text. They are used to aid the user
4674 * in locating a control or to convey information in a space-efficient way. See the
4675 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
4676 * included in the library.
4678 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
4680 * @abstract
4681 * @class
4683 * @constructor
4684 * @param {Object} [config] Configuration options
4685 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
4686 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
4687 * the icon element be set to an existing icon instead of the one generated by this class, set a
4688 * value using a jQuery selection. For example:
4690 * // Use a <div> tag instead of a <span>
4691 * $icon: $("<div>")
4692 * // Use an existing icon element instead of the one generated by the class
4693 * $icon: this.$element
4694 * // Use an icon element from a child widget
4695 * $icon: this.childwidget.$element
4696 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
4697 * symbolic names. A map is used for i18n purposes and contains a `default` icon
4698 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
4699 * by the user's language.
4701 * Example of an i18n map:
4703 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
4704 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
4705 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
4706 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
4707 * text. The icon title is displayed when users move the mouse over the icon.
4709 OO.ui.IconElement = function OoUiIconElement( config ) {
4710 // Configuration initialization
4711 config = config || {};
4713 // Properties
4714 this.$icon = null;
4715 this.icon = null;
4716 this.iconTitle = null;
4718 // Initialization
4719 this.setIcon( config.icon || this.constructor.static.icon );
4720 this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle );
4721 this.setIconElement( config.$icon || $( '<span>' ) );
4724 /* Setup */
4726 OO.initClass( OO.ui.IconElement );
4728 /* Static Properties */
4731 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
4732 * for i18n purposes and contains a `default` icon name and additional names keyed by
4733 * language code. The `default` name is used when no icon is keyed by the user's language.
4735 * Example of an i18n map:
4737 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
4739 * Note: the static property will be overridden if the #icon configuration is used.
4741 * @static
4742 * @inheritable
4743 * @property {Object|string}
4745 OO.ui.IconElement.static.icon = null;
4748 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
4749 * function that returns title text, or `null` for no title.
4751 * The static property will be overridden if the #iconTitle configuration is used.
4753 * @static
4754 * @inheritable
4755 * @property {string|Function|null}
4757 OO.ui.IconElement.static.iconTitle = null;
4759 /* Methods */
4762 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
4763 * applies to the specified icon element instead of the one created by the class. If an icon
4764 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
4765 * and mixin methods will no longer affect the element.
4767 * @param {jQuery} $icon Element to use as icon
4769 OO.ui.IconElement.prototype.setIconElement = function ( $icon ) {
4770 if ( this.$icon ) {
4771 this.$icon
4772 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
4773 .removeAttr( 'title' );
4776 this.$icon = $icon
4777 .addClass( 'oo-ui-iconElement-icon' )
4778 .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
4779 if ( this.iconTitle !== null ) {
4780 this.$icon.attr( 'title', this.iconTitle );
4785 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
4786 * The icon parameter can also be set to a map of icon names. See the #icon config setting
4787 * for an example.
4789 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
4790 * by language code, or `null` to remove the icon.
4791 * @chainable
4793 OO.ui.IconElement.prototype.setIcon = function ( icon ) {
4794 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
4795 icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
4797 if ( this.icon !== icon ) {
4798 if ( this.$icon ) {
4799 if ( this.icon !== null ) {
4800 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
4802 if ( icon !== null ) {
4803 this.$icon.addClass( 'oo-ui-icon-' + icon );
4806 this.icon = icon;
4809 this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
4810 this.updateThemeClasses();
4812 return this;
4816 * Set the icon title. Use `null` to remove the title.
4818 * @param {string|Function|null} iconTitle A text string used as the icon title,
4819 * a function that returns title text, or `null` for no title.
4820 * @chainable
4822 OO.ui.IconElement.prototype.setIconTitle = function ( iconTitle ) {
4823 iconTitle = typeof iconTitle === 'function' ||
4824 ( typeof iconTitle === 'string' && iconTitle.length ) ?
4825 OO.ui.resolveMsg( iconTitle ) : null;
4827 if ( this.iconTitle !== iconTitle ) {
4828 this.iconTitle = iconTitle;
4829 if ( this.$icon ) {
4830 if ( this.iconTitle !== null ) {
4831 this.$icon.attr( 'title', iconTitle );
4832 } else {
4833 this.$icon.removeAttr( 'title' );
4838 return this;
4842 * Get the symbolic name of the icon.
4844 * @return {string} Icon name
4846 OO.ui.IconElement.prototype.getIcon = function () {
4847 return this.icon;
4851 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
4853 * @return {string} Icon title text
4855 OO.ui.IconElement.prototype.getIconTitle = function () {
4856 return this.iconTitle;
4860 * IndicatorElement is often mixed into other classes to generate an indicator.
4861 * Indicators are small graphics that are generally used in two ways:
4863 * - To draw attention to the status of an item. For example, an indicator might be
4864 * used to show that an item in a list has errors that need to be resolved.
4865 * - To clarify the function of a control that acts in an exceptional way (a button
4866 * that opens a menu instead of performing an action directly, for example).
4868 * For a list of indicators included in the library, please see the
4869 * [OOjs UI documentation on MediaWiki] [1].
4871 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
4873 * @abstract
4874 * @class
4876 * @constructor
4877 * @param {Object} [config] Configuration options
4878 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
4879 * configuration is omitted, the indicator element will use a generated `<span>`.
4880 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
4881 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
4882 * in the library.
4883 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
4884 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
4885 * or a function that returns title text. The indicator title is displayed when users move
4886 * the mouse over the indicator.
4888 OO.ui.IndicatorElement = function OoUiIndicatorElement( config ) {
4889 // Configuration initialization
4890 config = config || {};
4892 // Properties
4893 this.$indicator = null;
4894 this.indicator = null;
4895 this.indicatorTitle = null;
4897 // Initialization
4898 this.setIndicator( config.indicator || this.constructor.static.indicator );
4899 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
4900 this.setIndicatorElement( config.$indicator || $( '<span>' ) );
4903 /* Setup */
4905 OO.initClass( OO.ui.IndicatorElement );
4907 /* Static Properties */
4910 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
4911 * The static property will be overridden if the #indicator configuration is used.
4913 * @static
4914 * @inheritable
4915 * @property {string|null}
4917 OO.ui.IndicatorElement.static.indicator = null;
4920 * A text string used as the indicator title, a function that returns title text, or `null`
4921 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
4923 * @static
4924 * @inheritable
4925 * @property {string|Function|null}
4927 OO.ui.IndicatorElement.static.indicatorTitle = null;
4929 /* Methods */
4932 * Set the indicator element.
4934 * If an element is already set, it will be cleaned up before setting up the new element.
4936 * @param {jQuery} $indicator Element to use as indicator
4938 OO.ui.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
4939 if ( this.$indicator ) {
4940 this.$indicator
4941 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
4942 .removeAttr( 'title' );
4945 this.$indicator = $indicator
4946 .addClass( 'oo-ui-indicatorElement-indicator' )
4947 .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
4948 if ( this.indicatorTitle !== null ) {
4949 this.$indicator.attr( 'title', this.indicatorTitle );
4954 * Set indicator name.
4956 * @param {string|null} indicator Symbolic name of indicator to use or null for no indicator
4957 * @chainable
4959 OO.ui.IndicatorElement.prototype.setIndicator = function ( indicator ) {
4960 indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
4962 if ( this.indicator !== indicator ) {
4963 if ( this.$indicator ) {
4964 if ( this.indicator !== null ) {
4965 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
4967 if ( indicator !== null ) {
4968 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
4971 this.indicator = indicator;
4974 this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
4975 this.updateThemeClasses();
4977 return this;
4981 * Set indicator title.
4983 * @param {string|Function|null} indicator Indicator title text, a function that returns text or
4984 * null for no indicator title
4985 * @chainable
4987 OO.ui.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
4988 indicatorTitle = typeof indicatorTitle === 'function' ||
4989 ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ?
4990 OO.ui.resolveMsg( indicatorTitle ) : null;
4992 if ( this.indicatorTitle !== indicatorTitle ) {
4993 this.indicatorTitle = indicatorTitle;
4994 if ( this.$indicator ) {
4995 if ( this.indicatorTitle !== null ) {
4996 this.$indicator.attr( 'title', indicatorTitle );
4997 } else {
4998 this.$indicator.removeAttr( 'title' );
5003 return this;
5007 * Get indicator name.
5009 * @return {string} Symbolic name of indicator
5011 OO.ui.IndicatorElement.prototype.getIndicator = function () {
5012 return this.indicator;
5016 * Get indicator title.
5018 * @return {string} Indicator title text
5020 OO.ui.IndicatorElement.prototype.getIndicatorTitle = function () {
5021 return this.indicatorTitle;
5025 * LabelElement is often mixed into other classes to generate a label, which
5026 * helps identify the function of an interface element.
5027 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5029 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5031 * @abstract
5032 * @class
5034 * @constructor
5035 * @param {Object} [config] Configuration options
5036 * @cfg {jQuery} [$label] The label element created by the class. If this
5037 * configuration is omitted, the label element will use a generated `<span>`.
5038 * @cfg {jQuery|string|Function} [label] The label text. The label can be specified as a plaintext string,
5039 * a jQuery selection of elements, or a function that will produce a string in the future. See the
5040 * [OOjs UI documentation on MediaWiki] [2] for examples.
5041 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5042 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5043 * The label will be truncated to fit if necessary.
5045 OO.ui.LabelElement = function OoUiLabelElement( config ) {
5046 // Configuration initialization
5047 config = config || {};
5049 // Properties
5050 this.$label = null;
5051 this.label = null;
5052 this.autoFitLabel = config.autoFitLabel === undefined || !!config.autoFitLabel;
5054 // Initialization
5055 this.setLabel( config.label || this.constructor.static.label );
5056 this.setLabelElement( config.$label || $( '<span>' ) );
5059 /* Setup */
5061 OO.initClass( OO.ui.LabelElement );
5063 /* Events */
5066 * @event labelChange
5067 * @param {string} value
5070 /* Static Properties */
5073 * The label text. The label can be specified as a plaintext string, a function that will
5074 * produce a string in the future, or `null` for no label. The static value will
5075 * be overridden if a label is specified with the #label config option.
5077 * @static
5078 * @inheritable
5079 * @property {string|Function|null}
5081 OO.ui.LabelElement.static.label = null;
5083 /* Methods */
5086 * Set the label element.
5088 * If an element is already set, it will be cleaned up before setting up the new element.
5090 * @param {jQuery} $label Element to use as label
5092 OO.ui.LabelElement.prototype.setLabelElement = function ( $label ) {
5093 if ( this.$label ) {
5094 this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
5097 this.$label = $label.addClass( 'oo-ui-labelElement-label' );
5098 this.setLabelContent( this.label );
5102 * Set the label.
5104 * An empty string will result in the label being hidden. A string containing only whitespace will
5105 * be converted to a single `&nbsp;`.
5107 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
5108 * text; or null for no label
5109 * @chainable
5111 OO.ui.LabelElement.prototype.setLabel = function ( label ) {
5112 label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
5113 label = ( ( typeof label === 'string' && label.length ) || label instanceof jQuery || label instanceof OO.ui.HtmlSnippet ) ? label : null;
5115 this.$element.toggleClass( 'oo-ui-labelElement', !!label );
5117 if ( this.label !== label ) {
5118 if ( this.$label ) {
5119 this.setLabelContent( label );
5121 this.label = label;
5122 this.emit( 'labelChange' );
5125 return this;
5129 * Get the label.
5131 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
5132 * text; or null for no label
5134 OO.ui.LabelElement.prototype.getLabel = function () {
5135 return this.label;
5139 * Fit the label.
5141 * @chainable
5143 OO.ui.LabelElement.prototype.fitLabel = function () {
5144 if ( this.$label && this.$label.autoEllipsis && this.autoFitLabel ) {
5145 this.$label.autoEllipsis( { hasSpan: false, tooltip: true } );
5148 return this;
5152 * Set the content of the label.
5154 * Do not call this method until after the label element has been set by #setLabelElement.
5156 * @private
5157 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5158 * text; or null for no label
5160 OO.ui.LabelElement.prototype.setLabelContent = function ( label ) {
5161 if ( typeof label === 'string' ) {
5162 if ( label.match( /^\s*$/ ) ) {
5163 // Convert whitespace only string to a single non-breaking space
5164 this.$label.html( '&nbsp;' );
5165 } else {
5166 this.$label.text( label );
5168 } else if ( label instanceof OO.ui.HtmlSnippet ) {
5169 this.$label.html( label.toString() );
5170 } else if ( label instanceof jQuery ) {
5171 this.$label.empty().append( label );
5172 } else {
5173 this.$label.empty();
5178 * Mixin that adds a menu showing suggested values for a OO.ui.TextInputWidget.
5180 * Subclasses that set the value of #lookupInput from #onLookupMenuItemChoose should
5181 * be aware that this will cause new suggestions to be looked up for the new value. If this is
5182 * not desired, disable lookups with #setLookupsDisabled, then set the value, then re-enable lookups.
5184 * @class
5185 * @abstract
5187 * @constructor
5188 * @param {Object} [config] Configuration options
5189 * @cfg {jQuery} [$overlay] Overlay for dropdown; defaults to relative positioning
5190 * @cfg {jQuery} [$container=this.$element] Element to render menu under
5192 OO.ui.LookupElement = function OoUiLookupElement( config ) {
5193 // Configuration initialization
5194 config = config || {};
5196 // Properties
5197 this.$overlay = config.$overlay || this.$element;
5198 this.lookupMenu = new OO.ui.TextInputMenuSelectWidget( this, {
5199 widget: this,
5200 input: this,
5201 $container: config.$container
5202 } );
5203 this.lookupCache = {};
5204 this.lookupQuery = null;
5205 this.lookupRequest = null;
5206 this.lookupsDisabled = false;
5207 this.lookupInputFocused = false;
5209 // Events
5210 this.$input.on( {
5211 focus: this.onLookupInputFocus.bind( this ),
5212 blur: this.onLookupInputBlur.bind( this ),
5213 mousedown: this.onLookupInputMouseDown.bind( this )
5214 } );
5215 this.connect( this, { change: 'onLookupInputChange' } );
5216 this.lookupMenu.connect( this, {
5217 toggle: 'onLookupMenuToggle',
5218 choose: 'onLookupMenuItemChoose'
5219 } );
5221 // Initialization
5222 this.$element.addClass( 'oo-ui-lookupElement' );
5223 this.lookupMenu.$element.addClass( 'oo-ui-lookupElement-menu' );
5224 this.$overlay.append( this.lookupMenu.$element );
5227 /* Methods */
5230 * Handle input focus event.
5232 * @param {jQuery.Event} e Input focus event
5234 OO.ui.LookupElement.prototype.onLookupInputFocus = function () {
5235 this.lookupInputFocused = true;
5236 this.populateLookupMenu();
5240 * Handle input blur event.
5242 * @param {jQuery.Event} e Input blur event
5244 OO.ui.LookupElement.prototype.onLookupInputBlur = function () {
5245 this.closeLookupMenu();
5246 this.lookupInputFocused = false;
5250 * Handle input mouse down event.
5252 * @param {jQuery.Event} e Input mouse down event
5254 OO.ui.LookupElement.prototype.onLookupInputMouseDown = function () {
5255 // Only open the menu if the input was already focused.
5256 // This way we allow the user to open the menu again after closing it with Esc
5257 // by clicking in the input. Opening (and populating) the menu when initially
5258 // clicking into the input is handled by the focus handler.
5259 if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) {
5260 this.populateLookupMenu();
5265 * Handle input change event.
5267 * @param {string} value New input value
5269 OO.ui.LookupElement.prototype.onLookupInputChange = function () {
5270 if ( this.lookupInputFocused ) {
5271 this.populateLookupMenu();
5276 * Handle the lookup menu being shown/hidden.
5278 * @param {boolean} visible Whether the lookup menu is now visible.
5280 OO.ui.LookupElement.prototype.onLookupMenuToggle = function ( visible ) {
5281 if ( !visible ) {
5282 // When the menu is hidden, abort any active request and clear the menu.
5283 // This has to be done here in addition to closeLookupMenu(), because
5284 // MenuSelectWidget will close itself when the user presses Esc.
5285 this.abortLookupRequest();
5286 this.lookupMenu.clearItems();
5291 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
5293 * @param {OO.ui.MenuOptionWidget|null} item Selected item
5295 OO.ui.LookupElement.prototype.onLookupMenuItemChoose = function ( item ) {
5296 if ( item ) {
5297 this.setValue( item.getData() );
5302 * Get lookup menu.
5304 * @return {OO.ui.TextInputMenuSelectWidget}
5306 OO.ui.LookupElement.prototype.getLookupMenu = function () {
5307 return this.lookupMenu;
5311 * Disable or re-enable lookups.
5313 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
5315 * @param {boolean} disabled Disable lookups
5317 OO.ui.LookupElement.prototype.setLookupsDisabled = function ( disabled ) {
5318 this.lookupsDisabled = !!disabled;
5322 * Open the menu. If there are no entries in the menu, this does nothing.
5324 * @chainable
5326 OO.ui.LookupElement.prototype.openLookupMenu = function () {
5327 if ( !this.lookupMenu.isEmpty() ) {
5328 this.lookupMenu.toggle( true );
5330 return this;
5334 * Close the menu, empty it, and abort any pending request.
5336 * @chainable
5338 OO.ui.LookupElement.prototype.closeLookupMenu = function () {
5339 this.lookupMenu.toggle( false );
5340 this.abortLookupRequest();
5341 this.lookupMenu.clearItems();
5342 return this;
5346 * Request menu items based on the input's current value, and when they arrive,
5347 * populate the menu with these items and show the menu.
5349 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
5351 * @chainable
5353 OO.ui.LookupElement.prototype.populateLookupMenu = function () {
5354 var widget = this,
5355 value = this.getValue();
5357 if ( this.lookupsDisabled ) {
5358 return;
5361 // If the input is empty, clear the menu
5362 if ( value === '' ) {
5363 this.closeLookupMenu();
5364 // Skip population if there is already a request pending for the current value
5365 } else if ( value !== this.lookupQuery ) {
5366 this.getLookupMenuItems()
5367 .done( function ( items ) {
5368 widget.lookupMenu.clearItems();
5369 if ( items.length ) {
5370 widget.lookupMenu
5371 .addItems( items )
5372 .toggle( true );
5373 widget.initializeLookupMenuSelection();
5374 } else {
5375 widget.lookupMenu.toggle( false );
5378 .fail( function () {
5379 widget.lookupMenu.clearItems();
5380 } );
5383 return this;
5387 * Select and highlight the first selectable item in the menu.
5389 * @chainable
5391 OO.ui.LookupElement.prototype.initializeLookupMenuSelection = function () {
5392 if ( !this.lookupMenu.getSelectedItem() ) {
5393 this.lookupMenu.selectItem( this.lookupMenu.getFirstSelectableItem() );
5395 this.lookupMenu.highlightItem( this.lookupMenu.getSelectedItem() );
5399 * Get lookup menu items for the current query.
5401 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
5402 * the done event. If the request was aborted to make way for a subsequent request, this promise
5403 * will not be rejected: it will remain pending forever.
5405 OO.ui.LookupElement.prototype.getLookupMenuItems = function () {
5406 var widget = this,
5407 value = this.getValue(),
5408 deferred = $.Deferred(),
5409 ourRequest;
5411 this.abortLookupRequest();
5412 if ( Object.prototype.hasOwnProperty.call( this.lookupCache, value ) ) {
5413 deferred.resolve( this.getLookupMenuOptionsFromData( this.lookupCache[ value ] ) );
5414 } else {
5415 this.pushPending();
5416 this.lookupQuery = value;
5417 ourRequest = this.lookupRequest = this.getLookupRequest();
5418 ourRequest
5419 .always( function () {
5420 // We need to pop pending even if this is an old request, otherwise
5421 // the widget will remain pending forever.
5422 // TODO: this assumes that an aborted request will fail or succeed soon after
5423 // being aborted, or at least eventually. It would be nice if we could popPending()
5424 // at abort time, but only if we knew that we hadn't already called popPending()
5425 // for that request.
5426 widget.popPending();
5428 .done( function ( data ) {
5429 // If this is an old request (and aborting it somehow caused it to still succeed),
5430 // ignore its success completely
5431 if ( ourRequest === widget.lookupRequest ) {
5432 widget.lookupQuery = null;
5433 widget.lookupRequest = null;
5434 widget.lookupCache[ value ] = widget.getLookupCacheDataFromResponse( data );
5435 deferred.resolve( widget.getLookupMenuOptionsFromData( widget.lookupCache[ value ] ) );
5438 .fail( function () {
5439 // If this is an old request (or a request failing because it's being aborted),
5440 // ignore its failure completely
5441 if ( ourRequest === widget.lookupRequest ) {
5442 widget.lookupQuery = null;
5443 widget.lookupRequest = null;
5444 deferred.reject();
5446 } );
5448 return deferred.promise();
5452 * Abort the currently pending lookup request, if any.
5454 OO.ui.LookupElement.prototype.abortLookupRequest = function () {
5455 var oldRequest = this.lookupRequest;
5456 if ( oldRequest ) {
5457 // First unset this.lookupRequest to the fail handler will notice
5458 // that the request is no longer current
5459 this.lookupRequest = null;
5460 this.lookupQuery = null;
5461 oldRequest.abort();
5466 * Get a new request object of the current lookup query value.
5468 * @abstract
5469 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
5471 OO.ui.LookupElement.prototype.getLookupRequest = function () {
5472 // Stub, implemented in subclass
5473 return null;
5477 * Pre-process data returned by the request from #getLookupRequest.
5479 * The return value of this function will be cached, and any further queries for the given value
5480 * will use the cache rather than doing API requests.
5482 * @abstract
5483 * @param {Mixed} data Response from server
5484 * @return {Mixed} Cached result data
5486 OO.ui.LookupElement.prototype.getLookupCacheDataFromResponse = function () {
5487 // Stub, implemented in subclass
5488 return [];
5492 * Get a list of menu option widgets from the (possibly cached) data returned by
5493 * #getLookupCacheDataFromResponse.
5495 * @abstract
5496 * @param {Mixed} data Cached result data, usually an array
5497 * @return {OO.ui.MenuOptionWidget[]} Menu items
5499 OO.ui.LookupElement.prototype.getLookupMenuOptionsFromData = function () {
5500 // Stub, implemented in subclass
5501 return [];
5505 * Element containing an OO.ui.PopupWidget object.
5507 * @abstract
5508 * @class
5510 * @constructor
5511 * @param {Object} [config] Configuration options
5512 * @cfg {Object} [popup] Configuration to pass to popup
5513 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5515 OO.ui.PopupElement = function OoUiPopupElement( config ) {
5516 // Configuration initialization
5517 config = config || {};
5519 // Properties
5520 this.popup = new OO.ui.PopupWidget( $.extend(
5521 { autoClose: true },
5522 config.popup,
5523 { $autoCloseIgnore: this.$element }
5524 ) );
5527 /* Methods */
5530 * Get popup.
5532 * @return {OO.ui.PopupWidget} Popup widget
5534 OO.ui.PopupElement.prototype.getPopup = function () {
5535 return this.popup;
5539 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
5540 * additional functionality to an element created by another class. The class provides
5541 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
5542 * which are used to customize the look and feel of a widget to better describe its
5543 * importance and functionality.
5545 * The library currently contains the following styling flags for general use:
5547 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
5548 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
5549 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
5551 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
5552 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
5554 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
5556 * @abstract
5557 * @class
5559 * @constructor
5560 * @param {Object} [config] Configuration options
5561 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
5562 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
5563 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
5564 * @cfg {jQuery} [$flagged] Flagged node, assigned to $flagged, omit to use $element
5566 OO.ui.FlaggedElement = function OoUiFlaggedElement( config ) {
5567 // Configuration initialization
5568 config = config || {};
5570 // Properties
5571 this.flags = {};
5572 this.$flagged = null;
5574 // Initialization
5575 this.setFlags( config.flags );
5576 this.setFlaggedElement( config.$flagged || this.$element );
5579 /* Events */
5582 * @event flag
5583 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
5584 * parameter contains the name of each modified flag and indicates whether it was
5585 * added or removed.
5587 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
5588 * that the flag was added, `false` that the flag was removed.
5591 /* Methods */
5594 * Set the flagged element.
5596 * If an element is already set, it will be cleaned up before setting up the new element.
5598 * @param {jQuery} $flagged Element to add flags to
5600 OO.ui.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
5601 var classNames = Object.keys( this.flags ).map( function ( flag ) {
5602 return 'oo-ui-flaggedElement-' + flag;
5603 } ).join( ' ' );
5605 if ( this.$flagged ) {
5606 this.$flagged.removeClass( classNames );
5609 this.$flagged = $flagged.addClass( classNames );
5613 * Check if a flag is set.
5615 * @param {string} flag Name of flag
5616 * @return {boolean} Has flag
5618 OO.ui.FlaggedElement.prototype.hasFlag = function ( flag ) {
5619 return flag in this.flags;
5623 * Get the names of all flags set.
5625 * @return {string[]} Flag names
5627 OO.ui.FlaggedElement.prototype.getFlags = function () {
5628 return Object.keys( this.flags );
5632 * Clear all flags.
5634 * @chainable
5635 * @fires flag
5637 OO.ui.FlaggedElement.prototype.clearFlags = function () {
5638 var flag, className,
5639 changes = {},
5640 remove = [],
5641 classPrefix = 'oo-ui-flaggedElement-';
5643 for ( flag in this.flags ) {
5644 className = classPrefix + flag;
5645 changes[ flag ] = false;
5646 delete this.flags[ flag ];
5647 remove.push( className );
5650 if ( this.$flagged ) {
5651 this.$flagged.removeClass( remove.join( ' ' ) );
5654 this.updateThemeClasses();
5655 this.emit( 'flag', changes );
5657 return this;
5661 * Add one or more flags.
5663 * @param {string|string[]|Object.<string, boolean>} flags One or more flags to add, or an object
5664 * keyed by flag name containing boolean set/remove instructions.
5665 * @chainable
5666 * @fires flag
5668 OO.ui.FlaggedElement.prototype.setFlags = function ( flags ) {
5669 var i, len, flag, className,
5670 changes = {},
5671 add = [],
5672 remove = [],
5673 classPrefix = 'oo-ui-flaggedElement-';
5675 if ( typeof flags === 'string' ) {
5676 className = classPrefix + flags;
5677 // Set
5678 if ( !this.flags[ flags ] ) {
5679 this.flags[ flags ] = true;
5680 add.push( className );
5682 } else if ( Array.isArray( flags ) ) {
5683 for ( i = 0, len = flags.length; i < len; i++ ) {
5684 flag = flags[ i ];
5685 className = classPrefix + flag;
5686 // Set
5687 if ( !this.flags[ flag ] ) {
5688 changes[ flag ] = true;
5689 this.flags[ flag ] = true;
5690 add.push( className );
5693 } else if ( OO.isPlainObject( flags ) ) {
5694 for ( flag in flags ) {
5695 className = classPrefix + flag;
5696 if ( flags[ flag ] ) {
5697 // Set
5698 if ( !this.flags[ flag ] ) {
5699 changes[ flag ] = true;
5700 this.flags[ flag ] = true;
5701 add.push( className );
5703 } else {
5704 // Remove
5705 if ( this.flags[ flag ] ) {
5706 changes[ flag ] = false;
5707 delete this.flags[ flag ];
5708 remove.push( className );
5714 if ( this.$flagged ) {
5715 this.$flagged
5716 .addClass( add.join( ' ' ) )
5717 .removeClass( remove.join( ' ' ) );
5720 this.updateThemeClasses();
5721 this.emit( 'flag', changes );
5723 return this;
5727 * TitledElement is mixed into other classes to provide a `title` attribute.
5728 * Titles are rendered by the browser and are made visible when the user moves
5729 * the mouse over the element. Titles are not visible on touch devices.
5731 * @example
5732 * // TitledElement provides a 'title' attribute to the
5733 * // ButtonWidget class
5734 * var button = new OO.ui.ButtonWidget( {
5735 * label : 'Button with Title',
5736 * title : 'I am a button'
5737 * } );
5738 * $( 'body' ).append( button.$element );
5740 * @abstract
5741 * @class
5743 * @constructor
5744 * @param {Object} [config] Configuration options
5745 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
5746 * If this config is omitted, the title functionality is applied to $element, the
5747 * element created by the class.
5748 * @cfg {string|Function} [title] The title text or a function that returns text. If
5749 * this config is omitted, the value of the static `title` property is used.
5751 OO.ui.TitledElement = function OoUiTitledElement( config ) {
5752 // Configuration initialization
5753 config = config || {};
5755 // Properties
5756 this.$titled = null;
5757 this.title = null;
5759 // Initialization
5760 this.setTitle( config.title || this.constructor.static.title );
5761 this.setTitledElement( config.$titled || this.$element );
5764 /* Setup */
5766 OO.initClass( OO.ui.TitledElement );
5768 /* Static Properties */
5771 * The title text, a function that returns text, or `null` for no title. The value of the static property
5772 * is overridden if the #title config option is used.
5774 * @static
5775 * @inheritable
5776 * @property {string|Function|null}
5778 OO.ui.TitledElement.static.title = null;
5780 /* Methods */
5783 * Set the titled element.
5785 * If an element is already set, it will be cleaned up before setting up the new element.
5787 * @param {jQuery} $titled Element to set title on
5789 OO.ui.TitledElement.prototype.setTitledElement = function ( $titled ) {
5790 if ( this.$titled ) {
5791 this.$titled.removeAttr( 'title' );
5794 this.$titled = $titled;
5795 if ( this.title ) {
5796 this.$titled.attr( 'title', this.title );
5801 * Set title.
5803 * @param {string|Function|null} title Title text, a function that returns text or null for no title
5804 * @chainable
5806 OO.ui.TitledElement.prototype.setTitle = function ( title ) {
5807 title = typeof title === 'string' ? OO.ui.resolveMsg( title ) : null;
5809 if ( this.title !== title ) {
5810 if ( this.$titled ) {
5811 if ( title !== null ) {
5812 this.$titled.attr( 'title', title );
5813 } else {
5814 this.$titled.removeAttr( 'title' );
5817 this.title = title;
5820 return this;
5824 * Get title.
5826 * @return {string} Title string
5828 OO.ui.TitledElement.prototype.getTitle = function () {
5829 return this.title;
5833 * Element that can be automatically clipped to visible boundaries.
5835 * Whenever the element's natural height changes, you have to call
5836 * #clip to make sure it's still clipping correctly.
5838 * @abstract
5839 * @class
5841 * @constructor
5842 * @param {Object} [config] Configuration options
5843 * @cfg {jQuery} [$clippable] Nodes to clip, assigned to #$clippable, omit to use #$element
5845 OO.ui.ClippableElement = function OoUiClippableElement( config ) {
5846 // Configuration initialization
5847 config = config || {};
5849 // Properties
5850 this.$clippable = null;
5851 this.clipping = false;
5852 this.clippedHorizontally = false;
5853 this.clippedVertically = false;
5854 this.$clippableContainer = null;
5855 this.$clippableScroller = null;
5856 this.$clippableWindow = null;
5857 this.idealWidth = null;
5858 this.idealHeight = null;
5859 this.onClippableContainerScrollHandler = this.clip.bind( this );
5860 this.onClippableWindowResizeHandler = this.clip.bind( this );
5862 // Initialization
5863 this.setClippableElement( config.$clippable || this.$element );
5866 /* Methods */
5869 * Set clippable element.
5871 * If an element is already set, it will be cleaned up before setting up the new element.
5873 * @param {jQuery} $clippable Element to make clippable
5875 OO.ui.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
5876 if ( this.$clippable ) {
5877 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
5878 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
5879 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
5882 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
5883 this.clip();
5887 * Toggle clipping.
5889 * Do not turn clipping on until after the element is attached to the DOM and visible.
5891 * @param {boolean} [clipping] Enable clipping, omit to toggle
5892 * @chainable
5894 OO.ui.ClippableElement.prototype.toggleClipping = function ( clipping ) {
5895 clipping = clipping === undefined ? !this.clipping : !!clipping;
5897 if ( this.clipping !== clipping ) {
5898 this.clipping = clipping;
5899 if ( clipping ) {
5900 this.$clippableContainer = $( this.getClosestScrollableElementContainer() );
5901 // If the clippable container is the root, we have to listen to scroll events and check
5902 // jQuery.scrollTop on the window because of browser inconsistencies
5903 this.$clippableScroller = this.$clippableContainer.is( 'html, body' ) ?
5904 $( OO.ui.Element.static.getWindow( this.$clippableContainer ) ) :
5905 this.$clippableContainer;
5906 this.$clippableScroller.on( 'scroll', this.onClippableContainerScrollHandler );
5907 this.$clippableWindow = $( this.getElementWindow() )
5908 .on( 'resize', this.onClippableWindowResizeHandler );
5909 // Initial clip after visible
5910 this.clip();
5911 } else {
5912 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
5913 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
5915 this.$clippableContainer = null;
5916 this.$clippableScroller.off( 'scroll', this.onClippableContainerScrollHandler );
5917 this.$clippableScroller = null;
5918 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
5919 this.$clippableWindow = null;
5923 return this;
5927 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
5929 * @return {boolean} Element will be clipped to the visible area
5931 OO.ui.ClippableElement.prototype.isClipping = function () {
5932 return this.clipping;
5936 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
5938 * @return {boolean} Part of the element is being clipped
5940 OO.ui.ClippableElement.prototype.isClipped = function () {
5941 return this.clippedHorizontally || this.clippedVertically;
5945 * Check if the right of the element is being clipped by the nearest scrollable container.
5947 * @return {boolean} Part of the element is being clipped
5949 OO.ui.ClippableElement.prototype.isClippedHorizontally = function () {
5950 return this.clippedHorizontally;
5954 * Check if the bottom of the element is being clipped by the nearest scrollable container.
5956 * @return {boolean} Part of the element is being clipped
5958 OO.ui.ClippableElement.prototype.isClippedVertically = function () {
5959 return this.clippedVertically;
5963 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
5965 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
5966 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
5968 OO.ui.ClippableElement.prototype.setIdealSize = function ( width, height ) {
5969 this.idealWidth = width;
5970 this.idealHeight = height;
5972 if ( !this.clipping ) {
5973 // Update dimensions
5974 this.$clippable.css( { width: width, height: height } );
5976 // While clipping, idealWidth and idealHeight are not considered
5980 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
5981 * the element's natural height changes.
5983 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
5984 * overlapped by, the visible area of the nearest scrollable container.
5986 * @chainable
5988 OO.ui.ClippableElement.prototype.clip = function () {
5989 if ( !this.clipping ) {
5990 // this.$clippableContainer and this.$clippableWindow are null, so the below will fail
5991 return this;
5994 var buffer = 7, // Chosen by fair dice roll
5995 cOffset = this.$clippable.offset(),
5996 $container = this.$clippableContainer.is( 'html, body' ) ?
5997 this.$clippableWindow : this.$clippableContainer,
5998 ccOffset = $container.offset() || { top: 0, left: 0 },
5999 ccHeight = $container.innerHeight() - buffer,
6000 ccWidth = $container.innerWidth() - buffer,
6001 cHeight = this.$clippable.outerHeight() + buffer,
6002 cWidth = this.$clippable.outerWidth() + buffer,
6003 scrollTop = this.$clippableScroller.scrollTop(),
6004 scrollLeft = this.$clippableScroller.scrollLeft(),
6005 desiredWidth = cOffset.left < 0 ?
6006 cWidth + cOffset.left :
6007 ( ccOffset.left + scrollLeft + ccWidth ) - cOffset.left,
6008 desiredHeight = cOffset.top < 0 ?
6009 cHeight + cOffset.top :
6010 ( ccOffset.top + scrollTop + ccHeight ) - cOffset.top,
6011 naturalWidth = this.$clippable.prop( 'scrollWidth' ),
6012 naturalHeight = this.$clippable.prop( 'scrollHeight' ),
6013 clipWidth = desiredWidth < naturalWidth,
6014 clipHeight = desiredHeight < naturalHeight;
6016 if ( clipWidth ) {
6017 this.$clippable.css( { overflowX: 'scroll', width: desiredWidth } );
6018 } else {
6019 this.$clippable.css( { width: this.idealWidth || '', overflowX: '' } );
6021 if ( clipHeight ) {
6022 this.$clippable.css( { overflowY: 'scroll', height: desiredHeight } );
6023 } else {
6024 this.$clippable.css( { height: this.idealHeight || '', overflowY: '' } );
6027 // If we stopped clipping in at least one of the dimensions
6028 if ( !clipWidth || !clipHeight ) {
6029 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6032 this.clippedHorizontally = clipWidth;
6033 this.clippedVertically = clipHeight;
6035 return this;
6039 * Generic toolbar tool.
6041 * @abstract
6042 * @class
6043 * @extends OO.ui.Widget
6044 * @mixins OO.ui.IconElement
6045 * @mixins OO.ui.FlaggedElement
6047 * @constructor
6048 * @param {OO.ui.ToolGroup} toolGroup
6049 * @param {Object} [config] Configuration options
6050 * @cfg {string|Function} [title] Title text or a function that returns text
6052 OO.ui.Tool = function OoUiTool( toolGroup, config ) {
6053 // Allow passing positional parameters inside the config object
6054 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
6055 config = toolGroup;
6056 toolGroup = config.toolGroup;
6059 // Configuration initialization
6060 config = config || {};
6062 // Parent constructor
6063 OO.ui.Tool.super.call( this, config );
6065 // Mixin constructors
6066 OO.ui.IconElement.call( this, config );
6067 OO.ui.FlaggedElement.call( this, config );
6069 // Properties
6070 this.toolGroup = toolGroup;
6071 this.toolbar = this.toolGroup.getToolbar();
6072 this.active = false;
6073 this.$title = $( '<span>' );
6074 this.$accel = $( '<span>' );
6075 this.$link = $( '<a>' );
6076 this.title = null;
6078 // Events
6079 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
6081 // Initialization
6082 this.$title.addClass( 'oo-ui-tool-title' );
6083 this.$accel
6084 .addClass( 'oo-ui-tool-accel' )
6085 .prop( {
6086 // This may need to be changed if the key names are ever localized,
6087 // but for now they are essentially written in English
6088 dir: 'ltr',
6089 lang: 'en'
6090 } );
6091 this.$link
6092 .addClass( 'oo-ui-tool-link' )
6093 .append( this.$icon, this.$title, this.$accel )
6094 .prop( 'tabIndex', 0 )
6095 .attr( 'role', 'button' );
6096 this.$element
6097 .data( 'oo-ui-tool', this )
6098 .addClass(
6099 'oo-ui-tool ' + 'oo-ui-tool-name-' +
6100 this.constructor.static.name.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
6102 .append( this.$link );
6103 this.setTitle( config.title || this.constructor.static.title );
6106 /* Setup */
6108 OO.inheritClass( OO.ui.Tool, OO.ui.Widget );
6109 OO.mixinClass( OO.ui.Tool, OO.ui.IconElement );
6110 OO.mixinClass( OO.ui.Tool, OO.ui.FlaggedElement );
6112 /* Events */
6115 * @event select
6118 /* Static Properties */
6121 * @static
6122 * @inheritdoc
6124 OO.ui.Tool.static.tagName = 'span';
6127 * Symbolic name of tool.
6129 * @abstract
6130 * @static
6131 * @inheritable
6132 * @property {string}
6134 OO.ui.Tool.static.name = '';
6137 * Tool group.
6139 * @abstract
6140 * @static
6141 * @inheritable
6142 * @property {string}
6144 OO.ui.Tool.static.group = '';
6147 * Tool title.
6149 * Title is used as a tooltip when the tool is part of a bar tool group, or a label when the tool
6150 * is part of a list or menu tool group. If a trigger is associated with an action by the same name
6151 * as the tool, a description of its keyboard shortcut for the appropriate platform will be
6152 * appended to the title if the tool is part of a bar tool group.
6154 * @abstract
6155 * @static
6156 * @inheritable
6157 * @property {string|Function} Title text or a function that returns text
6159 OO.ui.Tool.static.title = '';
6162 * Tool can be automatically added to catch-all groups.
6164 * @static
6165 * @inheritable
6166 * @property {boolean}
6168 OO.ui.Tool.static.autoAddToCatchall = true;
6171 * Tool can be automatically added to named groups.
6173 * @static
6174 * @property {boolean}
6175 * @inheritable
6177 OO.ui.Tool.static.autoAddToGroup = true;
6180 * Check if this tool is compatible with given data.
6182 * @static
6183 * @inheritable
6184 * @param {Mixed} data Data to check
6185 * @return {boolean} Tool can be used with data
6187 OO.ui.Tool.static.isCompatibleWith = function () {
6188 return false;
6191 /* Methods */
6194 * Handle the toolbar state being updated.
6196 * This is an abstract method that must be overridden in a concrete subclass.
6198 * @abstract
6200 OO.ui.Tool.prototype.onUpdateState = function () {
6201 throw new Error(
6202 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
6207 * Handle the tool being selected.
6209 * This is an abstract method that must be overridden in a concrete subclass.
6211 * @abstract
6213 OO.ui.Tool.prototype.onSelect = function () {
6214 throw new Error(
6215 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
6220 * Check if the button is active.
6222 * @return {boolean} Button is active
6224 OO.ui.Tool.prototype.isActive = function () {
6225 return this.active;
6229 * Make the button appear active or inactive.
6231 * @param {boolean} state Make button appear active
6233 OO.ui.Tool.prototype.setActive = function ( state ) {
6234 this.active = !!state;
6235 if ( this.active ) {
6236 this.$element.addClass( 'oo-ui-tool-active' );
6237 } else {
6238 this.$element.removeClass( 'oo-ui-tool-active' );
6243 * Get the tool title.
6245 * @param {string|Function} title Title text or a function that returns text
6246 * @chainable
6248 OO.ui.Tool.prototype.setTitle = function ( title ) {
6249 this.title = OO.ui.resolveMsg( title );
6250 this.updateTitle();
6251 return this;
6255 * Get the tool title.
6257 * @return {string} Title text
6259 OO.ui.Tool.prototype.getTitle = function () {
6260 return this.title;
6264 * Get the tool's symbolic name.
6266 * @return {string} Symbolic name of tool
6268 OO.ui.Tool.prototype.getName = function () {
6269 return this.constructor.static.name;
6273 * Update the title.
6275 OO.ui.Tool.prototype.updateTitle = function () {
6276 var titleTooltips = this.toolGroup.constructor.static.titleTooltips,
6277 accelTooltips = this.toolGroup.constructor.static.accelTooltips,
6278 accel = this.toolbar.getToolAccelerator( this.constructor.static.name ),
6279 tooltipParts = [];
6281 this.$title.text( this.title );
6282 this.$accel.text( accel );
6284 if ( titleTooltips && typeof this.title === 'string' && this.title.length ) {
6285 tooltipParts.push( this.title );
6287 if ( accelTooltips && typeof accel === 'string' && accel.length ) {
6288 tooltipParts.push( accel );
6290 if ( tooltipParts.length ) {
6291 this.$link.attr( 'title', tooltipParts.join( ' ' ) );
6292 } else {
6293 this.$link.removeAttr( 'title' );
6298 * Destroy tool.
6300 OO.ui.Tool.prototype.destroy = function () {
6301 this.toolbar.disconnect( this );
6302 this.$element.remove();
6306 * Collection of tool groups.
6308 * @class
6309 * @extends OO.ui.Element
6310 * @mixins OO.EventEmitter
6311 * @mixins OO.ui.GroupElement
6313 * @constructor
6314 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
6315 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating tool groups
6316 * @param {Object} [config] Configuration options
6317 * @cfg {boolean} [actions] Add an actions section opposite to the tools
6318 * @cfg {boolean} [shadow] Add a shadow below the toolbar
6320 OO.ui.Toolbar = function OoUiToolbar( toolFactory, toolGroupFactory, config ) {
6321 // Allow passing positional parameters inside the config object
6322 if ( OO.isPlainObject( toolFactory ) && config === undefined ) {
6323 config = toolFactory;
6324 toolFactory = config.toolFactory;
6325 toolGroupFactory = config.toolGroupFactory;
6328 // Configuration initialization
6329 config = config || {};
6331 // Parent constructor
6332 OO.ui.Toolbar.super.call( this, config );
6334 // Mixin constructors
6335 OO.EventEmitter.call( this );
6336 OO.ui.GroupElement.call( this, config );
6338 // Properties
6339 this.toolFactory = toolFactory;
6340 this.toolGroupFactory = toolGroupFactory;
6341 this.groups = [];
6342 this.tools = {};
6343 this.$bar = $( '<div>' );
6344 this.$actions = $( '<div>' );
6345 this.initialized = false;
6347 // Events
6348 this.$element
6349 .add( this.$bar ).add( this.$group ).add( this.$actions )
6350 .on( 'mousedown touchstart', this.onPointerDown.bind( this ) );
6352 // Initialization
6353 this.$group.addClass( 'oo-ui-toolbar-tools' );
6354 if ( config.actions ) {
6355 this.$bar.append( this.$actions.addClass( 'oo-ui-toolbar-actions' ) );
6357 this.$bar
6358 .addClass( 'oo-ui-toolbar-bar' )
6359 .append( this.$group, '<div style="clear:both"></div>' );
6360 if ( config.shadow ) {
6361 this.$bar.append( '<div class="oo-ui-toolbar-shadow"></div>' );
6363 this.$element.addClass( 'oo-ui-toolbar' ).append( this.$bar );
6366 /* Setup */
6368 OO.inheritClass( OO.ui.Toolbar, OO.ui.Element );
6369 OO.mixinClass( OO.ui.Toolbar, OO.EventEmitter );
6370 OO.mixinClass( OO.ui.Toolbar, OO.ui.GroupElement );
6372 /* Methods */
6375 * Get the tool factory.
6377 * @return {OO.ui.ToolFactory} Tool factory
6379 OO.ui.Toolbar.prototype.getToolFactory = function () {
6380 return this.toolFactory;
6384 * Get the tool group factory.
6386 * @return {OO.Factory} Tool group factory
6388 OO.ui.Toolbar.prototype.getToolGroupFactory = function () {
6389 return this.toolGroupFactory;
6393 * Handles mouse down events.
6395 * @param {jQuery.Event} e Mouse down event
6397 OO.ui.Toolbar.prototype.onPointerDown = function ( e ) {
6398 var $closestWidgetToEvent = $( e.target ).closest( '.oo-ui-widget' ),
6399 $closestWidgetToToolbar = this.$element.closest( '.oo-ui-widget' );
6400 if ( !$closestWidgetToEvent.length || $closestWidgetToEvent[ 0 ] === $closestWidgetToToolbar[ 0 ] ) {
6401 return false;
6406 * Sets up handles and preloads required information for the toolbar to work.
6407 * This must be called after it is attached to a visible document and before doing anything else.
6409 OO.ui.Toolbar.prototype.initialize = function () {
6410 this.initialized = true;
6414 * Setup toolbar.
6416 * Tools can be specified in the following ways:
6418 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
6419 * - All tools in a group: `{ group: 'group-name' }`
6420 * - All tools: `'*'` - Using this will make the group a list with a "More" label by default
6422 * @param {Object.<string,Array>} groups List of tool group configurations
6423 * @param {Array|string} [groups.include] Tools to include
6424 * @param {Array|string} [groups.exclude] Tools to exclude
6425 * @param {Array|string} [groups.promote] Tools to promote to the beginning
6426 * @param {Array|string} [groups.demote] Tools to demote to the end
6428 OO.ui.Toolbar.prototype.setup = function ( groups ) {
6429 var i, len, type, group,
6430 items = [],
6431 defaultType = 'bar';
6433 // Cleanup previous groups
6434 this.reset();
6436 // Build out new groups
6437 for ( i = 0, len = groups.length; i < len; i++ ) {
6438 group = groups[ i ];
6439 if ( group.include === '*' ) {
6440 // Apply defaults to catch-all groups
6441 if ( group.type === undefined ) {
6442 group.type = 'list';
6444 if ( group.label === undefined ) {
6445 group.label = OO.ui.msg( 'ooui-toolbar-more' );
6448 // Check type has been registered
6449 type = this.getToolGroupFactory().lookup( group.type ) ? group.type : defaultType;
6450 items.push(
6451 this.getToolGroupFactory().create( type, this, group )
6454 this.addItems( items );
6458 * Remove all tools and groups from the toolbar.
6460 OO.ui.Toolbar.prototype.reset = function () {
6461 var i, len;
6463 this.groups = [];
6464 this.tools = {};
6465 for ( i = 0, len = this.items.length; i < len; i++ ) {
6466 this.items[ i ].destroy();
6468 this.clearItems();
6472 * Destroys toolbar, removing event handlers and DOM elements.
6474 * Call this whenever you are done using a toolbar.
6476 OO.ui.Toolbar.prototype.destroy = function () {
6477 this.reset();
6478 this.$element.remove();
6482 * Check if tool has not been used yet.
6484 * @param {string} name Symbolic name of tool
6485 * @return {boolean} Tool is available
6487 OO.ui.Toolbar.prototype.isToolAvailable = function ( name ) {
6488 return !this.tools[ name ];
6492 * Prevent tool from being used again.
6494 * @param {OO.ui.Tool} tool Tool to reserve
6496 OO.ui.Toolbar.prototype.reserveTool = function ( tool ) {
6497 this.tools[ tool.getName() ] = tool;
6501 * Allow tool to be used again.
6503 * @param {OO.ui.Tool} tool Tool to release
6505 OO.ui.Toolbar.prototype.releaseTool = function ( tool ) {
6506 delete this.tools[ tool.getName() ];
6510 * Get accelerator label for tool.
6512 * This is a stub that should be overridden to provide access to accelerator information.
6514 * @param {string} name Symbolic name of tool
6515 * @return {string|undefined} Tool accelerator label if available
6517 OO.ui.Toolbar.prototype.getToolAccelerator = function () {
6518 return undefined;
6522 * Collection of tools.
6524 * Tools can be specified in the following ways:
6526 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
6527 * - All tools in a group: `{ group: 'group-name' }`
6528 * - All tools: `'*'`
6530 * @abstract
6531 * @class
6532 * @extends OO.ui.Widget
6533 * @mixins OO.ui.GroupElement
6535 * @constructor
6536 * @param {OO.ui.Toolbar} toolbar
6537 * @param {Object} [config] Configuration options
6538 * @cfg {Array|string} [include=[]] List of tools to include
6539 * @cfg {Array|string} [exclude=[]] List of tools to exclude
6540 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning
6541 * @cfg {Array|string} [demote=[]] List of tools to demote to the end
6543 OO.ui.ToolGroup = function OoUiToolGroup( toolbar, config ) {
6544 // Allow passing positional parameters inside the config object
6545 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
6546 config = toolbar;
6547 toolbar = config.toolbar;
6550 // Configuration initialization
6551 config = config || {};
6553 // Parent constructor
6554 OO.ui.ToolGroup.super.call( this, config );
6556 // Mixin constructors
6557 OO.ui.GroupElement.call( this, config );
6559 // Properties
6560 this.toolbar = toolbar;
6561 this.tools = {};
6562 this.pressed = null;
6563 this.autoDisabled = false;
6564 this.include = config.include || [];
6565 this.exclude = config.exclude || [];
6566 this.promote = config.promote || [];
6567 this.demote = config.demote || [];
6568 this.onCapturedMouseUpHandler = this.onCapturedMouseUp.bind( this );
6570 // Events
6571 this.$element.on( {
6572 'mousedown touchstart': this.onPointerDown.bind( this ),
6573 'mouseup touchend': this.onPointerUp.bind( this ),
6574 mouseover: this.onMouseOver.bind( this ),
6575 mouseout: this.onMouseOut.bind( this )
6576 } );
6577 this.toolbar.getToolFactory().connect( this, { register: 'onToolFactoryRegister' } );
6578 this.aggregate( { disable: 'itemDisable' } );
6579 this.connect( this, { itemDisable: 'updateDisabled' } );
6581 // Initialization
6582 this.$group.addClass( 'oo-ui-toolGroup-tools' );
6583 this.$element
6584 .addClass( 'oo-ui-toolGroup' )
6585 .append( this.$group );
6586 this.populate();
6589 /* Setup */
6591 OO.inheritClass( OO.ui.ToolGroup, OO.ui.Widget );
6592 OO.mixinClass( OO.ui.ToolGroup, OO.ui.GroupElement );
6594 /* Events */
6597 * @event update
6600 /* Static Properties */
6603 * Show labels in tooltips.
6605 * @static
6606 * @inheritable
6607 * @property {boolean}
6609 OO.ui.ToolGroup.static.titleTooltips = false;
6612 * Show acceleration labels in tooltips.
6614 * @static
6615 * @inheritable
6616 * @property {boolean}
6618 OO.ui.ToolGroup.static.accelTooltips = false;
6621 * Automatically disable the toolgroup when all tools are disabled
6623 * @static
6624 * @inheritable
6625 * @property {boolean}
6627 OO.ui.ToolGroup.static.autoDisable = true;
6629 /* Methods */
6632 * @inheritdoc
6634 OO.ui.ToolGroup.prototype.isDisabled = function () {
6635 return this.autoDisabled || OO.ui.ToolGroup.super.prototype.isDisabled.apply( this, arguments );
6639 * @inheritdoc
6641 OO.ui.ToolGroup.prototype.updateDisabled = function () {
6642 var i, item, allDisabled = true;
6644 if ( this.constructor.static.autoDisable ) {
6645 for ( i = this.items.length - 1; i >= 0; i-- ) {
6646 item = this.items[ i ];
6647 if ( !item.isDisabled() ) {
6648 allDisabled = false;
6649 break;
6652 this.autoDisabled = allDisabled;
6654 OO.ui.ToolGroup.super.prototype.updateDisabled.apply( this, arguments );
6658 * Handle mouse down events.
6660 * @param {jQuery.Event} e Mouse down event
6662 OO.ui.ToolGroup.prototype.onPointerDown = function ( e ) {
6663 // e.which is 0 for touch events, 1 for left mouse button
6664 if ( !this.isDisabled() && e.which <= 1 ) {
6665 this.pressed = this.getTargetTool( e );
6666 if ( this.pressed ) {
6667 this.pressed.setActive( true );
6668 this.getElementDocument().addEventListener(
6669 'mouseup', this.onCapturedMouseUpHandler, true
6673 return false;
6677 * Handle captured mouse up events.
6679 * @param {Event} e Mouse up event
6681 OO.ui.ToolGroup.prototype.onCapturedMouseUp = function ( e ) {
6682 this.getElementDocument().removeEventListener( 'mouseup', this.onCapturedMouseUpHandler, true );
6683 // onPointerUp may be called a second time, depending on where the mouse is when the button is
6684 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
6685 this.onPointerUp( e );
6689 * Handle mouse up events.
6691 * @param {jQuery.Event} e Mouse up event
6693 OO.ui.ToolGroup.prototype.onPointerUp = function ( e ) {
6694 var tool = this.getTargetTool( e );
6696 // e.which is 0 for touch events, 1 for left mouse button
6697 if ( !this.isDisabled() && e.which <= 1 && this.pressed && this.pressed === tool ) {
6698 this.pressed.onSelect();
6701 this.pressed = null;
6702 return false;
6706 * Handle mouse over events.
6708 * @param {jQuery.Event} e Mouse over event
6710 OO.ui.ToolGroup.prototype.onMouseOver = function ( e ) {
6711 var tool = this.getTargetTool( e );
6713 if ( this.pressed && this.pressed === tool ) {
6714 this.pressed.setActive( true );
6719 * Handle mouse out events.
6721 * @param {jQuery.Event} e Mouse out event
6723 OO.ui.ToolGroup.prototype.onMouseOut = function ( e ) {
6724 var tool = this.getTargetTool( e );
6726 if ( this.pressed && this.pressed === tool ) {
6727 this.pressed.setActive( false );
6732 * Get the closest tool to a jQuery.Event.
6734 * Only tool links are considered, which prevents other elements in the tool such as popups from
6735 * triggering tool group interactions.
6737 * @private
6738 * @param {jQuery.Event} e
6739 * @return {OO.ui.Tool|null} Tool, `null` if none was found
6741 OO.ui.ToolGroup.prototype.getTargetTool = function ( e ) {
6742 var tool,
6743 $item = $( e.target ).closest( '.oo-ui-tool-link' );
6745 if ( $item.length ) {
6746 tool = $item.parent().data( 'oo-ui-tool' );
6749 return tool && !tool.isDisabled() ? tool : null;
6753 * Handle tool registry register events.
6755 * If a tool is registered after the group is created, we must repopulate the list to account for:
6757 * - a tool being added that may be included
6758 * - a tool already included being overridden
6760 * @param {string} name Symbolic name of tool
6762 OO.ui.ToolGroup.prototype.onToolFactoryRegister = function () {
6763 this.populate();
6767 * Get the toolbar this group is in.
6769 * @return {OO.ui.Toolbar} Toolbar of group
6771 OO.ui.ToolGroup.prototype.getToolbar = function () {
6772 return this.toolbar;
6776 * Add and remove tools based on configuration.
6778 OO.ui.ToolGroup.prototype.populate = function () {
6779 var i, len, name, tool,
6780 toolFactory = this.toolbar.getToolFactory(),
6781 names = {},
6782 add = [],
6783 remove = [],
6784 list = this.toolbar.getToolFactory().getTools(
6785 this.include, this.exclude, this.promote, this.demote
6788 // Build a list of needed tools
6789 for ( i = 0, len = list.length; i < len; i++ ) {
6790 name = list[ i ];
6791 if (
6792 // Tool exists
6793 toolFactory.lookup( name ) &&
6794 // Tool is available or is already in this group
6795 ( this.toolbar.isToolAvailable( name ) || this.tools[ name ] )
6797 tool = this.tools[ name ];
6798 if ( !tool ) {
6799 // Auto-initialize tools on first use
6800 this.tools[ name ] = tool = toolFactory.create( name, this );
6801 tool.updateTitle();
6803 this.toolbar.reserveTool( tool );
6804 add.push( tool );
6805 names[ name ] = true;
6808 // Remove tools that are no longer needed
6809 for ( name in this.tools ) {
6810 if ( !names[ name ] ) {
6811 this.tools[ name ].destroy();
6812 this.toolbar.releaseTool( this.tools[ name ] );
6813 remove.push( this.tools[ name ] );
6814 delete this.tools[ name ];
6817 if ( remove.length ) {
6818 this.removeItems( remove );
6820 // Update emptiness state
6821 if ( add.length ) {
6822 this.$element.removeClass( 'oo-ui-toolGroup-empty' );
6823 } else {
6824 this.$element.addClass( 'oo-ui-toolGroup-empty' );
6826 // Re-add tools (moving existing ones to new locations)
6827 this.addItems( add );
6828 // Disabled state may depend on items
6829 this.updateDisabled();
6833 * Destroy tool group.
6835 OO.ui.ToolGroup.prototype.destroy = function () {
6836 var name;
6838 this.clearItems();
6839 this.toolbar.getToolFactory().disconnect( this );
6840 for ( name in this.tools ) {
6841 this.toolbar.releaseTool( this.tools[ name ] );
6842 this.tools[ name ].disconnect( this ).destroy();
6843 delete this.tools[ name ];
6845 this.$element.remove();
6849 * Dialog for showing a message.
6851 * User interface:
6852 * - Registers two actions by default (safe and primary).
6853 * - Renders action widgets in the footer.
6855 * @class
6856 * @extends OO.ui.Dialog
6858 * @constructor
6859 * @param {Object} [config] Configuration options
6861 OO.ui.MessageDialog = function OoUiMessageDialog( config ) {
6862 // Parent constructor
6863 OO.ui.MessageDialog.super.call( this, config );
6865 // Properties
6866 this.verticalActionLayout = null;
6868 // Initialization
6869 this.$element.addClass( 'oo-ui-messageDialog' );
6872 /* Inheritance */
6874 OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog );
6876 /* Static Properties */
6878 OO.ui.MessageDialog.static.name = 'message';
6880 OO.ui.MessageDialog.static.size = 'small';
6882 OO.ui.MessageDialog.static.verbose = false;
6885 * Dialog title.
6887 * A confirmation dialog's title should describe what the progressive action will do. An alert
6888 * dialog's title should describe what event occurred.
6890 * @static
6891 * inheritable
6892 * @property {jQuery|string|Function|null}
6894 OO.ui.MessageDialog.static.title = null;
6897 * A confirmation dialog's message should describe the consequences of the progressive action. An
6898 * alert dialog's message should describe why the event occurred.
6900 * @static
6901 * inheritable
6902 * @property {jQuery|string|Function|null}
6904 OO.ui.MessageDialog.static.message = null;
6906 OO.ui.MessageDialog.static.actions = [
6907 { action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' },
6908 { action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' }
6911 /* Methods */
6914 * @inheritdoc
6916 OO.ui.MessageDialog.prototype.setManager = function ( manager ) {
6917 OO.ui.MessageDialog.super.prototype.setManager.call( this, manager );
6919 // Events
6920 this.manager.connect( this, {
6921 resize: 'onResize'
6922 } );
6924 return this;
6928 * @inheritdoc
6930 OO.ui.MessageDialog.prototype.onActionResize = function ( action ) {
6931 this.fitActions();
6932 return OO.ui.MessageDialog.super.prototype.onActionResize.call( this, action );
6936 * Handle window resized events.
6938 OO.ui.MessageDialog.prototype.onResize = function () {
6939 var dialog = this;
6940 dialog.fitActions();
6941 // Wait for CSS transition to finish and do it again :(
6942 setTimeout( function () {
6943 dialog.fitActions();
6944 }, 300 );
6948 * Toggle action layout between vertical and horizontal.
6950 * @param {boolean} [value] Layout actions vertically, omit to toggle
6951 * @chainable
6953 OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) {
6954 value = value === undefined ? !this.verticalActionLayout : !!value;
6956 if ( value !== this.verticalActionLayout ) {
6957 this.verticalActionLayout = value;
6958 this.$actions
6959 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value )
6960 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value );
6963 return this;
6967 * @inheritdoc
6969 OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) {
6970 if ( action ) {
6971 return new OO.ui.Process( function () {
6972 this.close( { action: action } );
6973 }, this );
6975 return OO.ui.MessageDialog.super.prototype.getActionProcess.call( this, action );
6979 * @inheritdoc
6981 * @param {Object} [data] Dialog opening data
6982 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
6983 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
6984 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
6985 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
6986 * action item
6988 OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) {
6989 data = data || {};
6991 // Parent method
6992 return OO.ui.MessageDialog.super.prototype.getSetupProcess.call( this, data )
6993 .next( function () {
6994 this.title.setLabel(
6995 data.title !== undefined ? data.title : this.constructor.static.title
6997 this.message.setLabel(
6998 data.message !== undefined ? data.message : this.constructor.static.message
7000 this.message.$element.toggleClass(
7001 'oo-ui-messageDialog-message-verbose',
7002 data.verbose !== undefined ? data.verbose : this.constructor.static.verbose
7004 }, this );
7008 * @inheritdoc
7010 OO.ui.MessageDialog.prototype.getBodyHeight = function () {
7011 var bodyHeight, oldOverflow,
7012 $scrollable = this.container.$element;
7014 oldOverflow = $scrollable[ 0 ].style.overflow;
7015 $scrollable[ 0 ].style.overflow = 'hidden';
7017 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
7019 bodyHeight = this.text.$element.outerHeight( true );
7020 $scrollable[ 0 ].style.overflow = oldOverflow;
7022 return bodyHeight;
7026 * @inheritdoc
7028 OO.ui.MessageDialog.prototype.setDimensions = function ( dim ) {
7029 var $scrollable = this.container.$element;
7030 OO.ui.MessageDialog.super.prototype.setDimensions.call( this, dim );
7032 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
7033 // Need to do it after transition completes (250ms), add 50ms just in case.
7034 setTimeout( function () {
7035 var oldOverflow = $scrollable[ 0 ].style.overflow;
7036 $scrollable[ 0 ].style.overflow = 'hidden';
7038 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
7040 $scrollable[ 0 ].style.overflow = oldOverflow;
7041 }, 300 );
7043 return this;
7047 * @inheritdoc
7049 OO.ui.MessageDialog.prototype.initialize = function () {
7050 // Parent method
7051 OO.ui.MessageDialog.super.prototype.initialize.call( this );
7053 // Properties
7054 this.$actions = $( '<div>' );
7055 this.container = new OO.ui.PanelLayout( {
7056 scrollable: true, classes: [ 'oo-ui-messageDialog-container' ]
7057 } );
7058 this.text = new OO.ui.PanelLayout( {
7059 padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ]
7060 } );
7061 this.message = new OO.ui.LabelWidget( {
7062 classes: [ 'oo-ui-messageDialog-message' ]
7063 } );
7065 // Initialization
7066 this.title.$element.addClass( 'oo-ui-messageDialog-title' );
7067 this.$content.addClass( 'oo-ui-messageDialog-content' );
7068 this.container.$element.append( this.text.$element );
7069 this.text.$element.append( this.title.$element, this.message.$element );
7070 this.$body.append( this.container.$element );
7071 this.$actions.addClass( 'oo-ui-messageDialog-actions' );
7072 this.$foot.append( this.$actions );
7076 * @inheritdoc
7078 OO.ui.MessageDialog.prototype.attachActions = function () {
7079 var i, len, other, special, others;
7081 // Parent method
7082 OO.ui.MessageDialog.super.prototype.attachActions.call( this );
7084 special = this.actions.getSpecial();
7085 others = this.actions.getOthers();
7086 if ( special.safe ) {
7087 this.$actions.append( special.safe.$element );
7088 special.safe.toggleFramed( false );
7090 if ( others.length ) {
7091 for ( i = 0, len = others.length; i < len; i++ ) {
7092 other = others[ i ];
7093 this.$actions.append( other.$element );
7094 other.toggleFramed( false );
7097 if ( special.primary ) {
7098 this.$actions.append( special.primary.$element );
7099 special.primary.toggleFramed( false );
7102 if ( !this.isOpening() ) {
7103 // If the dialog is currently opening, this will be called automatically soon.
7104 // This also calls #fitActions.
7105 this.updateSize();
7110 * Fit action actions into columns or rows.
7112 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
7114 OO.ui.MessageDialog.prototype.fitActions = function () {
7115 var i, len, action,
7116 previous = this.verticalActionLayout,
7117 actions = this.actions.get();
7119 // Detect clipping
7120 this.toggleVerticalActionLayout( false );
7121 for ( i = 0, len = actions.length; i < len; i++ ) {
7122 action = actions[ i ];
7123 if ( action.$element.innerWidth() < action.$label.outerWidth( true ) ) {
7124 this.toggleVerticalActionLayout( true );
7125 break;
7129 // Move the body out of the way of the foot
7130 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
7132 if ( this.verticalActionLayout !== previous ) {
7133 // We changed the layout, window height might need to be updated.
7134 this.updateSize();
7139 * Navigation dialog window.
7141 * Logic:
7142 * - Show and hide errors.
7143 * - Retry an action.
7145 * User interface:
7146 * - Renders header with dialog title and one action widget on either side
7147 * (a 'safe' button on the left, and a 'primary' button on the right, both of
7148 * which close the dialog).
7149 * - Displays any action widgets in the footer (none by default).
7150 * - Ability to dismiss errors.
7152 * Subclass responsibilities:
7153 * - Register a 'safe' action.
7154 * - Register a 'primary' action.
7155 * - Add content to the dialog.
7157 * @abstract
7158 * @class
7159 * @extends OO.ui.Dialog
7161 * @constructor
7162 * @param {Object} [config] Configuration options
7164 OO.ui.ProcessDialog = function OoUiProcessDialog( config ) {
7165 // Parent constructor
7166 OO.ui.ProcessDialog.super.call( this, config );
7168 // Initialization
7169 this.$element.addClass( 'oo-ui-processDialog' );
7172 /* Setup */
7174 OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog );
7176 /* Methods */
7179 * Handle dismiss button click events.
7181 * Hides errors.
7183 OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () {
7184 this.hideErrors();
7188 * Handle retry button click events.
7190 * Hides errors and then tries again.
7192 OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () {
7193 this.hideErrors();
7194 this.executeAction( this.currentAction.getAction() );
7198 * @inheritdoc
7200 OO.ui.ProcessDialog.prototype.onActionResize = function ( action ) {
7201 if ( this.actions.isSpecial( action ) ) {
7202 this.fitLabel();
7204 return OO.ui.ProcessDialog.super.prototype.onActionResize.call( this, action );
7208 * @inheritdoc
7210 OO.ui.ProcessDialog.prototype.initialize = function () {
7211 // Parent method
7212 OO.ui.ProcessDialog.super.prototype.initialize.call( this );
7214 // Properties
7215 this.$navigation = $( '<div>' );
7216 this.$location = $( '<div>' );
7217 this.$safeActions = $( '<div>' );
7218 this.$primaryActions = $( '<div>' );
7219 this.$otherActions = $( '<div>' );
7220 this.dismissButton = new OO.ui.ButtonWidget( {
7221 label: OO.ui.msg( 'ooui-dialog-process-dismiss' )
7222 } );
7223 this.retryButton = new OO.ui.ButtonWidget();
7224 this.$errors = $( '<div>' );
7225 this.$errorsTitle = $( '<div>' );
7227 // Events
7228 this.dismissButton.connect( this, { click: 'onDismissErrorButtonClick' } );
7229 this.retryButton.connect( this, { click: 'onRetryButtonClick' } );
7231 // Initialization
7232 this.title.$element.addClass( 'oo-ui-processDialog-title' );
7233 this.$location
7234 .append( this.title.$element )
7235 .addClass( 'oo-ui-processDialog-location' );
7236 this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' );
7237 this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' );
7238 this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' );
7239 this.$errorsTitle
7240 .addClass( 'oo-ui-processDialog-errors-title' )
7241 .text( OO.ui.msg( 'ooui-dialog-process-error' ) );
7242 this.$errors
7243 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
7244 .append( this.$errorsTitle, this.dismissButton.$element, this.retryButton.$element );
7245 this.$content
7246 .addClass( 'oo-ui-processDialog-content' )
7247 .append( this.$errors );
7248 this.$navigation
7249 .addClass( 'oo-ui-processDialog-navigation' )
7250 .append( this.$safeActions, this.$location, this.$primaryActions );
7251 this.$head.append( this.$navigation );
7252 this.$foot.append( this.$otherActions );
7256 * @inheritdoc
7258 OO.ui.ProcessDialog.prototype.attachActions = function () {
7259 var i, len, other, special, others;
7261 // Parent method
7262 OO.ui.ProcessDialog.super.prototype.attachActions.call( this );
7264 special = this.actions.getSpecial();
7265 others = this.actions.getOthers();
7266 if ( special.primary ) {
7267 this.$primaryActions.append( special.primary.$element );
7268 special.primary.toggleFramed( true );
7270 for ( i = 0, len = others.length; i < len; i++ ) {
7271 other = others[ i ];
7272 this.$otherActions.append( other.$element );
7273 other.toggleFramed( true );
7275 if ( special.safe ) {
7276 this.$safeActions.append( special.safe.$element );
7277 special.safe.toggleFramed( true );
7280 this.fitLabel();
7281 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
7285 * @inheritdoc
7287 OO.ui.ProcessDialog.prototype.executeAction = function ( action ) {
7288 OO.ui.ProcessDialog.super.prototype.executeAction.call( this, action )
7289 .fail( this.showErrors.bind( this ) );
7293 * Fit label between actions.
7295 * @chainable
7297 OO.ui.ProcessDialog.prototype.fitLabel = function () {
7298 var width = Math.max(
7299 this.$safeActions.is( ':visible' ) ? this.$safeActions.width() : 0,
7300 this.$primaryActions.is( ':visible' ) ? this.$primaryActions.width() : 0
7302 this.$location.css( { paddingLeft: width, paddingRight: width } );
7304 return this;
7308 * Handle errors that occurred during accept or reject processes.
7310 * @param {OO.ui.Error[]} errors Errors to be handled
7312 OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) {
7313 var i, len, $item,
7314 items = [],
7315 recoverable = true,
7316 warning = false;
7318 for ( i = 0, len = errors.length; i < len; i++ ) {
7319 if ( !errors[ i ].isRecoverable() ) {
7320 recoverable = false;
7322 if ( errors[ i ].isWarning() ) {
7323 warning = true;
7325 $item = $( '<div>' )
7326 .addClass( 'oo-ui-processDialog-error' )
7327 .append( errors[ i ].getMessage() );
7328 items.push( $item[ 0 ] );
7330 this.$errorItems = $( items );
7331 if ( recoverable ) {
7332 this.retryButton.clearFlags().setFlags( this.currentAction.getFlags() );
7333 } else {
7334 this.currentAction.setDisabled( true );
7336 if ( warning ) {
7337 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-continue' ) );
7338 } else {
7339 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-retry' ) );
7341 this.retryButton.toggle( recoverable );
7342 this.$errorsTitle.after( this.$errorItems );
7343 this.$errors.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
7347 * Hide errors.
7349 OO.ui.ProcessDialog.prototype.hideErrors = function () {
7350 this.$errors.addClass( 'oo-ui-element-hidden' );
7351 this.$errorItems.remove();
7352 this.$errorItems = null;
7356 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
7357 * which is a widget that is specified by reference before any optional configuration settings.
7359 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
7361 * - **left**: The label is placed before the field-widget and aligned with the left margin.
7362 * A left-alignment is used for forms with many fields.
7363 * - **right**: The label is placed before the field-widget and aligned to the right margin.
7364 * A right-alignment is used for long but familiar forms which users tab through,
7365 * verifying the current field with a quick glance at the label.
7366 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
7367 * that users fill out from top to bottom.
7368 * - **inline**: The label is placed after the field-widget and aligned to the left.
7369 An inline-alignment is best used with checkboxes or radio buttons.
7371 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
7372 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
7374 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
7375 * @class
7376 * @extends OO.ui.Layout
7377 * @mixins OO.ui.LabelElement
7379 * @constructor
7380 * @param {OO.ui.Widget} fieldWidget Field widget
7381 * @param {Object} [config] Configuration options
7382 * @cfg {string} [align='left'] Alignment mode, either 'left', 'right', 'top' or 'inline'
7383 * @cfg {string} [help] Explanatory text shown as a '?' icon.
7385 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
7386 // Allow passing positional parameters inside the config object
7387 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
7388 config = fieldWidget;
7389 fieldWidget = config.fieldWidget;
7392 var hasInputWidget = fieldWidget instanceof OO.ui.InputWidget;
7394 // Configuration initialization
7395 config = $.extend( { align: 'left' }, config );
7397 // Parent constructor
7398 OO.ui.FieldLayout.super.call( this, config );
7400 // Mixin constructors
7401 OO.ui.LabelElement.call( this, config );
7403 // Properties
7404 this.fieldWidget = fieldWidget;
7405 this.$field = $( '<div>' );
7406 this.$body = $( '<' + ( hasInputWidget ? 'label' : 'div' ) + '>' );
7407 this.align = null;
7408 if ( config.help ) {
7409 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
7410 classes: [ 'oo-ui-fieldLayout-help' ],
7411 framed: false,
7412 icon: 'info'
7413 } );
7415 this.popupButtonWidget.getPopup().$body.append(
7416 $( '<div>' )
7417 .text( config.help )
7418 .addClass( 'oo-ui-fieldLayout-help-content' )
7420 this.$help = this.popupButtonWidget.$element;
7421 } else {
7422 this.$help = $( [] );
7425 // Events
7426 if ( hasInputWidget ) {
7427 this.$label.on( 'click', this.onLabelClick.bind( this ) );
7429 this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
7431 // Initialization
7432 this.$element
7433 .addClass( 'oo-ui-fieldLayout' )
7434 .append( this.$help, this.$body );
7435 this.$body.addClass( 'oo-ui-fieldLayout-body' );
7436 this.$field
7437 .addClass( 'oo-ui-fieldLayout-field' )
7438 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget.isDisabled() )
7439 .append( this.fieldWidget.$element );
7441 this.setAlignment( config.align );
7444 /* Setup */
7446 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
7447 OO.mixinClass( OO.ui.FieldLayout, OO.ui.LabelElement );
7449 /* Methods */
7452 * Handle field disable events.
7454 * @param {boolean} value Field is disabled
7456 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
7457 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
7461 * Handle label mouse click events.
7463 * @param {jQuery.Event} e Mouse click event
7465 OO.ui.FieldLayout.prototype.onLabelClick = function () {
7466 this.fieldWidget.simulateLabelClick();
7467 return false;
7471 * Get the field.
7473 * @return {OO.ui.Widget} Field widget
7475 OO.ui.FieldLayout.prototype.getField = function () {
7476 return this.fieldWidget;
7480 * Set the field alignment mode.
7482 * @private
7483 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
7484 * @chainable
7486 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
7487 if ( value !== this.align ) {
7488 // Default to 'left'
7489 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
7490 value = 'left';
7492 // Reorder elements
7493 if ( value === 'inline' ) {
7494 this.$body.append( this.$field, this.$label );
7495 } else {
7496 this.$body.append( this.$label, this.$field );
7498 // Set classes. The following classes can be used here:
7499 // * oo-ui-fieldLayout-align-left
7500 // * oo-ui-fieldLayout-align-right
7501 // * oo-ui-fieldLayout-align-top
7502 // * oo-ui-fieldLayout-align-inline
7503 if ( this.align ) {
7504 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
7506 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
7507 this.align = value;
7510 return this;
7514 * Layout made of a field, a button, and an optional label.
7516 * @class
7517 * @extends OO.ui.FieldLayout
7519 * @constructor
7520 * @param {OO.ui.Widget} fieldWidget Field widget
7521 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
7522 * @param {Object} [config] Configuration options
7523 * @cfg {string} [align='left'] Alignment mode, either 'left', 'right', 'top' or 'inline'
7524 * @cfg {string} [help] Explanatory text shown as a '?' icon.
7526 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
7527 // Allow passing positional parameters inside the config object
7528 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
7529 config = fieldWidget;
7530 fieldWidget = config.fieldWidget;
7531 buttonWidget = config.buttonWidget;
7534 // Configuration initialization
7535 config = $.extend( { align: 'left' }, config );
7537 // Parent constructor
7538 OO.ui.ActionFieldLayout.super.call( this, fieldWidget, config );
7540 // Mixin constructors
7541 OO.ui.LabelElement.call( this, config );
7543 // Properties
7544 this.fieldWidget = fieldWidget;
7545 this.buttonWidget = buttonWidget;
7546 this.$button = $( '<div>' )
7547 .addClass( 'oo-ui-actionFieldLayout-button' )
7548 .append( this.buttonWidget.$element );
7549 this.$input = $( '<div>' )
7550 .addClass( 'oo-ui-actionFieldLayout-input' )
7551 .append( this.fieldWidget.$element );
7552 this.$field
7553 .addClass( 'oo-ui-actionFieldLayout' )
7554 .append( this.$input, this.$button );
7557 /* Setup */
7559 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
7562 * Layout made of a fieldset and optional legend.
7564 * Just add OO.ui.FieldLayout items.
7566 * @class
7567 * @extends OO.ui.Layout
7568 * @mixins OO.ui.IconElement
7569 * @mixins OO.ui.LabelElement
7570 * @mixins OO.ui.GroupElement
7572 * @constructor
7573 * @param {Object} [config] Configuration options
7574 * @cfg {OO.ui.FieldLayout[]} [items] Items to add
7576 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
7577 // Configuration initialization
7578 config = config || {};
7580 // Parent constructor
7581 OO.ui.FieldsetLayout.super.call( this, config );
7583 // Mixin constructors
7584 OO.ui.IconElement.call( this, config );
7585 OO.ui.LabelElement.call( this, config );
7586 OO.ui.GroupElement.call( this, config );
7588 if ( config.help ) {
7589 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
7590 classes: [ 'oo-ui-fieldsetLayout-help' ],
7591 framed: false,
7592 icon: 'info'
7593 } );
7595 this.popupButtonWidget.getPopup().$body.append(
7596 $( '<div>' )
7597 .text( config.help )
7598 .addClass( 'oo-ui-fieldsetLayout-help-content' )
7600 this.$help = this.popupButtonWidget.$element;
7601 } else {
7602 this.$help = $( [] );
7605 // Initialization
7606 this.$element
7607 .addClass( 'oo-ui-fieldsetLayout' )
7608 .prepend( this.$help, this.$icon, this.$label, this.$group );
7609 if ( Array.isArray( config.items ) ) {
7610 this.addItems( config.items );
7614 /* Setup */
7616 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
7617 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.IconElement );
7618 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.LabelElement );
7619 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.GroupElement );
7622 * Layout with an HTML form.
7624 * @class
7625 * @extends OO.ui.Layout
7626 * @mixins OO.ui.GroupElement
7628 * @constructor
7629 * @param {Object} [config] Configuration options
7630 * @cfg {string} [method] HTML form `method` attribute
7631 * @cfg {string} [action] HTML form `action` attribute
7632 * @cfg {string} [enctype] HTML form `enctype` attribute
7633 * @cfg {OO.ui.FieldsetLayout[]} [items] Items to add
7635 OO.ui.FormLayout = function OoUiFormLayout( config ) {
7636 // Configuration initialization
7637 config = config || {};
7639 // Parent constructor
7640 OO.ui.FormLayout.super.call( this, config );
7642 // Mixin constructors
7643 OO.ui.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
7645 // Events
7646 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
7648 // Initialization
7649 this.$element
7650 .addClass( 'oo-ui-formLayout' )
7651 .attr( {
7652 method: config.method,
7653 action: config.action,
7654 enctype: config.enctype
7655 } );
7656 if ( Array.isArray( config.items ) ) {
7657 this.addItems( config.items );
7661 /* Setup */
7663 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
7664 OO.mixinClass( OO.ui.FormLayout, OO.ui.GroupElement );
7666 /* Events */
7669 * The HTML form was submitted. If the submission is handled, call `e.preventDefault()` to prevent
7670 * HTML form submission.
7672 * @event submit
7673 * @param {jQuery.Event} e Submit event
7676 /* Static Properties */
7678 OO.ui.FormLayout.static.tagName = 'form';
7680 /* Methods */
7683 * Handle form submit events.
7685 * @param {jQuery.Event} e Submit event
7686 * @fires submit
7688 OO.ui.FormLayout.prototype.onFormSubmit = function ( e ) {
7689 this.emit( 'submit', e );
7693 * Layout made of proportionally sized columns and rows.
7695 * @class
7696 * @extends OO.ui.Layout
7697 * @deprecated Use OO.ui.MenuLayout or plain CSS instead.
7699 * @constructor
7700 * @param {OO.ui.PanelLayout[]} panels Panels in the grid
7701 * @param {Object} [config] Configuration options
7702 * @cfg {number[]} [widths] Widths of columns as ratios
7703 * @cfg {number[]} [heights] Heights of rows as ratios
7705 OO.ui.GridLayout = function OoUiGridLayout( panels, config ) {
7706 // Allow passing positional parameters inside the config object
7707 if ( OO.isPlainObject( panels ) && config === undefined ) {
7708 config = panels;
7709 panels = config.panels;
7712 var i, len, widths;
7714 // Configuration initialization
7715 config = config || {};
7717 // Parent constructor
7718 OO.ui.GridLayout.super.call( this, config );
7720 // Properties
7721 this.panels = [];
7722 this.widths = [];
7723 this.heights = [];
7725 // Initialization
7726 this.$element.addClass( 'oo-ui-gridLayout' );
7727 for ( i = 0, len = panels.length; i < len; i++ ) {
7728 this.panels.push( panels[ i ] );
7729 this.$element.append( panels[ i ].$element );
7731 if ( config.widths || config.heights ) {
7732 this.layout( config.widths || [ 1 ], config.heights || [ 1 ] );
7733 } else {
7734 // Arrange in columns by default
7735 widths = this.panels.map( function () { return 1; } );
7736 this.layout( widths, [ 1 ] );
7740 /* Setup */
7742 OO.inheritClass( OO.ui.GridLayout, OO.ui.Layout );
7744 /* Events */
7747 * @event layout
7751 * @event update
7754 /* Methods */
7757 * Set grid dimensions.
7759 * @param {number[]} widths Widths of columns as ratios
7760 * @param {number[]} heights Heights of rows as ratios
7761 * @fires layout
7762 * @throws {Error} If grid is not large enough to fit all panels
7764 OO.ui.GridLayout.prototype.layout = function ( widths, heights ) {
7765 var x, y,
7766 xd = 0,
7767 yd = 0,
7768 cols = widths.length,
7769 rows = heights.length;
7771 // Verify grid is big enough to fit panels
7772 if ( cols * rows < this.panels.length ) {
7773 throw new Error( 'Grid is not large enough to fit ' + this.panels.length + 'panels' );
7776 // Sum up denominators
7777 for ( x = 0; x < cols; x++ ) {
7778 xd += widths[ x ];
7780 for ( y = 0; y < rows; y++ ) {
7781 yd += heights[ y ];
7783 // Store factors
7784 this.widths = [];
7785 this.heights = [];
7786 for ( x = 0; x < cols; x++ ) {
7787 this.widths[ x ] = widths[ x ] / xd;
7789 for ( y = 0; y < rows; y++ ) {
7790 this.heights[ y ] = heights[ y ] / yd;
7792 // Synchronize view
7793 this.update();
7794 this.emit( 'layout' );
7798 * Update panel positions and sizes.
7800 * @fires update
7802 OO.ui.GridLayout.prototype.update = function () {
7803 var x, y, panel, width, height, dimensions,
7804 i = 0,
7805 top = 0,
7806 left = 0,
7807 cols = this.widths.length,
7808 rows = this.heights.length;
7810 for ( y = 0; y < rows; y++ ) {
7811 height = this.heights[ y ];
7812 for ( x = 0; x < cols; x++ ) {
7813 width = this.widths[ x ];
7814 panel = this.panels[ i ];
7815 dimensions = {
7816 width: ( width * 100 ) + '%',
7817 height: ( height * 100 ) + '%',
7818 top: ( top * 100 ) + '%'
7820 // If RTL, reverse:
7821 if ( OO.ui.Element.static.getDir( document ) === 'rtl' ) {
7822 dimensions.right = ( left * 100 ) + '%';
7823 } else {
7824 dimensions.left = ( left * 100 ) + '%';
7826 // HACK: Work around IE bug by setting visibility: hidden; if width or height is zero
7827 if ( width === 0 || height === 0 ) {
7828 dimensions.visibility = 'hidden';
7829 } else {
7830 dimensions.visibility = '';
7832 panel.$element.css( dimensions );
7833 i++;
7834 left += width;
7836 top += height;
7837 left = 0;
7840 this.emit( 'update' );
7844 * Get a panel at a given position.
7846 * The x and y position is affected by the current grid layout.
7848 * @param {number} x Horizontal position
7849 * @param {number} y Vertical position
7850 * @return {OO.ui.PanelLayout} The panel at the given position
7852 OO.ui.GridLayout.prototype.getPanel = function ( x, y ) {
7853 return this.panels[ ( x * this.widths.length ) + y ];
7857 * Layout with a content and menu area.
7859 * The menu area can be positioned at the top, after, bottom or before. The content area will fill
7860 * all remaining space.
7862 * @class
7863 * @extends OO.ui.Layout
7865 * @constructor
7866 * @param {Object} [config] Configuration options
7867 * @cfg {number|string} [menuSize='18em'] Size of menu in pixels or any CSS unit
7868 * @cfg {boolean} [showMenu=true] Show menu
7869 * @cfg {string} [position='before'] Position of menu, either `top`, `after`, `bottom` or `before`
7870 * @cfg {boolean} [collapse] Collapse the menu out of view
7872 OO.ui.MenuLayout = function OoUiMenuLayout( config ) {
7873 var positions = this.constructor.static.menuPositions;
7875 // Configuration initialization
7876 config = config || {};
7878 // Parent constructor
7879 OO.ui.MenuLayout.super.call( this, config );
7881 // Properties
7882 this.showMenu = config.showMenu !== false;
7883 this.menuSize = config.menuSize || '18em';
7884 this.menuPosition = positions[ config.menuPosition ] || positions.before;
7887 * Menu DOM node
7889 * @property {jQuery}
7891 this.$menu = $( '<div>' );
7893 * Content DOM node
7895 * @property {jQuery}
7897 this.$content = $( '<div>' );
7899 // Initialization
7900 this.toggleMenu( this.showMenu );
7901 this.updateSizes();
7902 this.$menu
7903 .addClass( 'oo-ui-menuLayout-menu' )
7904 .css( this.menuPosition.sizeProperty, this.menuSize );
7905 this.$content.addClass( 'oo-ui-menuLayout-content' );
7906 this.$element
7907 .addClass( 'oo-ui-menuLayout ' + this.menuPosition.className )
7908 .append( this.$content, this.$menu );
7911 /* Setup */
7913 OO.inheritClass( OO.ui.MenuLayout, OO.ui.Layout );
7915 /* Static Properties */
7917 OO.ui.MenuLayout.static.menuPositions = {
7918 top: {
7919 sizeProperty: 'height',
7920 className: 'oo-ui-menuLayout-top'
7922 after: {
7923 sizeProperty: 'width',
7924 className: 'oo-ui-menuLayout-after'
7926 bottom: {
7927 sizeProperty: 'height',
7928 className: 'oo-ui-menuLayout-bottom'
7930 before: {
7931 sizeProperty: 'width',
7932 className: 'oo-ui-menuLayout-before'
7936 /* Methods */
7939 * Toggle menu.
7941 * @param {boolean} showMenu Show menu, omit to toggle
7942 * @chainable
7944 OO.ui.MenuLayout.prototype.toggleMenu = function ( showMenu ) {
7945 showMenu = showMenu === undefined ? !this.showMenu : !!showMenu;
7947 if ( this.showMenu !== showMenu ) {
7948 this.showMenu = showMenu;
7949 this.updateSizes();
7952 return this;
7956 * Check if menu is visible
7958 * @return {boolean} Menu is visible
7960 OO.ui.MenuLayout.prototype.isMenuVisible = function () {
7961 return this.showMenu;
7965 * Set menu size.
7967 * @param {number|string} size Size of menu in pixels or any CSS unit
7968 * @chainable
7970 OO.ui.MenuLayout.prototype.setMenuSize = function ( size ) {
7971 this.menuSize = size;
7972 this.updateSizes();
7974 return this;
7978 * Update menu and content CSS based on current menu size and visibility
7980 * This method is called internally when size or position is changed.
7982 OO.ui.MenuLayout.prototype.updateSizes = function () {
7983 if ( this.showMenu ) {
7984 this.$menu
7985 .css( this.menuPosition.sizeProperty, this.menuSize )
7986 .css( 'overflow', '' );
7987 // Set offsets on all sides. CSS resets all but one with
7988 // 'important' rules so directionality flips are supported
7989 this.$content.css( {
7990 top: this.menuSize,
7991 right: this.menuSize,
7992 bottom: this.menuSize,
7993 left: this.menuSize
7994 } );
7995 } else {
7996 this.$menu
7997 .css( this.menuPosition.sizeProperty, 0 )
7998 .css( 'overflow', 'hidden' );
7999 this.$content.css( {
8000 top: 0,
8001 right: 0,
8002 bottom: 0,
8003 left: 0
8004 } );
8009 * Get menu size.
8011 * @return {number|string} Menu size
8013 OO.ui.MenuLayout.prototype.getMenuSize = function () {
8014 return this.menuSize;
8018 * Set menu position.
8020 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
8021 * @throws {Error} If position value is not supported
8022 * @chainable
8024 OO.ui.MenuLayout.prototype.setMenuPosition = function ( position ) {
8025 var positions = this.constructor.static.menuPositions;
8027 if ( !positions[ position ] ) {
8028 throw new Error( 'Cannot set position; unsupported position value: ' + position );
8031 this.$menu.css( this.menuPosition.sizeProperty, '' );
8032 this.$element.removeClass( this.menuPosition.className );
8034 this.menuPosition = positions[ position ];
8036 this.updateSizes();
8037 this.$element.addClass( this.menuPosition.className );
8039 return this;
8043 * Get menu position.
8045 * @return {string} Menu position
8047 OO.ui.MenuLayout.prototype.getMenuPosition = function () {
8048 return this.menuPosition;
8052 * Layout containing a series of pages.
8054 * @class
8055 * @extends OO.ui.MenuLayout
8057 * @constructor
8058 * @param {Object} [config] Configuration options
8059 * @cfg {boolean} [continuous=false] Show all pages, one after another
8060 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when changing to a page
8061 * @cfg {boolean} [outlined=false] Show an outline
8062 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
8064 OO.ui.BookletLayout = function OoUiBookletLayout( config ) {
8065 // Configuration initialization
8066 config = config || {};
8068 // Parent constructor
8069 OO.ui.BookletLayout.super.call( this, config );
8071 // Properties
8072 this.currentPageName = null;
8073 this.pages = {};
8074 this.ignoreFocus = false;
8075 this.stackLayout = new OO.ui.StackLayout( { continuous: !!config.continuous } );
8076 this.$content.append( this.stackLayout.$element );
8077 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
8078 this.outlineVisible = false;
8079 this.outlined = !!config.outlined;
8080 if ( this.outlined ) {
8081 this.editable = !!config.editable;
8082 this.outlineControlsWidget = null;
8083 this.outlineSelectWidget = new OO.ui.OutlineSelectWidget();
8084 this.outlinePanel = new OO.ui.PanelLayout( { scrollable: true } );
8085 this.$menu.append( this.outlinePanel.$element );
8086 this.outlineVisible = true;
8087 if ( this.editable ) {
8088 this.outlineControlsWidget = new OO.ui.OutlineControlsWidget(
8089 this.outlineSelectWidget
8093 this.toggleMenu( this.outlined );
8095 // Events
8096 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
8097 if ( this.outlined ) {
8098 this.outlineSelectWidget.connect( this, { select: 'onOutlineSelectWidgetSelect' } );
8100 if ( this.autoFocus ) {
8101 // Event 'focus' does not bubble, but 'focusin' does
8102 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
8105 // Initialization
8106 this.$element.addClass( 'oo-ui-bookletLayout' );
8107 this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' );
8108 if ( this.outlined ) {
8109 this.outlinePanel.$element
8110 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
8111 .append( this.outlineSelectWidget.$element );
8112 if ( this.editable ) {
8113 this.outlinePanel.$element
8114 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
8115 .append( this.outlineControlsWidget.$element );
8120 /* Setup */
8122 OO.inheritClass( OO.ui.BookletLayout, OO.ui.MenuLayout );
8124 /* Events */
8127 * @event set
8128 * @param {OO.ui.PageLayout} page Current page
8132 * @event add
8133 * @param {OO.ui.PageLayout[]} page Added pages
8134 * @param {number} index Index pages were added at
8138 * @event remove
8139 * @param {OO.ui.PageLayout[]} pages Removed pages
8142 /* Methods */
8145 * Handle stack layout focus.
8147 * @param {jQuery.Event} e Focusin event
8149 OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) {
8150 var name, $target;
8152 // Find the page that an element was focused within
8153 $target = $( e.target ).closest( '.oo-ui-pageLayout' );
8154 for ( name in this.pages ) {
8155 // Check for page match, exclude current page to find only page changes
8156 if ( this.pages[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentPageName ) {
8157 this.setPage( name );
8158 break;
8164 * Handle stack layout set events.
8166 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
8168 OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) {
8169 var layout = this;
8170 if ( page ) {
8171 page.scrollElementIntoView( { complete: function () {
8172 if ( layout.autoFocus ) {
8173 layout.focus();
8175 } } );
8180 * Focus the first input in the current page.
8182 * If no page is selected, the first selectable page will be selected.
8183 * If the focus is already in an element on the current page, nothing will happen.
8185 OO.ui.BookletLayout.prototype.focus = function () {
8186 var $input, page = this.stackLayout.getCurrentItem();
8187 if ( !page && this.outlined ) {
8188 this.selectFirstSelectablePage();
8189 page = this.stackLayout.getCurrentItem();
8191 if ( !page ) {
8192 return;
8194 // Only change the focus if is not already in the current page
8195 if ( !page.$element.find( ':focus' ).length ) {
8196 $input = page.$element.find( ':input:first' );
8197 if ( $input.length ) {
8198 $input[ 0 ].focus();
8204 * Handle outline widget select events.
8206 * @param {OO.ui.OptionWidget|null} item Selected item
8208 OO.ui.BookletLayout.prototype.onOutlineSelectWidgetSelect = function ( item ) {
8209 if ( item ) {
8210 this.setPage( item.getData() );
8215 * Check if booklet has an outline.
8217 * @return {boolean}
8219 OO.ui.BookletLayout.prototype.isOutlined = function () {
8220 return this.outlined;
8224 * Check if booklet has editing controls.
8226 * @return {boolean}
8228 OO.ui.BookletLayout.prototype.isEditable = function () {
8229 return this.editable;
8233 * Check if booklet has a visible outline.
8235 * @return {boolean}
8237 OO.ui.BookletLayout.prototype.isOutlineVisible = function () {
8238 return this.outlined && this.outlineVisible;
8242 * Hide or show the outline.
8244 * @param {boolean} [show] Show outline, omit to invert current state
8245 * @chainable
8247 OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) {
8248 if ( this.outlined ) {
8249 show = show === undefined ? !this.outlineVisible : !!show;
8250 this.outlineVisible = show;
8251 this.toggleMenu( show );
8254 return this;
8258 * Get the outline widget.
8260 * @param {OO.ui.PageLayout} page Page to be selected
8261 * @return {OO.ui.PageLayout|null} Closest page to another
8263 OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) {
8264 var next, prev, level,
8265 pages = this.stackLayout.getItems(),
8266 index = $.inArray( page, pages );
8268 if ( index !== -1 ) {
8269 next = pages[ index + 1 ];
8270 prev = pages[ index - 1 ];
8271 // Prefer adjacent pages at the same level
8272 if ( this.outlined ) {
8273 level = this.outlineSelectWidget.getItemFromData( page.getName() ).getLevel();
8274 if (
8275 prev &&
8276 level === this.outlineSelectWidget.getItemFromData( prev.getName() ).getLevel()
8278 return prev;
8280 if (
8281 next &&
8282 level === this.outlineSelectWidget.getItemFromData( next.getName() ).getLevel()
8284 return next;
8288 return prev || next || null;
8292 * Get the outline widget.
8294 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if booklet has no outline
8296 OO.ui.BookletLayout.prototype.getOutline = function () {
8297 return this.outlineSelectWidget;
8301 * Get the outline controls widget. If the outline is not editable, null is returned.
8303 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
8305 OO.ui.BookletLayout.prototype.getOutlineControls = function () {
8306 return this.outlineControlsWidget;
8310 * Get a page by name.
8312 * @param {string} name Symbolic name of page
8313 * @return {OO.ui.PageLayout|undefined} Page, if found
8315 OO.ui.BookletLayout.prototype.getPage = function ( name ) {
8316 return this.pages[ name ];
8320 * Get the current page
8322 * @return {OO.ui.PageLayout|undefined} Current page, if found
8324 OO.ui.BookletLayout.prototype.getCurrentPage = function () {
8325 var name = this.getCurrentPageName();
8326 return name ? this.getPage( name ) : undefined;
8330 * Get the current page name.
8332 * @return {string|null} Current page name
8334 OO.ui.BookletLayout.prototype.getCurrentPageName = function () {
8335 return this.currentPageName;
8339 * Add a page to the layout.
8341 * When pages are added with the same names as existing pages, the existing pages will be
8342 * automatically removed before the new pages are added.
8344 * @param {OO.ui.PageLayout[]} pages Pages to add
8345 * @param {number} index Index to insert pages after
8346 * @fires add
8347 * @chainable
8349 OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
8350 var i, len, name, page, item, currentIndex,
8351 stackLayoutPages = this.stackLayout.getItems(),
8352 remove = [],
8353 items = [];
8355 // Remove pages with same names
8356 for ( i = 0, len = pages.length; i < len; i++ ) {
8357 page = pages[ i ];
8358 name = page.getName();
8360 if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
8361 // Correct the insertion index
8362 currentIndex = $.inArray( this.pages[ name ], stackLayoutPages );
8363 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
8364 index--;
8366 remove.push( this.pages[ name ] );
8369 if ( remove.length ) {
8370 this.removePages( remove );
8373 // Add new pages
8374 for ( i = 0, len = pages.length; i < len; i++ ) {
8375 page = pages[ i ];
8376 name = page.getName();
8377 this.pages[ page.getName() ] = page;
8378 if ( this.outlined ) {
8379 item = new OO.ui.OutlineOptionWidget( { data: name } );
8380 page.setOutlineItem( item );
8381 items.push( item );
8385 if ( this.outlined && items.length ) {
8386 this.outlineSelectWidget.addItems( items, index );
8387 this.selectFirstSelectablePage();
8389 this.stackLayout.addItems( pages, index );
8390 this.emit( 'add', pages, index );
8392 return this;
8396 * Remove a page from the layout.
8398 * @fires remove
8399 * @chainable
8401 OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
8402 var i, len, name, page,
8403 items = [];
8405 for ( i = 0, len = pages.length; i < len; i++ ) {
8406 page = pages[ i ];
8407 name = page.getName();
8408 delete this.pages[ name ];
8409 if ( this.outlined ) {
8410 items.push( this.outlineSelectWidget.getItemFromData( name ) );
8411 page.setOutlineItem( null );
8414 if ( this.outlined && items.length ) {
8415 this.outlineSelectWidget.removeItems( items );
8416 this.selectFirstSelectablePage();
8418 this.stackLayout.removeItems( pages );
8419 this.emit( 'remove', pages );
8421 return this;
8425 * Clear all pages from the layout.
8427 * @fires remove
8428 * @chainable
8430 OO.ui.BookletLayout.prototype.clearPages = function () {
8431 var i, len,
8432 pages = this.stackLayout.getItems();
8434 this.pages = {};
8435 this.currentPageName = null;
8436 if ( this.outlined ) {
8437 this.outlineSelectWidget.clearItems();
8438 for ( i = 0, len = pages.length; i < len; i++ ) {
8439 pages[ i ].setOutlineItem( null );
8442 this.stackLayout.clearItems();
8444 this.emit( 'remove', pages );
8446 return this;
8450 * Set the current page by name.
8452 * @fires set
8453 * @param {string} name Symbolic name of page
8455 OO.ui.BookletLayout.prototype.setPage = function ( name ) {
8456 var selectedItem,
8457 $focused,
8458 page = this.pages[ name ];
8460 if ( name !== this.currentPageName ) {
8461 if ( this.outlined ) {
8462 selectedItem = this.outlineSelectWidget.getSelectedItem();
8463 if ( selectedItem && selectedItem.getData() !== name ) {
8464 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getItemFromData( name ) );
8467 if ( page ) {
8468 if ( this.currentPageName && this.pages[ this.currentPageName ] ) {
8469 this.pages[ this.currentPageName ].setActive( false );
8470 // Blur anything focused if the next page doesn't have anything focusable - this
8471 // is not needed if the next page has something focusable because once it is focused
8472 // this blur happens automatically
8473 if ( this.autoFocus && !page.$element.find( ':input' ).length ) {
8474 $focused = this.pages[ this.currentPageName ].$element.find( ':focus' );
8475 if ( $focused.length ) {
8476 $focused[ 0 ].blur();
8480 this.currentPageName = name;
8481 this.stackLayout.setItem( page );
8482 page.setActive( true );
8483 this.emit( 'set', page );
8489 * Select the first selectable page.
8491 * @chainable
8493 OO.ui.BookletLayout.prototype.selectFirstSelectablePage = function () {
8494 if ( !this.outlineSelectWidget.getSelectedItem() ) {
8495 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getFirstSelectableItem() );
8498 return this;
8502 * Layout that expands to cover the entire area of its parent, with optional scrolling and padding.
8504 * @class
8505 * @extends OO.ui.Layout
8507 * @constructor
8508 * @param {Object} [config] Configuration options
8509 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
8510 * @cfg {boolean} [padded=false] Pad the content from the edges
8511 * @cfg {boolean} [expanded=true] Expand size to fill the entire parent element
8513 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
8514 // Configuration initialization
8515 config = $.extend( {
8516 scrollable: false,
8517 padded: false,
8518 expanded: true
8519 }, config );
8521 // Parent constructor
8522 OO.ui.PanelLayout.super.call( this, config );
8524 // Initialization
8525 this.$element.addClass( 'oo-ui-panelLayout' );
8526 if ( config.scrollable ) {
8527 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
8529 if ( config.padded ) {
8530 this.$element.addClass( 'oo-ui-panelLayout-padded' );
8532 if ( config.expanded ) {
8533 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
8537 /* Setup */
8539 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
8542 * Page within an booklet layout.
8544 * @class
8545 * @extends OO.ui.PanelLayout
8547 * @constructor
8548 * @param {string} name Unique symbolic name of page
8549 * @param {Object} [config] Configuration options
8551 OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
8552 // Allow passing positional parameters inside the config object
8553 if ( OO.isPlainObject( name ) && config === undefined ) {
8554 config = name;
8555 name = config.name;
8558 // Configuration initialization
8559 config = $.extend( { scrollable: true }, config );
8561 // Parent constructor
8562 OO.ui.PageLayout.super.call( this, config );
8564 // Properties
8565 this.name = name;
8566 this.outlineItem = null;
8567 this.active = false;
8569 // Initialization
8570 this.$element.addClass( 'oo-ui-pageLayout' );
8573 /* Setup */
8575 OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
8577 /* Events */
8580 * @event active
8581 * @param {boolean} active Page is active
8584 /* Methods */
8587 * Get page name.
8589 * @return {string} Symbolic name of page
8591 OO.ui.PageLayout.prototype.getName = function () {
8592 return this.name;
8596 * Check if page is active.
8598 * @return {boolean} Page is active
8600 OO.ui.PageLayout.prototype.isActive = function () {
8601 return this.active;
8605 * Get outline item.
8607 * @return {OO.ui.OutlineOptionWidget|null} Outline item widget
8609 OO.ui.PageLayout.prototype.getOutlineItem = function () {
8610 return this.outlineItem;
8614 * Set outline item.
8616 * @localdoc Subclasses should override #setupOutlineItem instead of this method to adjust the
8617 * outline item as desired; this method is called for setting (with an object) and unsetting
8618 * (with null) and overriding methods would have to check the value of `outlineItem` to avoid
8619 * operating on null instead of an OO.ui.OutlineOptionWidget object.
8621 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline item widget, null to clear
8622 * @chainable
8624 OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
8625 this.outlineItem = outlineItem || null;
8626 if ( outlineItem ) {
8627 this.setupOutlineItem();
8629 return this;
8633 * Setup outline item.
8635 * @localdoc Subclasses should override this method to adjust the outline item as desired.
8637 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline item widget to setup
8638 * @chainable
8640 OO.ui.PageLayout.prototype.setupOutlineItem = function () {
8641 return this;
8645 * Set page active state.
8647 * @param {boolean} Page is active
8648 * @fires active
8650 OO.ui.PageLayout.prototype.setActive = function ( active ) {
8651 active = !!active;
8653 if ( active !== this.active ) {
8654 this.active = active;
8655 this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
8656 this.emit( 'active', this.active );
8661 * Layout containing a series of mutually exclusive pages.
8663 * @class
8664 * @extends OO.ui.PanelLayout
8665 * @mixins OO.ui.GroupElement
8667 * @constructor
8668 * @param {Object} [config] Configuration options
8669 * @cfg {boolean} [continuous=false] Show all pages, one after another
8670 * @cfg {OO.ui.Layout[]} [items] Layouts to add
8672 OO.ui.StackLayout = function OoUiStackLayout( config ) {
8673 // Configuration initialization
8674 config = $.extend( { scrollable: true }, config );
8676 // Parent constructor
8677 OO.ui.StackLayout.super.call( this, config );
8679 // Mixin constructors
8680 OO.ui.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
8682 // Properties
8683 this.currentItem = null;
8684 this.continuous = !!config.continuous;
8686 // Initialization
8687 this.$element.addClass( 'oo-ui-stackLayout' );
8688 if ( this.continuous ) {
8689 this.$element.addClass( 'oo-ui-stackLayout-continuous' );
8691 if ( Array.isArray( config.items ) ) {
8692 this.addItems( config.items );
8696 /* Setup */
8698 OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
8699 OO.mixinClass( OO.ui.StackLayout, OO.ui.GroupElement );
8701 /* Events */
8704 * @event set
8705 * @param {OO.ui.Layout|null} item Current item or null if there is no longer a layout shown
8708 /* Methods */
8711 * Get the current item.
8713 * @return {OO.ui.Layout|null}
8715 OO.ui.StackLayout.prototype.getCurrentItem = function () {
8716 return this.currentItem;
8720 * Unset the current item.
8722 * @private
8723 * @param {OO.ui.StackLayout} layout
8724 * @fires set
8726 OO.ui.StackLayout.prototype.unsetCurrentItem = function () {
8727 var prevItem = this.currentItem;
8728 if ( prevItem === null ) {
8729 return;
8732 this.currentItem = null;
8733 this.emit( 'set', null );
8737 * Add items.
8739 * Adding an existing item (by value) will move it.
8741 * @param {OO.ui.Layout[]} items Items to add
8742 * @param {number} [index] Index to insert items after
8743 * @chainable
8745 OO.ui.StackLayout.prototype.addItems = function ( items, index ) {
8746 // Update the visibility
8747 this.updateHiddenState( items, this.currentItem );
8749 // Mixin method
8750 OO.ui.GroupElement.prototype.addItems.call( this, items, index );
8752 if ( !this.currentItem && items.length ) {
8753 this.setItem( items[ 0 ] );
8756 return this;
8760 * Remove items.
8762 * Items will be detached, not removed, so they can be used later.
8764 * @param {OO.ui.Layout[]} items Items to remove
8765 * @chainable
8766 * @fires set
8768 OO.ui.StackLayout.prototype.removeItems = function ( items ) {
8769 // Mixin method
8770 OO.ui.GroupElement.prototype.removeItems.call( this, items );
8772 if ( $.inArray( this.currentItem, items ) !== -1 ) {
8773 if ( this.items.length ) {
8774 this.setItem( this.items[ 0 ] );
8775 } else {
8776 this.unsetCurrentItem();
8780 return this;
8784 * Clear all items.
8786 * Items will be detached, not removed, so they can be used later.
8788 * @chainable
8789 * @fires set
8791 OO.ui.StackLayout.prototype.clearItems = function () {
8792 this.unsetCurrentItem();
8793 OO.ui.GroupElement.prototype.clearItems.call( this );
8795 return this;
8799 * Show item.
8801 * Any currently shown item will be hidden.
8803 * FIXME: If the passed item to show has not been added in the items list, then
8804 * this method drops it and unsets the current item.
8806 * @param {OO.ui.Layout} item Item to show
8807 * @chainable
8808 * @fires set
8810 OO.ui.StackLayout.prototype.setItem = function ( item ) {
8811 if ( item !== this.currentItem ) {
8812 this.updateHiddenState( this.items, item );
8814 if ( $.inArray( item, this.items ) !== -1 ) {
8815 this.currentItem = item;
8816 this.emit( 'set', item );
8817 } else {
8818 this.unsetCurrentItem();
8822 return this;
8826 * Update the visibility of all items in case of non-continuous view.
8828 * Ensure all items are hidden except for the selected one.
8829 * This method does nothing when the stack is continuous.
8831 * @param {OO.ui.Layout[]} items Item list iterate over
8832 * @param {OO.ui.Layout} [selectedItem] Selected item to show
8834 OO.ui.StackLayout.prototype.updateHiddenState = function ( items, selectedItem ) {
8835 var i, len;
8837 if ( !this.continuous ) {
8838 for ( i = 0, len = items.length; i < len; i++ ) {
8839 if ( !selectedItem || selectedItem !== items[ i ] ) {
8840 items[ i ].$element.addClass( 'oo-ui-element-hidden' );
8843 if ( selectedItem ) {
8844 selectedItem.$element.removeClass( 'oo-ui-element-hidden' );
8850 * Horizontal bar layout of tools as icon buttons.
8852 * @class
8853 * @extends OO.ui.ToolGroup
8855 * @constructor
8856 * @param {OO.ui.Toolbar} toolbar
8857 * @param {Object} [config] Configuration options
8859 OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) {
8860 // Allow passing positional parameters inside the config object
8861 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
8862 config = toolbar;
8863 toolbar = config.toolbar;
8866 // Parent constructor
8867 OO.ui.BarToolGroup.super.call( this, toolbar, config );
8869 // Initialization
8870 this.$element.addClass( 'oo-ui-barToolGroup' );
8873 /* Setup */
8875 OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup );
8877 /* Static Properties */
8879 OO.ui.BarToolGroup.static.titleTooltips = true;
8881 OO.ui.BarToolGroup.static.accelTooltips = true;
8883 OO.ui.BarToolGroup.static.name = 'bar';
8886 * Popup list of tools with an icon and optional label.
8888 * @abstract
8889 * @class
8890 * @extends OO.ui.ToolGroup
8891 * @mixins OO.ui.IconElement
8892 * @mixins OO.ui.IndicatorElement
8893 * @mixins OO.ui.LabelElement
8894 * @mixins OO.ui.TitledElement
8895 * @mixins OO.ui.ClippableElement
8897 * @constructor
8898 * @param {OO.ui.Toolbar} toolbar
8899 * @param {Object} [config] Configuration options
8900 * @cfg {string} [header] Text to display at the top of the pop-up
8902 OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) {
8903 // Allow passing positional parameters inside the config object
8904 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
8905 config = toolbar;
8906 toolbar = config.toolbar;
8909 // Configuration initialization
8910 config = config || {};
8912 // Parent constructor
8913 OO.ui.PopupToolGroup.super.call( this, toolbar, config );
8915 // Mixin constructors
8916 OO.ui.IconElement.call( this, config );
8917 OO.ui.IndicatorElement.call( this, config );
8918 OO.ui.LabelElement.call( this, config );
8919 OO.ui.TitledElement.call( this, config );
8920 OO.ui.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
8922 // Properties
8923 this.active = false;
8924 this.dragging = false;
8925 this.onBlurHandler = this.onBlur.bind( this );
8926 this.$handle = $( '<span>' );
8928 // Events
8929 this.$handle.on( {
8930 'mousedown touchstart': this.onHandlePointerDown.bind( this ),
8931 'mouseup touchend': this.onHandlePointerUp.bind( this )
8932 } );
8934 // Initialization
8935 this.$handle
8936 .addClass( 'oo-ui-popupToolGroup-handle' )
8937 .append( this.$icon, this.$label, this.$indicator );
8938 // If the pop-up should have a header, add it to the top of the toolGroup.
8939 // Note: If this feature is useful for other widgets, we could abstract it into an
8940 // OO.ui.HeaderedElement mixin constructor.
8941 if ( config.header !== undefined ) {
8942 this.$group
8943 .prepend( $( '<span>' )
8944 .addClass( 'oo-ui-popupToolGroup-header' )
8945 .text( config.header )
8948 this.$element
8949 .addClass( 'oo-ui-popupToolGroup' )
8950 .prepend( this.$handle );
8953 /* Setup */
8955 OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup );
8956 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.IconElement );
8957 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.IndicatorElement );
8958 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.LabelElement );
8959 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.TitledElement );
8960 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.ClippableElement );
8962 /* Static Properties */
8964 /* Methods */
8967 * @inheritdoc
8969 OO.ui.PopupToolGroup.prototype.setDisabled = function () {
8970 // Parent method
8971 OO.ui.PopupToolGroup.super.prototype.setDisabled.apply( this, arguments );
8973 if ( this.isDisabled() && this.isElementAttached() ) {
8974 this.setActive( false );
8979 * Handle focus being lost.
8981 * The event is actually generated from a mouseup, so it is not a normal blur event object.
8983 * @param {jQuery.Event} e Mouse up event
8985 OO.ui.PopupToolGroup.prototype.onBlur = function ( e ) {
8986 // Only deactivate when clicking outside the dropdown element
8987 if ( $( e.target ).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element[ 0 ] ) {
8988 this.setActive( false );
8993 * @inheritdoc
8995 OO.ui.PopupToolGroup.prototype.onPointerUp = function ( e ) {
8996 // e.which is 0 for touch events, 1 for left mouse button
8997 // Only close toolgroup when a tool was actually selected
8998 // FIXME: this duplicates logic from the parent class
8999 if ( !this.isDisabled() && e.which <= 1 && this.pressed && this.pressed === this.getTargetTool( e ) ) {
9000 this.setActive( false );
9002 return OO.ui.PopupToolGroup.super.prototype.onPointerUp.call( this, e );
9006 * Handle mouse up events.
9008 * @param {jQuery.Event} e Mouse up event
9010 OO.ui.PopupToolGroup.prototype.onHandlePointerUp = function () {
9011 return false;
9015 * Handle mouse down events.
9017 * @param {jQuery.Event} e Mouse down event
9019 OO.ui.PopupToolGroup.prototype.onHandlePointerDown = function ( e ) {
9020 // e.which is 0 for touch events, 1 for left mouse button
9021 if ( !this.isDisabled() && e.which <= 1 ) {
9022 this.setActive( !this.active );
9024 return false;
9028 * Switch into active mode.
9030 * When active, mouseup events anywhere in the document will trigger deactivation.
9032 OO.ui.PopupToolGroup.prototype.setActive = function ( value ) {
9033 value = !!value;
9034 if ( this.active !== value ) {
9035 this.active = value;
9036 if ( value ) {
9037 this.getElementDocument().addEventListener( 'mouseup', this.onBlurHandler, true );
9039 // Try anchoring the popup to the left first
9040 this.$element.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
9041 this.toggleClipping( true );
9042 if ( this.isClippedHorizontally() ) {
9043 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
9044 this.toggleClipping( false );
9045 this.$element
9046 .removeClass( 'oo-ui-popupToolGroup-left' )
9047 .addClass( 'oo-ui-popupToolGroup-right' );
9048 this.toggleClipping( true );
9050 } else {
9051 this.getElementDocument().removeEventListener( 'mouseup', this.onBlurHandler, true );
9052 this.$element.removeClass(
9053 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
9055 this.toggleClipping( false );
9061 * Drop down list layout of tools as labeled icon buttons.
9063 * This layout allows some tools to be collapsible, controlled by a "More" / "Fewer" option at the
9064 * bottom of the main list. These are not automatically positioned at the bottom of the list; you
9065 * may want to use the 'promote' and 'demote' configuration options to achieve this.
9067 * @class
9068 * @extends OO.ui.PopupToolGroup
9070 * @constructor
9071 * @param {OO.ui.Toolbar} toolbar
9072 * @param {Object} [config] Configuration options
9073 * @cfg {Array} [allowCollapse] List of tools that can be collapsed. Remaining tools will be always
9074 * shown.
9075 * @cfg {Array} [forceExpand] List of tools that *may not* be collapsed. All remaining tools will be
9076 * allowed to be collapsed.
9077 * @cfg {boolean} [expanded=false] Whether the collapsible tools are expanded by default
9079 OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) {
9080 // Allow passing positional parameters inside the config object
9081 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
9082 config = toolbar;
9083 toolbar = config.toolbar;
9086 // Configuration initialization
9087 config = config || {};
9089 // Properties (must be set before parent constructor, which calls #populate)
9090 this.allowCollapse = config.allowCollapse;
9091 this.forceExpand = config.forceExpand;
9092 this.expanded = config.expanded !== undefined ? config.expanded : false;
9093 this.collapsibleTools = [];
9095 // Parent constructor
9096 OO.ui.ListToolGroup.super.call( this, toolbar, config );
9098 // Initialization
9099 this.$element.addClass( 'oo-ui-listToolGroup' );
9102 /* Setup */
9104 OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup );
9106 /* Static Properties */
9108 OO.ui.ListToolGroup.static.accelTooltips = true;
9110 OO.ui.ListToolGroup.static.name = 'list';
9112 /* Methods */
9115 * @inheritdoc
9117 OO.ui.ListToolGroup.prototype.populate = function () {
9118 var i, len, allowCollapse = [];
9120 OO.ui.ListToolGroup.super.prototype.populate.call( this );
9122 // Update the list of collapsible tools
9123 if ( this.allowCollapse !== undefined ) {
9124 allowCollapse = this.allowCollapse;
9125 } else if ( this.forceExpand !== undefined ) {
9126 allowCollapse = OO.simpleArrayDifference( Object.keys( this.tools ), this.forceExpand );
9129 this.collapsibleTools = [];
9130 for ( i = 0, len = allowCollapse.length; i < len; i++ ) {
9131 if ( this.tools[ allowCollapse[ i ] ] !== undefined ) {
9132 this.collapsibleTools.push( this.tools[ allowCollapse[ i ] ] );
9136 // Keep at the end, even when tools are added
9137 this.$group.append( this.getExpandCollapseTool().$element );
9139 this.getExpandCollapseTool().toggle( this.collapsibleTools.length !== 0 );
9140 this.updateCollapsibleState();
9143 OO.ui.ListToolGroup.prototype.getExpandCollapseTool = function () {
9144 if ( this.expandCollapseTool === undefined ) {
9145 var ExpandCollapseTool = function () {
9146 ExpandCollapseTool.super.apply( this, arguments );
9149 OO.inheritClass( ExpandCollapseTool, OO.ui.Tool );
9151 ExpandCollapseTool.prototype.onSelect = function () {
9152 this.toolGroup.expanded = !this.toolGroup.expanded;
9153 this.toolGroup.updateCollapsibleState();
9154 this.setActive( false );
9156 ExpandCollapseTool.prototype.onUpdateState = function () {
9157 // Do nothing. Tool interface requires an implementation of this function.
9160 ExpandCollapseTool.static.name = 'more-fewer';
9162 this.expandCollapseTool = new ExpandCollapseTool( this );
9164 return this.expandCollapseTool;
9168 * @inheritdoc
9170 OO.ui.ListToolGroup.prototype.onPointerUp = function ( e ) {
9171 var ret = OO.ui.ListToolGroup.super.prototype.onPointerUp.call( this, e );
9173 // Do not close the popup when the user wants to show more/fewer tools
9174 if ( $( e.target ).closest( '.oo-ui-tool-name-more-fewer' ).length ) {
9175 // Prevent the popup list from being hidden
9176 this.setActive( true );
9179 return ret;
9182 OO.ui.ListToolGroup.prototype.updateCollapsibleState = function () {
9183 var i, len;
9185 this.getExpandCollapseTool()
9186 .setIcon( this.expanded ? 'collapse' : 'expand' )
9187 .setTitle( OO.ui.msg( this.expanded ? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
9189 for ( i = 0, len = this.collapsibleTools.length; i < len; i++ ) {
9190 this.collapsibleTools[ i ].toggle( this.expanded );
9195 * Drop down menu layout of tools as selectable menu items.
9197 * @class
9198 * @extends OO.ui.PopupToolGroup
9200 * @constructor
9201 * @param {OO.ui.Toolbar} toolbar
9202 * @param {Object} [config] Configuration options
9204 OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) {
9205 // Allow passing positional parameters inside the config object
9206 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
9207 config = toolbar;
9208 toolbar = config.toolbar;
9211 // Configuration initialization
9212 config = config || {};
9214 // Parent constructor
9215 OO.ui.MenuToolGroup.super.call( this, toolbar, config );
9217 // Events
9218 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
9220 // Initialization
9221 this.$element.addClass( 'oo-ui-menuToolGroup' );
9224 /* Setup */
9226 OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup );
9228 /* Static Properties */
9230 OO.ui.MenuToolGroup.static.accelTooltips = true;
9232 OO.ui.MenuToolGroup.static.name = 'menu';
9234 /* Methods */
9237 * Handle the toolbar state being updated.
9239 * When the state changes, the title of each active item in the menu will be joined together and
9240 * used as a label for the group. The label will be empty if none of the items are active.
9242 OO.ui.MenuToolGroup.prototype.onUpdateState = function () {
9243 var name,
9244 labelTexts = [];
9246 for ( name in this.tools ) {
9247 if ( this.tools[ name ].isActive() ) {
9248 labelTexts.push( this.tools[ name ].getTitle() );
9252 this.setLabel( labelTexts.join( ', ' ) || ' ' );
9256 * Tool that shows a popup when selected.
9258 * @abstract
9259 * @class
9260 * @extends OO.ui.Tool
9261 * @mixins OO.ui.PopupElement
9263 * @constructor
9264 * @param {OO.ui.Toolbar} toolbar
9265 * @param {Object} [config] Configuration options
9267 OO.ui.PopupTool = function OoUiPopupTool( toolbar, config ) {
9268 // Allow passing positional parameters inside the config object
9269 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
9270 config = toolbar;
9271 toolbar = config.toolbar;
9274 // Parent constructor
9275 OO.ui.PopupTool.super.call( this, toolbar, config );
9277 // Mixin constructors
9278 OO.ui.PopupElement.call( this, config );
9280 // Initialization
9281 this.$element
9282 .addClass( 'oo-ui-popupTool' )
9283 .append( this.popup.$element );
9286 /* Setup */
9288 OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool );
9289 OO.mixinClass( OO.ui.PopupTool, OO.ui.PopupElement );
9291 /* Methods */
9294 * Handle the tool being selected.
9296 * @inheritdoc
9298 OO.ui.PopupTool.prototype.onSelect = function () {
9299 if ( !this.isDisabled() ) {
9300 this.popup.toggle();
9302 this.setActive( false );
9303 return false;
9307 * Handle the toolbar state being updated.
9309 * @inheritdoc
9311 OO.ui.PopupTool.prototype.onUpdateState = function () {
9312 this.setActive( false );
9316 * Mixin for OO.ui.Widget subclasses to provide OO.ui.GroupElement.
9318 * Use together with OO.ui.ItemWidget to make disabled state inheritable.
9320 * @abstract
9321 * @class
9322 * @extends OO.ui.GroupElement
9324 * @constructor
9325 * @param {Object} [config] Configuration options
9327 OO.ui.GroupWidget = function OoUiGroupWidget( config ) {
9328 // Parent constructor
9329 OO.ui.GroupWidget.super.call( this, config );
9332 /* Setup */
9334 OO.inheritClass( OO.ui.GroupWidget, OO.ui.GroupElement );
9336 /* Methods */
9339 * Set the disabled state of the widget.
9341 * This will also update the disabled state of child widgets.
9343 * @param {boolean} disabled Disable widget
9344 * @chainable
9346 OO.ui.GroupWidget.prototype.setDisabled = function ( disabled ) {
9347 var i, len;
9349 // Parent method
9350 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
9351 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
9353 // During construction, #setDisabled is called before the OO.ui.GroupElement constructor
9354 if ( this.items ) {
9355 for ( i = 0, len = this.items.length; i < len; i++ ) {
9356 this.items[ i ].updateDisabled();
9360 return this;
9364 * Mixin for widgets used as items in widgets that inherit OO.ui.GroupWidget.
9366 * Item widgets have a reference to a OO.ui.GroupWidget while they are attached to the group. This
9367 * allows bidirectional communication.
9369 * Use together with OO.ui.GroupWidget to make disabled state inheritable.
9371 * @abstract
9372 * @class
9374 * @constructor
9376 OO.ui.ItemWidget = function OoUiItemWidget() {
9380 /* Methods */
9383 * Check if widget is disabled.
9385 * Checks parent if present, making disabled state inheritable.
9387 * @return {boolean} Widget is disabled
9389 OO.ui.ItemWidget.prototype.isDisabled = function () {
9390 return this.disabled ||
9391 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
9395 * Set group element is in.
9397 * @param {OO.ui.GroupElement|null} group Group element, null if none
9398 * @chainable
9400 OO.ui.ItemWidget.prototype.setElementGroup = function ( group ) {
9401 // Parent method
9402 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
9403 OO.ui.Element.prototype.setElementGroup.call( this, group );
9405 // Initialize item disabled states
9406 this.updateDisabled();
9408 return this;
9412 * Mixin that adds a menu showing suggested values for a text input.
9414 * Subclasses must handle `select` and `choose` events on #lookupMenu to make use of selections.
9416 * Subclasses that set the value of #lookupInput from their `choose` or `select` handler should
9417 * be aware that this will cause new suggestions to be looked up for the new value. If this is
9418 * not desired, disable lookups with #setLookupsDisabled, then set the value, then re-enable lookups.
9420 * @class
9421 * @abstract
9422 * @deprecated Use OO.ui.LookupElement instead.
9424 * @constructor
9425 * @param {OO.ui.TextInputWidget} input Input widget
9426 * @param {Object} [config] Configuration options
9427 * @cfg {jQuery} [$overlay] Overlay for dropdown; defaults to relative positioning
9428 * @cfg {jQuery} [$container=input.$element] Element to render menu under
9430 OO.ui.LookupInputWidget = function OoUiLookupInputWidget( input, config ) {
9431 // Allow passing positional parameters inside the config object
9432 if ( OO.isPlainObject( input ) && config === undefined ) {
9433 config = input;
9434 input = config.input;
9437 // Configuration initialization
9438 config = config || {};
9440 // Properties
9441 this.lookupInput = input;
9442 this.$overlay = config.$overlay || this.$element;
9443 this.lookupMenu = new OO.ui.TextInputMenuSelectWidget( this, {
9444 input: this.lookupInput,
9445 $container: config.$container
9446 } );
9447 this.lookupCache = {};
9448 this.lookupQuery = null;
9449 this.lookupRequest = null;
9450 this.lookupsDisabled = false;
9451 this.lookupInputFocused = false;
9453 // Events
9454 this.lookupInput.$input.on( {
9455 focus: this.onLookupInputFocus.bind( this ),
9456 blur: this.onLookupInputBlur.bind( this ),
9457 mousedown: this.onLookupInputMouseDown.bind( this )
9458 } );
9459 this.lookupInput.connect( this, { change: 'onLookupInputChange' } );
9460 this.lookupMenu.connect( this, { toggle: 'onLookupMenuToggle' } );
9462 // Initialization
9463 this.$element.addClass( 'oo-ui-lookupWidget' );
9464 this.lookupMenu.$element.addClass( 'oo-ui-lookupWidget-menu' );
9465 this.$overlay.append( this.lookupMenu.$element );
9468 /* Methods */
9471 * Handle input focus event.
9473 * @param {jQuery.Event} e Input focus event
9475 OO.ui.LookupInputWidget.prototype.onLookupInputFocus = function () {
9476 this.lookupInputFocused = true;
9477 this.populateLookupMenu();
9481 * Handle input blur event.
9483 * @param {jQuery.Event} e Input blur event
9485 OO.ui.LookupInputWidget.prototype.onLookupInputBlur = function () {
9486 this.closeLookupMenu();
9487 this.lookupInputFocused = false;
9491 * Handle input mouse down event.
9493 * @param {jQuery.Event} e Input mouse down event
9495 OO.ui.LookupInputWidget.prototype.onLookupInputMouseDown = function () {
9496 // Only open the menu if the input was already focused.
9497 // This way we allow the user to open the menu again after closing it with Esc
9498 // by clicking in the input. Opening (and populating) the menu when initially
9499 // clicking into the input is handled by the focus handler.
9500 if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) {
9501 this.populateLookupMenu();
9506 * Handle input change event.
9508 * @param {string} value New input value
9510 OO.ui.LookupInputWidget.prototype.onLookupInputChange = function () {
9511 if ( this.lookupInputFocused ) {
9512 this.populateLookupMenu();
9517 * Handle the lookup menu being shown/hidden.
9518 * @param {boolean} visible Whether the lookup menu is now visible.
9520 OO.ui.LookupInputWidget.prototype.onLookupMenuToggle = function ( visible ) {
9521 if ( !visible ) {
9522 // When the menu is hidden, abort any active request and clear the menu.
9523 // This has to be done here in addition to closeLookupMenu(), because
9524 // MenuSelectWidget will close itself when the user presses Esc.
9525 this.abortLookupRequest();
9526 this.lookupMenu.clearItems();
9531 * Get lookup menu.
9533 * @return {OO.ui.TextInputMenuSelectWidget}
9535 OO.ui.LookupInputWidget.prototype.getLookupMenu = function () {
9536 return this.lookupMenu;
9540 * Disable or re-enable lookups.
9542 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
9544 * @param {boolean} disabled Disable lookups
9546 OO.ui.LookupInputWidget.prototype.setLookupsDisabled = function ( disabled ) {
9547 this.lookupsDisabled = !!disabled;
9551 * Open the menu. If there are no entries in the menu, this does nothing.
9553 * @chainable
9555 OO.ui.LookupInputWidget.prototype.openLookupMenu = function () {
9556 if ( !this.lookupMenu.isEmpty() ) {
9557 this.lookupMenu.toggle( true );
9559 return this;
9563 * Close the menu, empty it, and abort any pending request.
9565 * @chainable
9567 OO.ui.LookupInputWidget.prototype.closeLookupMenu = function () {
9568 this.lookupMenu.toggle( false );
9569 this.abortLookupRequest();
9570 this.lookupMenu.clearItems();
9571 return this;
9575 * Request menu items based on the input's current value, and when they arrive,
9576 * populate the menu with these items and show the menu.
9578 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
9580 * @chainable
9582 OO.ui.LookupInputWidget.prototype.populateLookupMenu = function () {
9583 var widget = this,
9584 value = this.lookupInput.getValue();
9586 if ( this.lookupsDisabled ) {
9587 return;
9590 // If the input is empty, clear the menu
9591 if ( value === '' ) {
9592 this.closeLookupMenu();
9593 // Skip population if there is already a request pending for the current value
9594 } else if ( value !== this.lookupQuery ) {
9595 this.getLookupMenuItems()
9596 .done( function ( items ) {
9597 widget.lookupMenu.clearItems();
9598 if ( items.length ) {
9599 widget.lookupMenu
9600 .addItems( items )
9601 .toggle( true );
9602 widget.initializeLookupMenuSelection();
9603 } else {
9604 widget.lookupMenu.toggle( false );
9607 .fail( function () {
9608 widget.lookupMenu.clearItems();
9609 } );
9612 return this;
9616 * Select and highlight the first selectable item in the menu.
9618 * @chainable
9620 OO.ui.LookupInputWidget.prototype.initializeLookupMenuSelection = function () {
9621 if ( !this.lookupMenu.getSelectedItem() ) {
9622 this.lookupMenu.selectItem( this.lookupMenu.getFirstSelectableItem() );
9624 this.lookupMenu.highlightItem( this.lookupMenu.getSelectedItem() );
9628 * Get lookup menu items for the current query.
9630 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument
9631 * of the done event. If the request was aborted to make way for a subsequent request,
9632 * this promise will not be rejected: it will remain pending forever.
9634 OO.ui.LookupInputWidget.prototype.getLookupMenuItems = function () {
9635 var widget = this,
9636 value = this.lookupInput.getValue(),
9637 deferred = $.Deferred(),
9638 ourRequest;
9640 this.abortLookupRequest();
9641 if ( Object.prototype.hasOwnProperty.call( this.lookupCache, value ) ) {
9642 deferred.resolve( this.getLookupMenuItemsFromData( this.lookupCache[ value ] ) );
9643 } else {
9644 this.lookupInput.pushPending();
9645 this.lookupQuery = value;
9646 ourRequest = this.lookupRequest = this.getLookupRequest();
9647 ourRequest
9648 .always( function () {
9649 // We need to pop pending even if this is an old request, otherwise
9650 // the widget will remain pending forever.
9651 // TODO: this assumes that an aborted request will fail or succeed soon after
9652 // being aborted, or at least eventually. It would be nice if we could popPending()
9653 // at abort time, but only if we knew that we hadn't already called popPending()
9654 // for that request.
9655 widget.lookupInput.popPending();
9657 .done( function ( data ) {
9658 // If this is an old request (and aborting it somehow caused it to still succeed),
9659 // ignore its success completely
9660 if ( ourRequest === widget.lookupRequest ) {
9661 widget.lookupQuery = null;
9662 widget.lookupRequest = null;
9663 widget.lookupCache[ value ] = widget.getLookupCacheItemFromData( data );
9664 deferred.resolve( widget.getLookupMenuItemsFromData( widget.lookupCache[ value ] ) );
9667 .fail( function () {
9668 // If this is an old request (or a request failing because it's being aborted),
9669 // ignore its failure completely
9670 if ( ourRequest === widget.lookupRequest ) {
9671 widget.lookupQuery = null;
9672 widget.lookupRequest = null;
9673 deferred.reject();
9675 } );
9677 return deferred.promise();
9681 * Abort the currently pending lookup request, if any.
9683 OO.ui.LookupInputWidget.prototype.abortLookupRequest = function () {
9684 var oldRequest = this.lookupRequest;
9685 if ( oldRequest ) {
9686 // First unset this.lookupRequest to the fail handler will notice
9687 // that the request is no longer current
9688 this.lookupRequest = null;
9689 this.lookupQuery = null;
9690 oldRequest.abort();
9695 * Get a new request object of the current lookup query value.
9697 * @abstract
9698 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
9700 OO.ui.LookupInputWidget.prototype.getLookupRequest = function () {
9701 // Stub, implemented in subclass
9702 return null;
9706 * Get a list of menu item widgets from the data stored by the lookup request's done handler.
9708 * @abstract
9709 * @param {Mixed} data Cached result data, usually an array
9710 * @return {OO.ui.MenuOptionWidget[]} Menu items
9712 OO.ui.LookupInputWidget.prototype.getLookupMenuItemsFromData = function () {
9713 // Stub, implemented in subclass
9714 return [];
9718 * Get lookup cache item from server response data.
9720 * @abstract
9721 * @param {Mixed} data Response from server
9722 * @return {Mixed} Cached result data
9724 OO.ui.LookupInputWidget.prototype.getLookupCacheItemFromData = function () {
9725 // Stub, implemented in subclass
9726 return [];
9730 * Set of controls for an OO.ui.OutlineSelectWidget.
9732 * Controls include moving items up and down, removing items, and adding different kinds of items.
9734 * @class
9735 * @extends OO.ui.Widget
9736 * @mixins OO.ui.GroupElement
9737 * @mixins OO.ui.IconElement
9739 * @constructor
9740 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
9741 * @param {Object} [config] Configuration options
9743 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
9744 // Allow passing positional parameters inside the config object
9745 if ( OO.isPlainObject( outline ) && config === undefined ) {
9746 config = outline;
9747 outline = config.outline;
9750 // Configuration initialization
9751 config = $.extend( { icon: 'add' }, config );
9753 // Parent constructor
9754 OO.ui.OutlineControlsWidget.super.call( this, config );
9756 // Mixin constructors
9757 OO.ui.GroupElement.call( this, config );
9758 OO.ui.IconElement.call( this, config );
9760 // Properties
9761 this.outline = outline;
9762 this.$movers = $( '<div>' );
9763 this.upButton = new OO.ui.ButtonWidget( {
9764 framed: false,
9765 icon: 'collapse',
9766 title: OO.ui.msg( 'ooui-outline-control-move-up' )
9767 } );
9768 this.downButton = new OO.ui.ButtonWidget( {
9769 framed: false,
9770 icon: 'expand',
9771 title: OO.ui.msg( 'ooui-outline-control-move-down' )
9772 } );
9773 this.removeButton = new OO.ui.ButtonWidget( {
9774 framed: false,
9775 icon: 'remove',
9776 title: OO.ui.msg( 'ooui-outline-control-remove' )
9777 } );
9779 // Events
9780 outline.connect( this, {
9781 select: 'onOutlineChange',
9782 add: 'onOutlineChange',
9783 remove: 'onOutlineChange'
9784 } );
9785 this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } );
9786 this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } );
9787 this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } );
9789 // Initialization
9790 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
9791 this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
9792 this.$movers
9793 .addClass( 'oo-ui-outlineControlsWidget-movers' )
9794 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
9795 this.$element.append( this.$icon, this.$group, this.$movers );
9798 /* Setup */
9800 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
9801 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.GroupElement );
9802 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.IconElement );
9804 /* Events */
9807 * @event move
9808 * @param {number} places Number of places to move
9812 * @event remove
9815 /* Methods */
9818 * Handle outline change events.
9820 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
9821 var i, len, firstMovable, lastMovable,
9822 items = this.outline.getItems(),
9823 selectedItem = this.outline.getSelectedItem(),
9824 movable = selectedItem && selectedItem.isMovable(),
9825 removable = selectedItem && selectedItem.isRemovable();
9827 if ( movable ) {
9828 i = -1;
9829 len = items.length;
9830 while ( ++i < len ) {
9831 if ( items[ i ].isMovable() ) {
9832 firstMovable = items[ i ];
9833 break;
9836 i = len;
9837 while ( i-- ) {
9838 if ( items[ i ].isMovable() ) {
9839 lastMovable = items[ i ];
9840 break;
9844 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
9845 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
9846 this.removeButton.setDisabled( !removable );
9850 * Mixin for widgets with a boolean on/off state.
9852 * @abstract
9853 * @class
9855 * @constructor
9856 * @param {Object} [config] Configuration options
9857 * @cfg {boolean} [value=false] Initial value
9859 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
9860 // Configuration initialization
9861 config = config || {};
9863 // Properties
9864 this.value = null;
9866 // Initialization
9867 this.$element.addClass( 'oo-ui-toggleWidget' );
9868 this.setValue( !!config.value );
9871 /* Events */
9874 * @event change
9875 * @param {boolean} value Changed value
9878 /* Methods */
9881 * Get the value of the toggle.
9883 * @return {boolean}
9885 OO.ui.ToggleWidget.prototype.getValue = function () {
9886 return this.value;
9890 * Set the value of the toggle.
9892 * @param {boolean} value New value
9893 * @fires change
9894 * @chainable
9896 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
9897 value = !!value;
9898 if ( this.value !== value ) {
9899 this.value = value;
9900 this.emit( 'change', value );
9901 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
9902 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
9903 this.$element.attr( 'aria-checked', value.toString() );
9905 return this;
9909 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
9910 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
9911 * removed, and cleared from the group.
9913 * @example
9914 * // Example: A ButtonGroupWidget with two buttons
9915 * var button1 = new OO.ui.PopupButtonWidget( {
9916 * label : 'Select a category',
9917 * icon : 'menu',
9918 * popup : {
9919 * $content: $( '<p>List of categories...</p>' ),
9920 * padded: true,
9921 * align: 'left'
9923 * } );
9924 * var button2 = new OO.ui.ButtonWidget( {
9925 * label : 'Add item'
9926 * });
9927 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
9928 * items: [button1, button2]
9929 * } );
9930 * $('body').append(buttonGroup.$element);
9932 * @class
9933 * @extends OO.ui.Widget
9934 * @mixins OO.ui.GroupElement
9936 * @constructor
9937 * @param {Object} [config] Configuration options
9938 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
9940 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
9941 // Configuration initialization
9942 config = config || {};
9944 // Parent constructor
9945 OO.ui.ButtonGroupWidget.super.call( this, config );
9947 // Mixin constructors
9948 OO.ui.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
9950 // Initialization
9951 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
9952 if ( Array.isArray( config.items ) ) {
9953 this.addItems( config.items );
9957 /* Setup */
9959 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
9960 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.GroupElement );
9963 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
9964 * feels, and functionality can be customized via the class’s configuration options
9965 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
9966 * and examples.
9968 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
9970 * @example
9971 * // A button widget
9972 * var button = new OO.ui.ButtonWidget( {
9973 * label : 'Button with Icon',
9974 * icon : 'remove',
9975 * iconTitle : 'Remove'
9976 * } );
9977 * $( 'body' ).append( button.$element );
9979 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
9981 * @class
9982 * @extends OO.ui.Widget
9983 * @mixins OO.ui.ButtonElement
9984 * @mixins OO.ui.IconElement
9985 * @mixins OO.ui.IndicatorElement
9986 * @mixins OO.ui.LabelElement
9987 * @mixins OO.ui.TitledElement
9988 * @mixins OO.ui.FlaggedElement
9989 * @mixins OO.ui.TabIndexedElement
9991 * @constructor
9992 * @param {Object} [config] Configuration options
9993 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
9994 * @cfg {string} [target] The frame or window in which to open the hyperlink.
9995 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
9997 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
9998 // Configuration initialization
9999 // FIXME: The `nofollow` alias is deprecated and will be removed (T89767)
10000 config = $.extend( { noFollow: config && config.nofollow }, config );
10002 // Parent constructor
10003 OO.ui.ButtonWidget.super.call( this, config );
10005 // Mixin constructors
10006 OO.ui.ButtonElement.call( this, config );
10007 OO.ui.IconElement.call( this, config );
10008 OO.ui.IndicatorElement.call( this, config );
10009 OO.ui.LabelElement.call( this, config );
10010 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
10011 OO.ui.FlaggedElement.call( this, config );
10012 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
10014 // Properties
10015 this.href = null;
10016 this.target = null;
10017 this.noFollow = false;
10018 this.isHyperlink = false;
10020 // Initialization
10021 this.$button.append( this.$icon, this.$label, this.$indicator );
10022 this.$element
10023 .addClass( 'oo-ui-buttonWidget' )
10024 .append( this.$button );
10025 this.setHref( config.href );
10026 this.setTarget( config.target );
10027 this.setNoFollow( config.noFollow );
10030 /* Setup */
10032 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
10033 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.ButtonElement );
10034 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.IconElement );
10035 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.IndicatorElement );
10036 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.LabelElement );
10037 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.TitledElement );
10038 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.FlaggedElement );
10039 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.TabIndexedElement );
10041 /* Methods */
10044 * @inheritdoc
10046 OO.ui.ButtonWidget.prototype.onMouseDown = function ( e ) {
10047 if ( !this.isDisabled() ) {
10048 // Remove the tab-index while the button is down to prevent the button from stealing focus
10049 this.$button.removeAttr( 'tabindex' );
10052 return OO.ui.ButtonElement.prototype.onMouseDown.call( this, e );
10056 * @inheritdoc
10058 OO.ui.ButtonWidget.prototype.onMouseUp = function ( e ) {
10059 if ( !this.isDisabled() ) {
10060 // Restore the tab-index after the button is up to restore the button's accessibility
10061 this.$button.attr( 'tabindex', this.tabIndex );
10064 return OO.ui.ButtonElement.prototype.onMouseUp.call( this, e );
10068 * @inheritdoc
10070 OO.ui.ButtonWidget.prototype.onClick = function ( e ) {
10071 var ret = OO.ui.ButtonElement.prototype.onClick.call( this, e );
10072 if ( this.isHyperlink ) {
10073 return true;
10075 return ret;
10079 * @inheritdoc
10081 OO.ui.ButtonWidget.prototype.onKeyPress = function ( e ) {
10082 var ret = OO.ui.ButtonElement.prototype.onKeyPress.call( this, e );
10083 if ( this.isHyperlink ) {
10084 return true;
10086 return ret;
10090 * Get hyperlink location.
10092 * @return {string} Hyperlink location
10094 OO.ui.ButtonWidget.prototype.getHref = function () {
10095 return this.href;
10099 * Get hyperlink target.
10101 * @return {string} Hyperlink target
10103 OO.ui.ButtonWidget.prototype.getTarget = function () {
10104 return this.target;
10108 * Get search engine traversal hint.
10110 * @return {boolean} Whether search engines should avoid traversing this hyperlink
10112 OO.ui.ButtonWidget.prototype.getNoFollow = function () {
10113 return this.noFollow;
10117 * Set hyperlink location.
10119 * @param {string|null} href Hyperlink location, null to remove
10121 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
10122 href = typeof href === 'string' ? href : null;
10124 if ( href !== this.href ) {
10125 this.href = href;
10126 if ( href !== null ) {
10127 this.$button.attr( 'href', href );
10128 this.isHyperlink = true;
10129 } else {
10130 this.$button.removeAttr( 'href' );
10131 this.isHyperlink = false;
10135 return this;
10139 * Set hyperlink target.
10141 * @param {string|null} target Hyperlink target, null to remove
10143 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
10144 target = typeof target === 'string' ? target : null;
10146 if ( target !== this.target ) {
10147 this.target = target;
10148 if ( target !== null ) {
10149 this.$button.attr( 'target', target );
10150 } else {
10151 this.$button.removeAttr( 'target' );
10155 return this;
10159 * Set search engine traversal hint.
10161 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
10163 OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) {
10164 noFollow = typeof noFollow === 'boolean' ? noFollow : true;
10166 if ( noFollow !== this.noFollow ) {
10167 this.noFollow = noFollow;
10168 if ( noFollow ) {
10169 this.$button.attr( 'rel', 'nofollow' );
10170 } else {
10171 this.$button.removeAttr( 'rel' );
10175 return this;
10179 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
10180 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
10181 * of the actions. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
10182 * and examples.
10184 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
10186 * @class
10187 * @extends OO.ui.ButtonWidget
10188 * @mixins OO.ui.PendingElement
10190 * @constructor
10191 * @param {Object} [config] Configuration options
10192 * @cfg {string} [action] Symbolic action name
10193 * @cfg {string[]} [modes] Symbolic mode names
10194 * @cfg {boolean} [framed=false] Render button with a frame
10196 OO.ui.ActionWidget = function OoUiActionWidget( config ) {
10197 // Configuration initialization
10198 config = $.extend( { framed: false }, config );
10200 // Parent constructor
10201 OO.ui.ActionWidget.super.call( this, config );
10203 // Mixin constructors
10204 OO.ui.PendingElement.call( this, config );
10206 // Properties
10207 this.action = config.action || '';
10208 this.modes = config.modes || [];
10209 this.width = 0;
10210 this.height = 0;
10212 // Initialization
10213 this.$element.addClass( 'oo-ui-actionWidget' );
10216 /* Setup */
10218 OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget );
10219 OO.mixinClass( OO.ui.ActionWidget, OO.ui.PendingElement );
10221 /* Events */
10224 * @event resize
10227 /* Methods */
10230 * Check if action is available in a certain mode.
10232 * @param {string} mode Name of mode
10233 * @return {boolean} Has mode
10235 OO.ui.ActionWidget.prototype.hasMode = function ( mode ) {
10236 return this.modes.indexOf( mode ) !== -1;
10240 * Get symbolic action name.
10242 * @return {string}
10244 OO.ui.ActionWidget.prototype.getAction = function () {
10245 return this.action;
10249 * Get symbolic action name.
10251 * @return {string}
10253 OO.ui.ActionWidget.prototype.getModes = function () {
10254 return this.modes.slice();
10258 * Emit a resize event if the size has changed.
10260 * @chainable
10262 OO.ui.ActionWidget.prototype.propagateResize = function () {
10263 var width, height;
10265 if ( this.isElementAttached() ) {
10266 width = this.$element.width();
10267 height = this.$element.height();
10269 if ( width !== this.width || height !== this.height ) {
10270 this.width = width;
10271 this.height = height;
10272 this.emit( 'resize' );
10276 return this;
10280 * @inheritdoc
10282 OO.ui.ActionWidget.prototype.setIcon = function () {
10283 // Mixin method
10284 OO.ui.IconElement.prototype.setIcon.apply( this, arguments );
10285 this.propagateResize();
10287 return this;
10291 * @inheritdoc
10293 OO.ui.ActionWidget.prototype.setLabel = function () {
10294 // Mixin method
10295 OO.ui.LabelElement.prototype.setLabel.apply( this, arguments );
10296 this.propagateResize();
10298 return this;
10302 * @inheritdoc
10304 OO.ui.ActionWidget.prototype.setFlags = function () {
10305 // Mixin method
10306 OO.ui.FlaggedElement.prototype.setFlags.apply( this, arguments );
10307 this.propagateResize();
10309 return this;
10313 * @inheritdoc
10315 OO.ui.ActionWidget.prototype.clearFlags = function () {
10316 // Mixin method
10317 OO.ui.FlaggedElement.prototype.clearFlags.apply( this, arguments );
10318 this.propagateResize();
10320 return this;
10324 * Toggle visibility of button.
10326 * @param {boolean} [show] Show button, omit to toggle visibility
10327 * @chainable
10329 OO.ui.ActionWidget.prototype.toggle = function () {
10330 // Parent method
10331 OO.ui.ActionWidget.super.prototype.toggle.apply( this, arguments );
10332 this.propagateResize();
10334 return this;
10338 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
10339 * which is used to display additional information or options.
10341 * @example
10342 * // Example of a popup button.
10343 * var popupButton = new OO.ui.PopupButtonWidget( {
10344 * label: 'Popup button with options',
10345 * icon: 'menu',
10346 * popup: {
10347 * $content: $( '<p>Additional options here.</p>' ),
10348 * padded: true,
10349 * align: 'left'
10351 * } );
10352 * // Append the button to the DOM.
10353 * $( 'body' ).append( popupButton.$element );
10355 * @class
10356 * @extends OO.ui.ButtonWidget
10357 * @mixins OO.ui.PopupElement
10359 * @constructor
10360 * @param {Object} [config] Configuration options
10362 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
10363 // Parent constructor
10364 OO.ui.PopupButtonWidget.super.call( this, config );
10366 // Mixin constructors
10367 OO.ui.PopupElement.call( this, config );
10369 // Events
10370 this.connect( this, { click: 'onAction' } );
10372 // Initialization
10373 this.$element
10374 .addClass( 'oo-ui-popupButtonWidget' )
10375 .attr( 'aria-haspopup', 'true' )
10376 .append( this.popup.$element );
10379 /* Setup */
10381 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
10382 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.PopupElement );
10384 /* Methods */
10387 * Handle the button action being triggered.
10389 * @private
10391 OO.ui.PopupButtonWidget.prototype.onAction = function () {
10392 this.popup.toggle();
10396 * Button that toggles on and off.
10398 * @class
10399 * @extends OO.ui.ButtonWidget
10400 * @mixins OO.ui.ToggleWidget
10402 * @constructor
10403 * @param {Object} [config] Configuration options
10404 * @cfg {boolean} [value=false] Initial value
10406 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
10407 // Configuration initialization
10408 config = config || {};
10410 // Parent constructor
10411 OO.ui.ToggleButtonWidget.super.call( this, config );
10413 // Mixin constructors
10414 OO.ui.ToggleWidget.call( this, config );
10416 // Events
10417 this.connect( this, { click: 'onAction' } );
10419 // Initialization
10420 this.$element.addClass( 'oo-ui-toggleButtonWidget' );
10423 /* Setup */
10425 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ButtonWidget );
10426 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
10428 /* Methods */
10431 * Handle the button action being triggered.
10433 OO.ui.ToggleButtonWidget.prototype.onAction = function () {
10434 this.setValue( !this.value );
10438 * @inheritdoc
10440 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
10441 value = !!value;
10442 if ( value !== this.value ) {
10443 this.$button.attr( 'aria-pressed', value.toString() );
10444 this.setActive( value );
10447 // Parent method (from mixin)
10448 OO.ui.ToggleWidget.prototype.setValue.call( this, value );
10450 return this;
10454 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
10455 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
10456 * users can interact with it.
10458 * @example
10459 * // Example: A DropdownWidget with a menu that contains three options
10460 * var dropDown=new OO.ui.DropdownWidget( {
10461 * label: 'Dropdown menu: Select a menu option',
10462 * menu: {
10463 * items: [
10464 * new OO.ui.MenuOptionWidget( {
10465 * data: 'a',
10466 * label: 'First'
10467 * } ),
10468 * new OO.ui.MenuOptionWidget( {
10469 * data: 'b',
10470 * label: 'Second'
10471 * } ),
10472 * new OO.ui.MenuOptionWidget( {
10473 * data: 'c',
10474 * label: 'Third'
10475 * } )
10478 * } );
10480 * $('body').append(dropDown.$element);
10482 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
10484 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
10486 * @class
10487 * @extends OO.ui.Widget
10488 * @mixins OO.ui.IconElement
10489 * @mixins OO.ui.IndicatorElement
10490 * @mixins OO.ui.LabelElement
10491 * @mixins OO.ui.TitledElement
10492 * @mixins OO.ui.TabIndexedElement
10494 * @constructor
10495 * @param {Object} [config] Configuration options
10496 * @cfg {Object} [menu] Configuration options to pass to menu widget
10498 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
10499 // Configuration initialization
10500 config = $.extend( { indicator: 'down' }, config );
10502 // Parent constructor
10503 OO.ui.DropdownWidget.super.call( this, config );
10505 // Properties (must be set before TabIndexedElement constructor call)
10506 this.$handle = this.$( '<span>' );
10508 // Mixin constructors
10509 OO.ui.IconElement.call( this, config );
10510 OO.ui.IndicatorElement.call( this, config );
10511 OO.ui.LabelElement.call( this, config );
10512 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
10513 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
10515 // Properties
10516 this.menu = new OO.ui.MenuSelectWidget( $.extend( { widget: this }, config.menu ) );
10518 // Events
10519 this.$handle.on( {
10520 click: this.onClick.bind( this ),
10521 keypress: this.onKeyPress.bind( this )
10522 } );
10523 this.menu.connect( this, { select: 'onMenuSelect' } );
10525 // Initialization
10526 this.$handle
10527 .addClass( 'oo-ui-dropdownWidget-handle' )
10528 .append( this.$icon, this.$label, this.$indicator );
10529 this.$element
10530 .addClass( 'oo-ui-dropdownWidget' )
10531 .append( this.$handle, this.menu.$element );
10534 /* Setup */
10536 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
10537 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.IconElement );
10538 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.IndicatorElement );
10539 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.LabelElement );
10540 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.TitledElement );
10541 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.TabIndexedElement );
10543 /* Methods */
10546 * Get the menu.
10548 * @return {OO.ui.MenuSelectWidget} Menu of widget
10550 OO.ui.DropdownWidget.prototype.getMenu = function () {
10551 return this.menu;
10555 * Handles menu select events.
10557 * @private
10558 * @param {OO.ui.MenuOptionWidget} item Selected menu item
10560 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
10561 var selectedLabel;
10563 if ( !item ) {
10564 return;
10567 selectedLabel = item.getLabel();
10569 // If the label is a DOM element, clone it, because setLabel will append() it
10570 if ( selectedLabel instanceof jQuery ) {
10571 selectedLabel = selectedLabel.clone();
10574 this.setLabel( selectedLabel );
10578 * Handle mouse click events.
10580 * @private
10581 * @param {jQuery.Event} e Mouse click event
10583 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
10584 if ( !this.isDisabled() && e.which === 1 ) {
10585 this.menu.toggle();
10587 return false;
10591 * Handle key press events.
10593 * @private
10594 * @param {jQuery.Event} e Key press event
10596 OO.ui.DropdownWidget.prototype.onKeyPress = function ( e ) {
10597 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
10598 this.menu.toggle();
10600 return false;
10604 * IconWidget is a generic widget for {@link OO.ui.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
10605 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
10606 * for a list of icons included in the library.
10608 * @example
10609 * // An icon widget with a label
10610 * var myIcon = new OO.ui.IconWidget({
10611 * icon: 'help',
10612 * iconTitle: 'Help'
10613 * });
10614 * // Create a label.
10615 * var iconLabel = new OO.ui.LabelWidget({
10616 * label: 'Help'
10617 * });
10618 * $('body').append(myIcon.$element, iconLabel.$element);
10620 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
10622 * @class
10623 * @extends OO.ui.Widget
10624 * @mixins OO.ui.IconElement
10625 * @mixins OO.ui.TitledElement
10627 * @constructor
10628 * @param {Object} [config] Configuration options
10630 OO.ui.IconWidget = function OoUiIconWidget( config ) {
10631 // Configuration initialization
10632 config = config || {};
10634 // Parent constructor
10635 OO.ui.IconWidget.super.call( this, config );
10637 // Mixin constructors
10638 OO.ui.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
10639 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
10641 // Initialization
10642 this.$element.addClass( 'oo-ui-iconWidget' );
10645 /* Setup */
10647 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
10648 OO.mixinClass( OO.ui.IconWidget, OO.ui.IconElement );
10649 OO.mixinClass( OO.ui.IconWidget, OO.ui.TitledElement );
10651 /* Static Properties */
10653 OO.ui.IconWidget.static.tagName = 'span';
10656 * Indicator widget.
10658 * See OO.ui.IndicatorElement for more information.
10660 * @class
10661 * @extends OO.ui.Widget
10662 * @mixins OO.ui.IndicatorElement
10663 * @mixins OO.ui.TitledElement
10665 * @constructor
10666 * @param {Object} [config] Configuration options
10668 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
10669 // Configuration initialization
10670 config = config || {};
10672 // Parent constructor
10673 OO.ui.IndicatorWidget.super.call( this, config );
10675 // Mixin constructors
10676 OO.ui.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
10677 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
10679 // Initialization
10680 this.$element.addClass( 'oo-ui-indicatorWidget' );
10683 /* Setup */
10685 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
10686 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.IndicatorElement );
10687 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.TitledElement );
10689 /* Static Properties */
10691 OO.ui.IndicatorWidget.static.tagName = 'span';
10694 * InputWidget is the base class for all input widgets, which
10695 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
10696 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
10697 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
10699 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
10701 * @abstract
10702 * @class
10703 * @extends OO.ui.Widget
10704 * @mixins OO.ui.FlaggedElement
10705 * @mixins OO.ui.TabIndexedElement
10707 * @constructor
10708 * @param {Object} [config] Configuration options
10709 * @cfg {string} [name=''] HTML input name
10710 * @cfg {string} [value=''] Input value
10711 * @cfg {Function} [inputFilter] Filter function to apply to the input. Takes a string argument and returns a string.
10713 OO.ui.InputWidget = function OoUiInputWidget( config ) {
10714 // Configuration initialization
10715 config = config || {};
10717 // Parent constructor
10718 OO.ui.InputWidget.super.call( this, config );
10720 // Properties
10721 this.$input = this.getInputElement( config );
10722 this.value = '';
10723 this.inputFilter = config.inputFilter;
10725 // Mixin constructors
10726 OO.ui.FlaggedElement.call( this, config );
10727 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
10729 // Events
10730 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
10732 // Initialization
10733 this.$input
10734 .attr( 'name', config.name )
10735 .prop( 'disabled', this.isDisabled() );
10736 this.$element.addClass( 'oo-ui-inputWidget' ).append( this.$input, $( '<span>' ) );
10737 this.setValue( config.value );
10740 /* Setup */
10742 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
10743 OO.mixinClass( OO.ui.InputWidget, OO.ui.FlaggedElement );
10744 OO.mixinClass( OO.ui.InputWidget, OO.ui.TabIndexedElement );
10746 /* Events */
10749 * @event change
10750 * @param {string} value
10753 /* Methods */
10756 * Get input element.
10758 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
10759 * different circumstances. The element must have a `value` property (like form elements).
10761 * @private
10762 * @param {Object} config Configuration options
10763 * @return {jQuery} Input element
10765 OO.ui.InputWidget.prototype.getInputElement = function () {
10766 return $( '<input>' );
10770 * Handle potentially value-changing events.
10772 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
10774 OO.ui.InputWidget.prototype.onEdit = function () {
10775 var widget = this;
10776 if ( !this.isDisabled() ) {
10777 // Allow the stack to clear so the value will be updated
10778 setTimeout( function () {
10779 widget.setValue( widget.$input.val() );
10780 } );
10785 * Get the value of the input.
10787 * @return {string} Input value
10789 OO.ui.InputWidget.prototype.getValue = function () {
10790 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
10791 // it, and we won't know unless they're kind enough to trigger a 'change' event.
10792 var value = this.$input.val();
10793 if ( this.value !== value ) {
10794 this.setValue( value );
10796 return this.value;
10800 * Sets the direction of the current input, either RTL or LTR
10802 * @param {boolean} isRTL
10804 OO.ui.InputWidget.prototype.setRTL = function ( isRTL ) {
10805 this.$input.prop( 'dir', isRTL ? 'rtl' : 'ltr' );
10809 * Set the value of the input.
10811 * @param {string} value New value
10812 * @fires change
10813 * @chainable
10815 OO.ui.InputWidget.prototype.setValue = function ( value ) {
10816 value = this.cleanUpValue( value );
10817 // Update the DOM if it has changed. Note that with cleanUpValue, it
10818 // is possible for the DOM value to change without this.value changing.
10819 if ( this.$input.val() !== value ) {
10820 this.$input.val( value );
10822 if ( this.value !== value ) {
10823 this.value = value;
10824 this.emit( 'change', this.value );
10826 return this;
10830 * Clean up incoming value.
10832 * Ensures value is a string, and converts undefined and null to empty string.
10834 * @private
10835 * @param {string} value Original value
10836 * @return {string} Cleaned up value
10838 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
10839 if ( value === undefined || value === null ) {
10840 return '';
10841 } else if ( this.inputFilter ) {
10842 return this.inputFilter( String( value ) );
10843 } else {
10844 return String( value );
10849 * Simulate the behavior of clicking on a label bound to this input.
10851 OO.ui.InputWidget.prototype.simulateLabelClick = function () {
10852 if ( !this.isDisabled() ) {
10853 if ( this.$input.is( ':checkbox,:radio' ) ) {
10854 this.$input.click();
10855 } else if ( this.$input.is( ':input' ) ) {
10856 this.$input[ 0 ].focus();
10862 * @inheritdoc
10864 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
10865 OO.ui.InputWidget.super.prototype.setDisabled.call( this, state );
10866 if ( this.$input ) {
10867 this.$input.prop( 'disabled', this.isDisabled() );
10869 return this;
10873 * Focus the input.
10875 * @chainable
10877 OO.ui.InputWidget.prototype.focus = function () {
10878 this.$input[ 0 ].focus();
10879 return this;
10883 * Blur the input.
10885 * @chainable
10887 OO.ui.InputWidget.prototype.blur = function () {
10888 this.$input[ 0 ].blur();
10889 return this;
10893 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
10894 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
10895 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
10896 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
10897 * [OOjs UI documentation on MediaWiki] [1] for more information.
10899 * @example
10900 * // A ButtonInputWidget rendered as an HTML button, the default.
10901 * var button = new OO.ui.ButtonInputWidget( {
10902 * label: 'Input button',
10903 * icon: 'check',
10904 * value: 'check'
10905 * } );
10906 * $( 'body' ).append( button.$element );
10908 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
10910 * @class
10911 * @extends OO.ui.InputWidget
10912 * @mixins OO.ui.ButtonElement
10913 * @mixins OO.ui.IconElement
10914 * @mixins OO.ui.IndicatorElement
10915 * @mixins OO.ui.LabelElement
10916 * @mixins OO.ui.TitledElement
10917 * @mixins OO.ui.FlaggedElement
10919 * @constructor
10920 * @param {Object} [config] Configuration options
10921 * @cfg {string} [type='button'] HTML tag `type` attribute, may be 'button', 'submit' or 'reset'
10922 * @cfg {boolean} [useInputTag=false] Whether to use `<input/>` rather than `<button/>`. Only useful
10923 * if you need IE 6 support in a form with multiple buttons. If you use this option, icons and
10924 * indicators will not be displayed, it won't be possible to have a non-plaintext label, and it
10925 * won't be possible to set a value (which will internally become identical to the label).
10927 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
10928 // Configuration initialization
10929 config = $.extend( { type: 'button', useInputTag: false }, config );
10931 // Properties (must be set before parent constructor, which calls #setValue)
10932 this.useInputTag = config.useInputTag;
10933 this.type = config.type;
10935 // Parent constructor
10936 OO.ui.ButtonInputWidget.super.call( this, config );
10938 // Mixin constructors
10939 OO.ui.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
10940 OO.ui.IconElement.call( this, config );
10941 OO.ui.IndicatorElement.call( this, config );
10942 OO.ui.LabelElement.call( this, config );
10943 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
10944 OO.ui.FlaggedElement.call( this, config );
10946 // Initialization
10947 if ( !config.useInputTag ) {
10948 this.$input.append( this.$icon, this.$label, this.$indicator );
10950 this.$element.addClass( 'oo-ui-buttonInputWidget' );
10953 /* Setup */
10955 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
10956 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.ButtonElement );
10957 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.IconElement );
10958 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.IndicatorElement );
10959 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.LabelElement );
10960 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.TitledElement );
10961 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.FlaggedElement );
10963 /* Methods */
10966 * @inheritdoc
10967 * @private
10969 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
10970 var html = '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + config.type + '">';
10971 return $( html );
10975 * Set label value.
10977 * Overridden to support setting the 'value' of `<input/>` elements.
10979 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
10980 * text; or null for no label
10981 * @chainable
10983 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
10984 OO.ui.LabelElement.prototype.setLabel.call( this, label );
10986 if ( this.useInputTag ) {
10987 if ( typeof label === 'function' ) {
10988 label = OO.ui.resolveMsg( label );
10990 if ( label instanceof jQuery ) {
10991 label = label.text();
10993 if ( !label ) {
10994 label = '';
10996 this.$input.val( label );
10999 return this;
11003 * Set the value of the input.
11005 * Overridden to disable for `<input/>` elements, which have value identical to the label.
11007 * @param {string} value New value
11008 * @chainable
11010 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
11011 if ( !this.useInputTag ) {
11012 OO.ui.ButtonInputWidget.super.prototype.setValue.call( this, value );
11014 return this;
11018 * @inheritdoc
11020 OO.ui.ButtonInputWidget.prototype.onClick = function ( e ) {
11021 var ret = OO.ui.ButtonElement.prototype.onClick.call( this, e );
11022 if ( this.type === 'submit' ) {
11023 // Never prevent default action (form submission)
11024 return true;
11026 return ret;
11030 * Checkbox input widget.
11032 * @class
11033 * @extends OO.ui.InputWidget
11035 * @constructor
11036 * @param {Object} [config] Configuration options
11037 * @cfg {boolean} [selected=false] Whether the checkbox is initially selected
11039 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
11040 // Configuration initialization
11041 config = config || {};
11043 // Parent constructor
11044 OO.ui.CheckboxInputWidget.super.call( this, config );
11046 // Initialization
11047 this.$element.addClass( 'oo-ui-checkboxInputWidget' );
11048 this.setSelected( config.selected !== undefined ? config.selected : false );
11051 /* Setup */
11053 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
11055 /* Methods */
11058 * @inheritdoc
11059 * @private
11061 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
11062 return $( '<input type="checkbox" />' );
11066 * @inheritdoc
11068 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
11069 var widget = this;
11070 if ( !this.isDisabled() ) {
11071 // Allow the stack to clear so the value will be updated
11072 setTimeout( function () {
11073 widget.setSelected( widget.$input.prop( 'checked' ) );
11074 } );
11079 * Set selection state of this checkbox.
11081 * @param {boolean} state Whether the checkbox is selected
11082 * @chainable
11084 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
11085 state = !!state;
11086 if ( this.selected !== state ) {
11087 this.selected = state;
11088 this.$input.prop( 'checked', this.selected );
11089 this.emit( 'change', this.selected );
11091 return this;
11095 * Check if this checkbox is selected.
11097 * @return {boolean} Checkbox is selected
11099 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
11100 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
11101 // it, and we won't know unless they're kind enough to trigger a 'change' event.
11102 var selected = this.$input.prop( 'checked' );
11103 if ( this.selected !== selected ) {
11104 this.setSelected( selected );
11106 return this.selected;
11110 * A OO.ui.DropdownWidget synchronized with a `<input type=hidden>` for form submission. Intended to
11111 * be used within a OO.ui.FormLayout.
11113 * @class
11114 * @extends OO.ui.InputWidget
11116 * @constructor
11117 * @param {Object} [config] Configuration options
11118 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
11120 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
11121 // Configuration initialization
11122 config = config || {};
11124 // Properties (must be done before parent constructor which calls #setDisabled)
11125 this.dropdownWidget = new OO.ui.DropdownWidget();
11127 // Parent constructor
11128 OO.ui.DropdownInputWidget.super.call( this, config );
11130 // Events
11131 this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } );
11133 // Initialization
11134 this.setOptions( config.options || [] );
11135 this.$element
11136 .addClass( 'oo-ui-dropdownInputWidget' )
11137 .append( this.dropdownWidget.$element );
11140 /* Setup */
11142 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
11144 /* Methods */
11147 * @inheritdoc
11148 * @private
11150 OO.ui.DropdownInputWidget.prototype.getInputElement = function () {
11151 return $( '<input type="hidden">' );
11155 * Handles menu select events.
11157 * @param {OO.ui.MenuOptionWidget} item Selected menu item
11159 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
11160 this.setValue( item.getData() );
11164 * @inheritdoc
11166 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
11167 var item = this.dropdownWidget.getMenu().getItemFromData( value );
11168 if ( item ) {
11169 this.dropdownWidget.getMenu().selectItem( item );
11171 OO.ui.DropdownInputWidget.super.prototype.setValue.call( this, value );
11172 return this;
11176 * @inheritdoc
11178 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
11179 this.dropdownWidget.setDisabled( state );
11180 OO.ui.DropdownInputWidget.super.prototype.setDisabled.call( this, state );
11181 return this;
11185 * Set the options available for this input.
11187 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
11188 * @chainable
11190 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
11191 var value = this.getValue();
11193 // Rebuild the dropdown menu
11194 this.dropdownWidget.getMenu()
11195 .clearItems()
11196 .addItems( options.map( function ( opt ) {
11197 return new OO.ui.MenuOptionWidget( {
11198 data: opt.data,
11199 label: opt.label !== undefined ? opt.label : opt.data
11200 } );
11201 } ) );
11203 // Restore the previous value, or reset to something sensible
11204 if ( this.dropdownWidget.getMenu().getItemFromData( value ) ) {
11205 // Previous value is still available, ensure consistency with the dropdown
11206 this.setValue( value );
11207 } else {
11208 // No longer valid, reset
11209 if ( options.length ) {
11210 this.setValue( options[ 0 ].data );
11214 return this;
11218 * @inheritdoc
11220 OO.ui.DropdownInputWidget.prototype.focus = function () {
11221 this.dropdownWidget.getMenu().toggle( true );
11222 return this;
11226 * @inheritdoc
11228 OO.ui.DropdownInputWidget.prototype.blur = function () {
11229 this.dropdownWidget.getMenu().toggle( false );
11230 return this;
11234 * Radio input widget.
11236 * Radio buttons only make sense as a set, and you probably want to use the OO.ui.RadioSelectWidget
11237 * class instead of using this class directly.
11239 * @class
11240 * @extends OO.ui.InputWidget
11242 * @constructor
11243 * @param {Object} [config] Configuration options
11244 * @cfg {boolean} [selected=false] Whether the radio button is initially selected
11246 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
11247 // Configuration initialization
11248 config = config || {};
11250 // Parent constructor
11251 OO.ui.RadioInputWidget.super.call( this, config );
11253 // Initialization
11254 this.$element.addClass( 'oo-ui-radioInputWidget' );
11255 this.setSelected( config.selected !== undefined ? config.selected : false );
11258 /* Setup */
11260 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
11262 /* Methods */
11265 * @inheritdoc
11266 * @private
11268 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
11269 return $( '<input type="radio" />' );
11273 * @inheritdoc
11275 OO.ui.RadioInputWidget.prototype.onEdit = function () {
11276 // RadioInputWidget doesn't track its state.
11280 * Set selection state of this radio button.
11282 * @param {boolean} state Whether the button is selected
11283 * @chainable
11285 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
11286 // RadioInputWidget doesn't track its state.
11287 this.$input.prop( 'checked', state );
11288 return this;
11292 * Check if this radio button is selected.
11294 * @return {boolean} Radio is selected
11296 OO.ui.RadioInputWidget.prototype.isSelected = function () {
11297 return this.$input.prop( 'checked' );
11301 * Input widget with a text field.
11303 * @class
11304 * @extends OO.ui.InputWidget
11305 * @mixins OO.ui.IconElement
11306 * @mixins OO.ui.IndicatorElement
11307 * @mixins OO.ui.PendingElement
11308 * @mixins OO.ui.LabelElement
11310 * @constructor
11311 * @param {Object} [config] Configuration options
11312 * @cfg {string} [type='text'] HTML tag `type` attribute
11313 * @cfg {string} [placeholder] Placeholder text
11314 * @cfg {boolean} [autofocus=false] Ask the browser to focus this widget, using the 'autofocus' HTML
11315 * attribute
11316 * @cfg {boolean} [readOnly=false] Prevent changes
11317 * @cfg {number} [maxLength] Maximum allowed number of characters to input
11318 * @cfg {boolean} [multiline=false] Allow multiple lines of text
11319 * @cfg {boolean} [autosize=false] Automatically resize to fit content
11320 * @cfg {boolean} [maxRows=10] Maximum number of rows to make visible when autosizing
11321 * @cfg {string} [labelPosition='after'] Label position, 'before' or 'after'
11322 * @cfg {boolean} [required=false] Mark the field as required
11323 * @cfg {RegExp|string} [validate] Regular expression to validate against (or symbolic name referencing
11324 * one, see #static-validationPatterns)
11326 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
11327 // Configuration initialization
11328 config = $.extend( {
11329 type: 'text',
11330 labelPosition: 'after',
11331 maxRows: 10
11332 }, config );
11334 // Parent constructor
11335 OO.ui.TextInputWidget.super.call( this, config );
11337 // Mixin constructors
11338 OO.ui.IconElement.call( this, config );
11339 OO.ui.IndicatorElement.call( this, config );
11340 OO.ui.PendingElement.call( this, config );
11341 OO.ui.LabelElement.call( this, config );
11343 // Properties
11344 this.readOnly = false;
11345 this.multiline = !!config.multiline;
11346 this.autosize = !!config.autosize;
11347 this.maxRows = config.maxRows;
11348 this.validate = null;
11350 // Clone for resizing
11351 if ( this.autosize ) {
11352 this.$clone = this.$input
11353 .clone()
11354 .insertAfter( this.$input )
11355 .attr( 'aria-hidden', 'true' )
11356 .addClass( 'oo-ui-element-hidden' );
11359 this.setValidation( config.validate );
11360 this.setLabelPosition( config.labelPosition );
11362 // Events
11363 this.$input.on( {
11364 keypress: this.onKeyPress.bind( this ),
11365 blur: this.setValidityFlag.bind( this )
11366 } );
11367 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
11368 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
11369 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
11370 this.on( 'labelChange', this.updatePosition.bind( this ) );
11372 // Initialization
11373 this.$element
11374 .addClass( 'oo-ui-textInputWidget' )
11375 .append( this.$icon, this.$indicator );
11376 this.setReadOnly( !!config.readOnly );
11377 if ( config.placeholder ) {
11378 this.$input.attr( 'placeholder', config.placeholder );
11380 if ( config.maxLength !== undefined ) {
11381 this.$input.attr( 'maxlength', config.maxLength );
11383 if ( config.autofocus ) {
11384 this.$input.attr( 'autofocus', 'autofocus' );
11386 if ( config.required ) {
11387 this.$input.attr( 'required', 'true' );
11391 /* Setup */
11393 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
11394 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.IconElement );
11395 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.IndicatorElement );
11396 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.PendingElement );
11397 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.LabelElement );
11399 /* Static properties */
11401 OO.ui.TextInputWidget.static.validationPatterns = {
11402 'non-empty': /.+/,
11403 integer: /^\d+$/
11406 /* Events */
11409 * User presses enter inside the text box.
11411 * Not called if input is multiline.
11413 * @event enter
11417 * User clicks the icon.
11419 * @deprecated Fundamentally not accessible. Make the icon focusable, associate a label or tooltip,
11420 * and handle click/keypress events on it manually.
11421 * @event icon
11425 * User clicks the indicator.
11427 * @deprecated Fundamentally not accessible. Make the indicator focusable, associate a label or
11428 * tooltip, and handle click/keypress events on it manually.
11429 * @event indicator
11432 /* Methods */
11435 * Handle icon mouse down events.
11437 * @param {jQuery.Event} e Mouse down event
11438 * @fires icon
11440 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
11441 if ( e.which === 1 ) {
11442 this.$input[ 0 ].focus();
11443 this.emit( 'icon' );
11444 return false;
11449 * Handle indicator mouse down events.
11451 * @param {jQuery.Event} e Mouse down event
11452 * @fires indicator
11454 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
11455 if ( e.which === 1 ) {
11456 this.$input[ 0 ].focus();
11457 this.emit( 'indicator' );
11458 return false;
11463 * Handle key press events.
11465 * @param {jQuery.Event} e Key press event
11466 * @fires enter If enter key is pressed and input is not multiline
11468 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
11469 if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) {
11470 this.emit( 'enter', e );
11475 * Handle element attach events.
11477 * @param {jQuery.Event} e Element attach event
11479 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
11480 // Any previously calculated size is now probably invalid if we reattached elsewhere
11481 this.valCache = null;
11482 this.adjustSize();
11483 this.positionLabel();
11487 * @inheritdoc
11489 OO.ui.TextInputWidget.prototype.onEdit = function () {
11490 this.adjustSize();
11492 // Parent method
11493 return OO.ui.TextInputWidget.super.prototype.onEdit.call( this );
11497 * @inheritdoc
11499 OO.ui.TextInputWidget.prototype.setValue = function ( value ) {
11500 // Parent method
11501 OO.ui.TextInputWidget.super.prototype.setValue.call( this, value );
11503 this.setValidityFlag();
11504 this.adjustSize();
11505 return this;
11509 * Check if the widget is read-only.
11511 * @return {boolean}
11513 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
11514 return this.readOnly;
11518 * Set the read-only state of the widget.
11520 * This should probably change the widget's appearance and prevent it from being used.
11522 * @param {boolean} state Make input read-only
11523 * @chainable
11525 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
11526 this.readOnly = !!state;
11527 this.$input.prop( 'readOnly', this.readOnly );
11528 return this;
11532 * Automatically adjust the size of the text input.
11534 * This only affects multi-line inputs that are auto-sized.
11536 * @chainable
11538 OO.ui.TextInputWidget.prototype.adjustSize = function () {
11539 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError, idealHeight;
11541 if ( this.multiline && this.autosize && this.$input.val() !== this.valCache ) {
11542 this.$clone
11543 .val( this.$input.val() )
11544 .attr( 'rows', '' )
11545 // Set inline height property to 0 to measure scroll height
11546 .css( 'height', 0 );
11548 this.$clone.removeClass( 'oo-ui-element-hidden' );
11550 this.valCache = this.$input.val();
11552 scrollHeight = this.$clone[ 0 ].scrollHeight;
11554 // Remove inline height property to measure natural heights
11555 this.$clone.css( 'height', '' );
11556 innerHeight = this.$clone.innerHeight();
11557 outerHeight = this.$clone.outerHeight();
11559 // Measure max rows height
11560 this.$clone
11561 .attr( 'rows', this.maxRows )
11562 .css( 'height', 'auto' )
11563 .val( '' );
11564 maxInnerHeight = this.$clone.innerHeight();
11566 // Difference between reported innerHeight and scrollHeight with no scrollbars present
11567 // Equals 1 on Blink-based browsers and 0 everywhere else
11568 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
11569 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
11571 this.$clone.addClass( 'oo-ui-element-hidden' );
11573 // Only apply inline height when expansion beyond natural height is needed
11574 if ( idealHeight > innerHeight ) {
11575 // Use the difference between the inner and outer height as a buffer
11576 this.$input.css( 'height', idealHeight + ( outerHeight - innerHeight ) );
11577 } else {
11578 this.$input.css( 'height', '' );
11581 return this;
11585 * @inheritdoc
11586 * @private
11588 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
11589 return config.multiline ? $( '<textarea>' ) : $( '<input type="' + config.type + '" />' );
11593 * Check if input supports multiple lines.
11595 * @return {boolean}
11597 OO.ui.TextInputWidget.prototype.isMultiline = function () {
11598 return !!this.multiline;
11602 * Check if input automatically adjusts its size.
11604 * @return {boolean}
11606 OO.ui.TextInputWidget.prototype.isAutosizing = function () {
11607 return !!this.autosize;
11611 * Select the contents of the input.
11613 * @chainable
11615 OO.ui.TextInputWidget.prototype.select = function () {
11616 this.$input.select();
11617 return this;
11621 * Sets the validation pattern to use.
11622 * @param {RegExp|string|null} validate Regular expression (or symbolic name referencing
11623 * one, see #static-validationPatterns)
11625 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
11626 if ( validate instanceof RegExp ) {
11627 this.validate = validate;
11628 } else {
11629 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
11634 * Sets the 'invalid' flag appropriately.
11636 OO.ui.TextInputWidget.prototype.setValidityFlag = function () {
11637 var widget = this;
11638 this.isValid().done( function ( valid ) {
11639 widget.setFlags( { invalid: !valid } );
11640 } );
11644 * Returns whether or not the current value is considered valid, according to the
11645 * supplied validation pattern.
11647 * @return {jQuery.Deferred}
11649 OO.ui.TextInputWidget.prototype.isValid = function () {
11650 return $.Deferred().resolve( !!this.getValue().match( this.validate ) ).promise();
11654 * Set the position of the inline label.
11656 * @param {string} labelPosition Label position, 'before' or 'after'
11657 * @chainable
11659 OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
11660 this.labelPosition = labelPosition;
11661 this.updatePosition();
11662 return this;
11666 * Deprecated alias of #setLabelPosition
11668 * @deprecated Use setLabelPosition instead.
11670 OO.ui.TextInputWidget.prototype.setPosition =
11671 OO.ui.TextInputWidget.prototype.setLabelPosition;
11674 * Update the position of the inline label.
11676 * @chainable
11678 OO.ui.TextInputWidget.prototype.updatePosition = function () {
11679 var after = this.labelPosition === 'after';
11681 this.$element
11682 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
11683 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
11685 if ( this.label ) {
11686 this.positionLabel();
11689 return this;
11693 * Position the label by setting the correct padding on the input.
11695 * @chainable
11697 OO.ui.TextInputWidget.prototype.positionLabel = function () {
11698 // Clear old values
11699 this.$input
11700 // Clear old values if present
11701 .css( {
11702 'padding-right': '',
11703 'padding-left': ''
11704 } );
11706 if ( this.label ) {
11707 this.$element.append( this.$label );
11708 } else {
11709 this.$label.detach();
11710 return;
11713 var after = this.labelPosition === 'after',
11714 rtl = this.$element.css( 'direction' ) === 'rtl',
11715 property = after === rtl ? 'padding-left' : 'padding-right';
11717 this.$input.css( property, this.$label.outerWidth( true ) );
11719 return this;
11723 * Text input with a menu of optional values.
11725 * @class
11726 * @extends OO.ui.Widget
11727 * @mixins OO.ui.TabIndexedElement
11729 * @constructor
11730 * @param {Object} [config] Configuration options
11731 * @cfg {Object} [menu] Configuration options to pass to menu widget
11732 * @cfg {Object} [input] Configuration options to pass to input widget
11733 * @cfg {jQuery} [$overlay] Overlay layer; defaults to relative positioning
11735 OO.ui.ComboBoxWidget = function OoUiComboBoxWidget( config ) {
11736 // Configuration initialization
11737 config = config || {};
11739 // Parent constructor
11740 OO.ui.ComboBoxWidget.super.call( this, config );
11742 // Properties (must be set before TabIndexedElement constructor call)
11743 this.$indicator = this.$( '<span>' );
11745 // Mixin constructors
11746 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$indicator } ) );
11748 // Properties
11749 this.$overlay = config.$overlay || this.$element;
11750 this.input = new OO.ui.TextInputWidget( $.extend(
11752 indicator: 'down',
11753 $indicator: this.$indicator,
11754 disabled: this.isDisabled()
11756 config.input
11757 ) );
11758 this.input.$input.eq( 0 ).attr( {
11759 role: 'combobox',
11760 'aria-autocomplete': 'list'
11761 } );
11762 this.menu = new OO.ui.TextInputMenuSelectWidget( this.input, $.extend(
11764 widget: this,
11765 input: this.input,
11766 disabled: this.isDisabled()
11768 config.menu
11769 ) );
11771 // Events
11772 this.$indicator.on( {
11773 click: this.onClick.bind( this ),
11774 keypress: this.onKeyPress.bind( this )
11775 } );
11776 this.input.connect( this, {
11777 change: 'onInputChange',
11778 enter: 'onInputEnter'
11779 } );
11780 this.menu.connect( this, {
11781 choose: 'onMenuChoose',
11782 add: 'onMenuItemsChange',
11783 remove: 'onMenuItemsChange'
11784 } );
11786 // Initialization
11787 this.$element.addClass( 'oo-ui-comboBoxWidget' ).append( this.input.$element );
11788 this.$overlay.append( this.menu.$element );
11789 this.onMenuItemsChange();
11792 /* Setup */
11794 OO.inheritClass( OO.ui.ComboBoxWidget, OO.ui.Widget );
11795 OO.mixinClass( OO.ui.ComboBoxWidget, OO.ui.TabIndexedElement );
11797 /* Methods */
11800 * Get the combobox's menu.
11801 * @return {OO.ui.TextInputMenuSelectWidget} Menu widget
11803 OO.ui.ComboBoxWidget.prototype.getMenu = function () {
11804 return this.menu;
11808 * Handle input change events.
11810 * @param {string} value New value
11812 OO.ui.ComboBoxWidget.prototype.onInputChange = function ( value ) {
11813 var match = this.menu.getItemFromData( value );
11815 this.menu.selectItem( match );
11816 if ( this.menu.getHighlightedItem() ) {
11817 this.menu.highlightItem( match );
11820 if ( !this.isDisabled() ) {
11821 this.menu.toggle( true );
11826 * Handle mouse click events.
11828 * @param {jQuery.Event} e Mouse click event
11830 OO.ui.ComboBoxWidget.prototype.onClick = function ( e ) {
11831 if ( !this.isDisabled() && e.which === 1 ) {
11832 this.menu.toggle();
11833 this.input.$input[ 0 ].focus();
11835 return false;
11839 * Handle key press events.
11841 * @param {jQuery.Event} e Key press event
11843 OO.ui.ComboBoxWidget.prototype.onKeyPress = function ( e ) {
11844 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
11845 this.menu.toggle();
11846 this.input.$input[ 0 ].focus();
11848 return false;
11852 * Handle input enter events.
11854 OO.ui.ComboBoxWidget.prototype.onInputEnter = function () {
11855 if ( !this.isDisabled() ) {
11856 this.menu.toggle( false );
11861 * Handle menu choose events.
11863 * @param {OO.ui.OptionWidget} item Chosen item
11865 OO.ui.ComboBoxWidget.prototype.onMenuChoose = function ( item ) {
11866 if ( item ) {
11867 this.input.setValue( item.getData() );
11872 * Handle menu item change events.
11874 OO.ui.ComboBoxWidget.prototype.onMenuItemsChange = function () {
11875 var match = this.menu.getItemFromData( this.input.getValue() );
11876 this.menu.selectItem( match );
11877 if ( this.menu.getHighlightedItem() ) {
11878 this.menu.highlightItem( match );
11880 this.$element.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu.isEmpty() );
11884 * @inheritdoc
11886 OO.ui.ComboBoxWidget.prototype.setDisabled = function ( disabled ) {
11887 // Parent method
11888 OO.ui.ComboBoxWidget.super.prototype.setDisabled.call( this, disabled );
11890 if ( this.input ) {
11891 this.input.setDisabled( this.isDisabled() );
11893 if ( this.menu ) {
11894 this.menu.setDisabled( this.isDisabled() );
11897 return this;
11901 * Label widget.
11903 * @class
11904 * @extends OO.ui.Widget
11905 * @mixins OO.ui.LabelElement
11907 * @constructor
11908 * @param {Object} [config] Configuration options
11909 * @cfg {OO.ui.InputWidget} [input] Input widget this label is for
11911 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
11912 // Configuration initialization
11913 config = config || {};
11915 // Parent constructor
11916 OO.ui.LabelWidget.super.call( this, config );
11918 // Mixin constructors
11919 OO.ui.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
11920 OO.ui.TitledElement.call( this, config );
11922 // Properties
11923 this.input = config.input;
11925 // Events
11926 if ( this.input instanceof OO.ui.InputWidget ) {
11927 this.$element.on( 'click', this.onClick.bind( this ) );
11930 // Initialization
11931 this.$element.addClass( 'oo-ui-labelWidget' );
11934 /* Setup */
11936 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
11937 OO.mixinClass( OO.ui.LabelWidget, OO.ui.LabelElement );
11938 OO.mixinClass( OO.ui.LabelWidget, OO.ui.TitledElement );
11940 /* Static Properties */
11942 OO.ui.LabelWidget.static.tagName = 'span';
11944 /* Methods */
11947 * Handles label mouse click events.
11949 * @param {jQuery.Event} e Mouse click event
11951 OO.ui.LabelWidget.prototype.onClick = function () {
11952 this.input.simulateLabelClick();
11953 return false;
11957 * OptionWidgets are special elements that can be selected and configured with data. The
11958 * data is often unique for each option, but it does not have to be. OptionWidgets are used
11959 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
11960 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
11962 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
11964 * @class
11965 * @extends OO.ui.Widget
11966 * @mixins OO.ui.LabelElement
11967 * @mixins OO.ui.FlaggedElement
11969 * @constructor
11970 * @param {Object} [config] Configuration options
11972 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
11973 // Configuration initialization
11974 config = config || {};
11976 // Parent constructor
11977 OO.ui.OptionWidget.super.call( this, config );
11979 // Mixin constructors
11980 OO.ui.ItemWidget.call( this );
11981 OO.ui.LabelElement.call( this, config );
11982 OO.ui.FlaggedElement.call( this, config );
11984 // Properties
11985 this.selected = false;
11986 this.highlighted = false;
11987 this.pressed = false;
11989 // Initialization
11990 this.$element
11991 .data( 'oo-ui-optionWidget', this )
11992 .attr( 'role', 'option' )
11993 .addClass( 'oo-ui-optionWidget' )
11994 .append( this.$label );
11997 /* Setup */
11999 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
12000 OO.mixinClass( OO.ui.OptionWidget, OO.ui.ItemWidget );
12001 OO.mixinClass( OO.ui.OptionWidget, OO.ui.LabelElement );
12002 OO.mixinClass( OO.ui.OptionWidget, OO.ui.FlaggedElement );
12004 /* Static Properties */
12006 OO.ui.OptionWidget.static.selectable = true;
12008 OO.ui.OptionWidget.static.highlightable = true;
12010 OO.ui.OptionWidget.static.pressable = true;
12012 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
12014 /* Methods */
12017 * Check if the option can be selected.
12019 * @return {boolean} Item is selectable
12021 OO.ui.OptionWidget.prototype.isSelectable = function () {
12022 return this.constructor.static.selectable && !this.isDisabled();
12026 * Check if the option can be highlighted. A highlight indicates that the option
12027 * may be selected when a user presses enter or clicks. Disabled items cannot
12028 * be highlighted.
12030 * @return {boolean} Item is highlightable
12032 OO.ui.OptionWidget.prototype.isHighlightable = function () {
12033 return this.constructor.static.highlightable && !this.isDisabled();
12037 * Check if the option can be pressed. The pressed state occurs when a user mouses
12038 * down on an item, but has not yet let go of the mouse.
12040 * @return {boolean} Item is pressable
12042 OO.ui.OptionWidget.prototype.isPressable = function () {
12043 return this.constructor.static.pressable && !this.isDisabled();
12047 * Check if the option is selected.
12049 * @return {boolean} Item is selected
12051 OO.ui.OptionWidget.prototype.isSelected = function () {
12052 return this.selected;
12056 * Check if the option is highlighted. A highlight indicates that the
12057 * item may be selected when a user presses enter or clicks.
12059 * @return {boolean} Item is highlighted
12061 OO.ui.OptionWidget.prototype.isHighlighted = function () {
12062 return this.highlighted;
12066 * Check if the option is pressed. The pressed state occurs when a user mouses
12067 * down on an item, but has not yet let go of the mouse. The item may appear
12068 * selected, but it will not be selected until the user releases the mouse.
12070 * @return {boolean} Item is pressed
12072 OO.ui.OptionWidget.prototype.isPressed = function () {
12073 return this.pressed;
12077 * Set the option’s selected state. In general, all modifications to the selection
12078 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
12079 * method instead of this method.
12081 * @param {boolean} [state=false] Select option
12082 * @chainable
12084 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
12085 if ( this.constructor.static.selectable ) {
12086 this.selected = !!state;
12087 this.$element
12088 .toggleClass( 'oo-ui-optionWidget-selected', state )
12089 .attr( 'aria-selected', state.toString() );
12090 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
12091 this.scrollElementIntoView();
12093 this.updateThemeClasses();
12095 return this;
12099 * Set the option’s highlighted state. In general, all programmatic
12100 * modifications to the highlight should be handled by the
12101 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
12102 * method instead of this method.
12104 * @param {boolean} [state=false] Highlight option
12105 * @chainable
12107 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
12108 if ( this.constructor.static.highlightable ) {
12109 this.highlighted = !!state;
12110 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
12111 this.updateThemeClasses();
12113 return this;
12117 * Set the option’s pressed state. In general, all
12118 * programmatic modifications to the pressed state should be handled by the
12119 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
12120 * method instead of this method.
12122 * @param {boolean} [state=false] Press option
12123 * @chainable
12125 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
12126 if ( this.constructor.static.pressable ) {
12127 this.pressed = !!state;
12128 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
12129 this.updateThemeClasses();
12131 return this;
12135 * Option widget with an option icon and indicator.
12137 * Use together with OO.ui.SelectWidget.
12139 * @class
12140 * @extends OO.ui.OptionWidget
12141 * @mixins OO.ui.IconElement
12142 * @mixins OO.ui.IndicatorElement
12144 * @constructor
12145 * @param {Object} [config] Configuration options
12147 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
12148 // Parent constructor
12149 OO.ui.DecoratedOptionWidget.super.call( this, config );
12151 // Mixin constructors
12152 OO.ui.IconElement.call( this, config );
12153 OO.ui.IndicatorElement.call( this, config );
12155 // Initialization
12156 this.$element
12157 .addClass( 'oo-ui-decoratedOptionWidget' )
12158 .prepend( this.$icon )
12159 .append( this.$indicator );
12162 /* Setup */
12164 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
12165 OO.mixinClass( OO.ui.OptionWidget, OO.ui.IconElement );
12166 OO.mixinClass( OO.ui.OptionWidget, OO.ui.IndicatorElement );
12169 * ButtonOptionWidget is a special type of {@link OO.ui.ButtonElement button element} that
12170 * can be selected and configured with data. The class is
12171 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
12172 * [OOjs UI documentation on MediaWiki] [1] for more information.
12174 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
12176 * @class
12177 * @extends OO.ui.DecoratedOptionWidget
12178 * @mixins OO.ui.ButtonElement
12179 * @mixins OO.ui.TabIndexedElement
12181 * @constructor
12182 * @param {Object} [config] Configuration options
12184 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) {
12185 // Configuration initialization
12186 config = $.extend( { tabIndex: -1 }, config );
12188 // Parent constructor
12189 OO.ui.ButtonOptionWidget.super.call( this, config );
12191 // Mixin constructors
12192 OO.ui.ButtonElement.call( this, config );
12193 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
12195 // Initialization
12196 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
12197 this.$button.append( this.$element.contents() );
12198 this.$element.append( this.$button );
12201 /* Setup */
12203 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.DecoratedOptionWidget );
12204 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.ButtonElement );
12205 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.TabIndexedElement );
12207 /* Static Properties */
12209 // Allow button mouse down events to pass through so they can be handled by the parent select widget
12210 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
12212 OO.ui.ButtonOptionWidget.static.highlightable = false;
12214 /* Methods */
12217 * @inheritdoc
12219 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
12220 OO.ui.ButtonOptionWidget.super.prototype.setSelected.call( this, state );
12222 if ( this.constructor.static.selectable ) {
12223 this.setActive( state );
12226 return this;
12230 * RadioOptionWidget is an option widget that looks like a radio button.
12231 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
12232 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
12234 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
12236 * @class
12237 * @extends OO.ui.OptionWidget
12239 * @constructor
12240 * @param {Object} [config] Configuration options
12242 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
12243 // Configuration initialization
12244 config = config || {};
12246 // Properties (must be done before parent constructor which calls #setDisabled)
12247 this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
12249 // Parent constructor
12250 OO.ui.RadioOptionWidget.super.call( this, config );
12252 // Initialization
12253 this.$element
12254 .addClass( 'oo-ui-radioOptionWidget' )
12255 .prepend( this.radio.$element );
12258 /* Setup */
12260 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
12262 /* Static Properties */
12264 OO.ui.RadioOptionWidget.static.highlightable = false;
12266 OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
12268 OO.ui.RadioOptionWidget.static.pressable = false;
12270 OO.ui.RadioOptionWidget.static.tagName = 'label';
12272 /* Methods */
12275 * @inheritdoc
12277 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
12278 OO.ui.RadioOptionWidget.super.prototype.setSelected.call( this, state );
12280 this.radio.setSelected( state );
12282 return this;
12286 * @inheritdoc
12288 OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
12289 OO.ui.RadioOptionWidget.super.prototype.setDisabled.call( this, disabled );
12291 this.radio.setDisabled( this.isDisabled() );
12293 return this;
12297 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
12298 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
12299 * the [OOjs UI documentation on MediaWiki] [1] for more information.
12301 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
12303 * @class
12304 * @extends OO.ui.DecoratedOptionWidget
12306 * @constructor
12307 * @param {Object} [config] Configuration options
12309 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
12310 // Configuration initialization
12311 config = $.extend( { icon: 'check' }, config );
12313 // Parent constructor
12314 OO.ui.MenuOptionWidget.super.call( this, config );
12316 // Initialization
12317 this.$element
12318 .attr( 'role', 'menuitem' )
12319 .addClass( 'oo-ui-menuOptionWidget' );
12322 /* Setup */
12324 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
12326 /* Static Properties */
12328 OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true;
12331 * Section to group one or more items in a OO.ui.MenuSelectWidget.
12333 * @class
12334 * @extends OO.ui.DecoratedOptionWidget
12336 * @constructor
12337 * @param {Object} [config] Configuration options
12339 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
12340 // Parent constructor
12341 OO.ui.MenuSectionOptionWidget.super.call( this, config );
12343 // Initialization
12344 this.$element.addClass( 'oo-ui-menuSectionOptionWidget' );
12347 /* Setup */
12349 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
12351 /* Static Properties */
12353 OO.ui.MenuSectionOptionWidget.static.selectable = false;
12355 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
12358 * Items for an OO.ui.OutlineSelectWidget.
12360 * @class
12361 * @extends OO.ui.DecoratedOptionWidget
12363 * @constructor
12364 * @param {Object} [config] Configuration options
12365 * @cfg {number} [level] Indentation level
12366 * @cfg {boolean} [movable] Allow modification from outline controls
12368 OO.ui.OutlineOptionWidget = function OoUiOutlineOptionWidget( config ) {
12369 // Configuration initialization
12370 config = config || {};
12372 // Parent constructor
12373 OO.ui.OutlineOptionWidget.super.call( this, config );
12375 // Properties
12376 this.level = 0;
12377 this.movable = !!config.movable;
12378 this.removable = !!config.removable;
12380 // Initialization
12381 this.$element.addClass( 'oo-ui-outlineOptionWidget' );
12382 this.setLevel( config.level );
12385 /* Setup */
12387 OO.inheritClass( OO.ui.OutlineOptionWidget, OO.ui.DecoratedOptionWidget );
12389 /* Static Properties */
12391 OO.ui.OutlineOptionWidget.static.highlightable = false;
12393 OO.ui.OutlineOptionWidget.static.scrollIntoViewOnSelect = true;
12395 OO.ui.OutlineOptionWidget.static.levelClass = 'oo-ui-outlineOptionWidget-level-';
12397 OO.ui.OutlineOptionWidget.static.levels = 3;
12399 /* Methods */
12402 * Check if item is movable.
12404 * Movability is used by outline controls.
12406 * @return {boolean} Item is movable
12408 OO.ui.OutlineOptionWidget.prototype.isMovable = function () {
12409 return this.movable;
12413 * Check if item is removable.
12415 * Removability is used by outline controls.
12417 * @return {boolean} Item is removable
12419 OO.ui.OutlineOptionWidget.prototype.isRemovable = function () {
12420 return this.removable;
12424 * Get indentation level.
12426 * @return {number} Indentation level
12428 OO.ui.OutlineOptionWidget.prototype.getLevel = function () {
12429 return this.level;
12433 * Set movability.
12435 * Movability is used by outline controls.
12437 * @param {boolean} movable Item is movable
12438 * @chainable
12440 OO.ui.OutlineOptionWidget.prototype.setMovable = function ( movable ) {
12441 this.movable = !!movable;
12442 this.updateThemeClasses();
12443 return this;
12447 * Set removability.
12449 * Removability is used by outline controls.
12451 * @param {boolean} movable Item is removable
12452 * @chainable
12454 OO.ui.OutlineOptionWidget.prototype.setRemovable = function ( removable ) {
12455 this.removable = !!removable;
12456 this.updateThemeClasses();
12457 return this;
12461 * Set indentation level.
12463 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
12464 * @chainable
12466 OO.ui.OutlineOptionWidget.prototype.setLevel = function ( level ) {
12467 var levels = this.constructor.static.levels,
12468 levelClass = this.constructor.static.levelClass,
12469 i = levels;
12471 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
12472 while ( i-- ) {
12473 if ( this.level === i ) {
12474 this.$element.addClass( levelClass + i );
12475 } else {
12476 this.$element.removeClass( levelClass + i );
12479 this.updateThemeClasses();
12481 return this;
12485 * Container for content that is overlaid and positioned absolutely.
12487 * @class
12488 * @extends OO.ui.Widget
12489 * @mixins OO.ui.LabelElement
12491 * @constructor
12492 * @param {Object} [config] Configuration options
12493 * @cfg {number} [width=320] Width of popup in pixels
12494 * @cfg {number} [height] Height of popup, omit to use automatic height
12495 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
12496 * @cfg {string} [align='center'] Alignment of popup to origin
12497 * @cfg {jQuery} [$container] Container to prevent popup from rendering outside of
12498 * @cfg {number} [containerPadding=10] How much padding to keep between popup and container
12499 * @cfg {jQuery} [$content] Content to append to the popup's body
12500 * @cfg {boolean} [autoClose=false] Popup auto-closes when it loses focus
12501 * @cfg {jQuery} [$autoCloseIgnore] Elements to not auto close when clicked
12502 * @cfg {boolean} [head] Show label and close button at the top
12503 * @cfg {boolean} [padded] Add padding to the body
12505 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
12506 // Configuration initialization
12507 config = config || {};
12509 // Parent constructor
12510 OO.ui.PopupWidget.super.call( this, config );
12512 // Properties (must be set before ClippableElement constructor call)
12513 this.$body = $( '<div>' );
12515 // Mixin constructors
12516 OO.ui.LabelElement.call( this, config );
12517 OO.ui.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$body } ) );
12519 // Properties
12520 this.$popup = $( '<div>' );
12521 this.$head = $( '<div>' );
12522 this.$anchor = $( '<div>' );
12523 // If undefined, will be computed lazily in updateDimensions()
12524 this.$container = config.$container;
12525 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
12526 this.autoClose = !!config.autoClose;
12527 this.$autoCloseIgnore = config.$autoCloseIgnore;
12528 this.transitionTimeout = null;
12529 this.anchor = null;
12530 this.width = config.width !== undefined ? config.width : 320;
12531 this.height = config.height !== undefined ? config.height : null;
12532 this.align = config.align || 'center';
12533 this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } );
12534 this.onMouseDownHandler = this.onMouseDown.bind( this );
12536 // Events
12537 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
12539 // Initialization
12540 this.toggleAnchor( config.anchor === undefined || config.anchor );
12541 this.$body.addClass( 'oo-ui-popupWidget-body' );
12542 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
12543 this.$head
12544 .addClass( 'oo-ui-popupWidget-head' )
12545 .append( this.$label, this.closeButton.$element );
12546 if ( !config.head ) {
12547 this.$head.addClass( 'oo-ui-element-hidden' );
12549 this.$popup
12550 .addClass( 'oo-ui-popupWidget-popup' )
12551 .append( this.$head, this.$body );
12552 this.$element
12553 .addClass( 'oo-ui-popupWidget' )
12554 .append( this.$popup, this.$anchor );
12555 // Move content, which was added to #$element by OO.ui.Widget, to the body
12556 if ( config.$content instanceof jQuery ) {
12557 this.$body.append( config.$content );
12559 if ( config.padded ) {
12560 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
12563 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
12564 // that reference properties not initialized at that time of parent class construction
12565 // TODO: Find a better way to handle post-constructor setup
12566 this.visible = false;
12567 this.$element.addClass( 'oo-ui-element-hidden' );
12570 /* Setup */
12572 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
12573 OO.mixinClass( OO.ui.PopupWidget, OO.ui.LabelElement );
12574 OO.mixinClass( OO.ui.PopupWidget, OO.ui.ClippableElement );
12576 /* Methods */
12579 * Handles mouse down events.
12581 * @param {jQuery.Event} e Mouse down event
12583 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
12584 if (
12585 this.isVisible() &&
12586 !$.contains( this.$element[ 0 ], e.target ) &&
12587 ( !this.$autoCloseIgnore || !this.$autoCloseIgnore.has( e.target ).length )
12589 this.toggle( false );
12594 * Bind mouse down listener.
12596 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
12597 // Capture clicks outside popup
12598 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler, true );
12602 * Handles close button click events.
12604 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
12605 if ( this.isVisible() ) {
12606 this.toggle( false );
12611 * Unbind mouse down listener.
12613 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
12614 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler, true );
12618 * Set whether to show a anchor.
12620 * @param {boolean} [show] Show anchor, omit to toggle
12622 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
12623 show = show === undefined ? !this.anchored : !!show;
12625 if ( this.anchored !== show ) {
12626 if ( show ) {
12627 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
12628 } else {
12629 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
12631 this.anchored = show;
12636 * Check if showing a anchor.
12638 * @return {boolean} anchor is visible
12640 OO.ui.PopupWidget.prototype.hasAnchor = function () {
12641 return this.anchor;
12645 * @inheritdoc
12647 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
12648 show = show === undefined ? !this.isVisible() : !!show;
12650 var change = show !== this.isVisible();
12652 // Parent method
12653 OO.ui.PopupWidget.super.prototype.toggle.call( this, show );
12655 if ( change ) {
12656 if ( show ) {
12657 if ( this.autoClose ) {
12658 this.bindMouseDownListener();
12660 this.updateDimensions();
12661 this.toggleClipping( true );
12662 } else {
12663 this.toggleClipping( false );
12664 if ( this.autoClose ) {
12665 this.unbindMouseDownListener();
12670 return this;
12674 * Set the size of the popup.
12676 * Changing the size may also change the popup's position depending on the alignment.
12678 * @param {number} width Width
12679 * @param {number} height Height
12680 * @param {boolean} [transition=false] Use a smooth transition
12681 * @chainable
12683 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
12684 this.width = width;
12685 this.height = height !== undefined ? height : null;
12686 if ( this.isVisible() ) {
12687 this.updateDimensions( transition );
12692 * Update the size and position.
12694 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
12695 * be called automatically.
12697 * @param {boolean} [transition=false] Use a smooth transition
12698 * @chainable
12700 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
12701 var popupOffset, originOffset, containerLeft, containerWidth, containerRight,
12702 popupLeft, popupRight, overlapLeft, overlapRight, anchorWidth,
12703 widget = this;
12705 if ( !this.$container ) {
12706 // Lazy-initialize $container if not specified in constructor
12707 this.$container = $( this.getClosestScrollableElementContainer() );
12710 // Set height and width before measuring things, since it might cause our measurements
12711 // to change (e.g. due to scrollbars appearing or disappearing)
12712 this.$popup.css( {
12713 width: this.width,
12714 height: this.height !== null ? this.height : 'auto'
12715 } );
12717 // Compute initial popupOffset based on alignment
12718 popupOffset = this.width * ( { left: 0, center: -0.5, right: -1 } )[ this.align ];
12720 // Figure out if this will cause the popup to go beyond the edge of the container
12721 originOffset = this.$element.offset().left;
12722 containerLeft = this.$container.offset().left;
12723 containerWidth = this.$container.innerWidth();
12724 containerRight = containerLeft + containerWidth;
12725 popupLeft = popupOffset - this.containerPadding;
12726 popupRight = popupOffset + this.containerPadding + this.width + this.containerPadding;
12727 overlapLeft = ( originOffset + popupLeft ) - containerLeft;
12728 overlapRight = containerRight - ( originOffset + popupRight );
12730 // Adjust offset to make the popup not go beyond the edge, if needed
12731 if ( overlapRight < 0 ) {
12732 popupOffset += overlapRight;
12733 } else if ( overlapLeft < 0 ) {
12734 popupOffset -= overlapLeft;
12737 // Adjust offset to avoid anchor being rendered too close to the edge
12738 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
12739 // TODO: Find a measurement that works for CSS anchors and image anchors
12740 anchorWidth = this.$anchor[ 0 ].scrollWidth * 2;
12741 if ( popupOffset + this.width < anchorWidth ) {
12742 popupOffset = anchorWidth - this.width;
12743 } else if ( -popupOffset < anchorWidth ) {
12744 popupOffset = -anchorWidth;
12747 // Prevent transition from being interrupted
12748 clearTimeout( this.transitionTimeout );
12749 if ( transition ) {
12750 // Enable transition
12751 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
12754 // Position body relative to anchor
12755 this.$popup.css( 'margin-left', popupOffset );
12757 if ( transition ) {
12758 // Prevent transitioning after transition is complete
12759 this.transitionTimeout = setTimeout( function () {
12760 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
12761 }, 200 );
12762 } else {
12763 // Prevent transitioning immediately
12764 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
12767 // Reevaluate clipping state since we've relocated and resized the popup
12768 this.clip();
12770 return this;
12774 * Progress bar widget.
12776 * @class
12777 * @extends OO.ui.Widget
12779 * @constructor
12780 * @param {Object} [config] Configuration options
12781 * @cfg {number|boolean} [progress=false] Initial progress percent or false for indeterminate
12783 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
12784 // Configuration initialization
12785 config = config || {};
12787 // Parent constructor
12788 OO.ui.ProgressBarWidget.super.call( this, config );
12790 // Properties
12791 this.$bar = $( '<div>' );
12792 this.progress = null;
12794 // Initialization
12795 this.setProgress( config.progress !== undefined ? config.progress : false );
12796 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
12797 this.$element
12798 .attr( {
12799 role: 'progressbar',
12800 'aria-valuemin': 0,
12801 'aria-valuemax': 100
12803 .addClass( 'oo-ui-progressBarWidget' )
12804 .append( this.$bar );
12807 /* Setup */
12809 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
12811 /* Static Properties */
12813 OO.ui.ProgressBarWidget.static.tagName = 'div';
12815 /* Methods */
12818 * Get progress percent
12820 * @return {number} Progress percent
12822 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
12823 return this.progress;
12827 * Set progress percent
12829 * @param {number|boolean} progress Progress percent or false for indeterminate
12831 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
12832 this.progress = progress;
12834 if ( progress !== false ) {
12835 this.$bar.css( 'width', this.progress + '%' );
12836 this.$element.attr( 'aria-valuenow', this.progress );
12837 } else {
12838 this.$bar.css( 'width', '' );
12839 this.$element.removeAttr( 'aria-valuenow' );
12841 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress );
12845 * Search widget.
12847 * Search widgets combine a query input, placed above, and a results selection widget, placed below.
12848 * Results are cleared and populated each time the query is changed.
12850 * @class
12851 * @extends OO.ui.Widget
12853 * @constructor
12854 * @param {Object} [config] Configuration options
12855 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
12856 * @cfg {string} [value] Initial query value
12858 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
12859 // Configuration initialization
12860 config = config || {};
12862 // Parent constructor
12863 OO.ui.SearchWidget.super.call( this, config );
12865 // Properties
12866 this.query = new OO.ui.TextInputWidget( {
12867 icon: 'search',
12868 placeholder: config.placeholder,
12869 value: config.value
12870 } );
12871 this.results = new OO.ui.SelectWidget();
12872 this.$query = $( '<div>' );
12873 this.$results = $( '<div>' );
12875 // Events
12876 this.query.connect( this, {
12877 change: 'onQueryChange',
12878 enter: 'onQueryEnter'
12879 } );
12880 this.results.connect( this, {
12881 highlight: 'onResultsHighlight',
12882 select: 'onResultsSelect'
12883 } );
12884 this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) );
12886 // Initialization
12887 this.$query
12888 .addClass( 'oo-ui-searchWidget-query' )
12889 .append( this.query.$element );
12890 this.$results
12891 .addClass( 'oo-ui-searchWidget-results' )
12892 .append( this.results.$element );
12893 this.$element
12894 .addClass( 'oo-ui-searchWidget' )
12895 .append( this.$results, this.$query );
12898 /* Setup */
12900 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
12902 /* Events */
12905 * @event highlight
12906 * @param {Object|null} item Item data or null if no item is highlighted
12910 * @event select
12911 * @param {Object|null} item Item data or null if no item is selected
12914 /* Methods */
12917 * Handle query key down events.
12919 * @param {jQuery.Event} e Key down event
12921 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
12922 var highlightedItem, nextItem,
12923 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
12925 if ( dir ) {
12926 highlightedItem = this.results.getHighlightedItem();
12927 if ( !highlightedItem ) {
12928 highlightedItem = this.results.getSelectedItem();
12930 nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir );
12931 this.results.highlightItem( nextItem );
12932 nextItem.scrollElementIntoView();
12937 * Handle select widget select events.
12939 * Clears existing results. Subclasses should repopulate items according to new query.
12941 * @param {string} value New value
12943 OO.ui.SearchWidget.prototype.onQueryChange = function () {
12944 // Reset
12945 this.results.clearItems();
12949 * Handle select widget enter key events.
12951 * Selects highlighted item.
12953 * @param {string} value New value
12955 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
12956 // Reset
12957 this.results.selectItem( this.results.getHighlightedItem() );
12961 * Handle select widget highlight events.
12963 * @param {OO.ui.OptionWidget} item Highlighted item
12964 * @fires highlight
12966 OO.ui.SearchWidget.prototype.onResultsHighlight = function ( item ) {
12967 this.emit( 'highlight', item ? item.getData() : null );
12971 * Handle select widget select events.
12973 * @param {OO.ui.OptionWidget} item Selected item
12974 * @fires select
12976 OO.ui.SearchWidget.prototype.onResultsSelect = function ( item ) {
12977 this.emit( 'select', item ? item.getData() : null );
12981 * Get the query input.
12983 * @return {OO.ui.TextInputWidget} Query input
12985 OO.ui.SearchWidget.prototype.getQuery = function () {
12986 return this.query;
12990 * Get the results list.
12992 * @return {OO.ui.SelectWidget} Select list
12994 OO.ui.SearchWidget.prototype.getResults = function () {
12995 return this.results;
12999 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
13000 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
13001 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
13002 * menu selects}.
13004 * This class should be used together with OO.ui.OptionWidget.
13006 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
13008 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
13010 * @class
13011 * @extends OO.ui.Widget
13012 * @mixins OO.ui.GroupElement
13014 * @constructor
13015 * @param {Object} [config] Configuration options
13016 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
13017 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
13018 * the [OOjs UI documentation on MediaWiki] [2] for examples.
13019 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
13021 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
13022 // Configuration initialization
13023 config = config || {};
13025 // Parent constructor
13026 OO.ui.SelectWidget.super.call( this, config );
13028 // Mixin constructors
13029 OO.ui.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
13031 // Properties
13032 this.pressed = false;
13033 this.selecting = null;
13034 this.onMouseUpHandler = this.onMouseUp.bind( this );
13035 this.onMouseMoveHandler = this.onMouseMove.bind( this );
13036 this.onKeyDownHandler = this.onKeyDown.bind( this );
13038 // Events
13039 this.$element.on( {
13040 mousedown: this.onMouseDown.bind( this ),
13041 mouseover: this.onMouseOver.bind( this ),
13042 mouseleave: this.onMouseLeave.bind( this )
13043 } );
13045 // Initialization
13046 this.$element
13047 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
13048 .attr( 'role', 'listbox' );
13049 if ( Array.isArray( config.items ) ) {
13050 this.addItems( config.items );
13054 /* Setup */
13056 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
13058 // Need to mixin base class as well
13059 OO.mixinClass( OO.ui.SelectWidget, OO.ui.GroupElement );
13060 OO.mixinClass( OO.ui.SelectWidget, OO.ui.GroupWidget );
13062 /* Events */
13065 * @event highlight
13067 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
13069 * @param {OO.ui.OptionWidget|null} item Highlighted item
13073 * @event press
13075 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
13076 * pressed state of an option.
13078 * @param {OO.ui.OptionWidget|null} item Pressed item
13082 * @event select
13084 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
13086 * @param {OO.ui.OptionWidget|null} item Selected item
13090 * @event choose
13091 * @param {OO.ui.OptionWidget|null} item Chosen item
13095 * @event add
13097 * An `add` event is emitted when options are added to the select with the #addItems method.
13099 * @param {OO.ui.OptionWidget[]} items Added items
13100 * @param {number} index Index of insertion point
13104 * @event remove
13106 * A `remove` event is emitted when options are removed from the select with the #clearItems
13107 * or #removeItems methods.
13109 * @param {OO.ui.OptionWidget[]} items Removed items
13112 /* Methods */
13115 * Handle mouse down events.
13117 * @private
13118 * @param {jQuery.Event} e Mouse down event
13120 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
13121 var item;
13123 if ( !this.isDisabled() && e.which === 1 ) {
13124 this.togglePressed( true );
13125 item = this.getTargetItem( e );
13126 if ( item && item.isSelectable() ) {
13127 this.pressItem( item );
13128 this.selecting = item;
13129 this.getElementDocument().addEventListener(
13130 'mouseup',
13131 this.onMouseUpHandler,
13132 true
13134 this.getElementDocument().addEventListener(
13135 'mousemove',
13136 this.onMouseMoveHandler,
13137 true
13141 return false;
13145 * Handle mouse up events.
13147 * @private
13148 * @param {jQuery.Event} e Mouse up event
13150 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
13151 var item;
13153 this.togglePressed( false );
13154 if ( !this.selecting ) {
13155 item = this.getTargetItem( e );
13156 if ( item && item.isSelectable() ) {
13157 this.selecting = item;
13160 if ( !this.isDisabled() && e.which === 1 && this.selecting ) {
13161 this.pressItem( null );
13162 this.chooseItem( this.selecting );
13163 this.selecting = null;
13166 this.getElementDocument().removeEventListener(
13167 'mouseup',
13168 this.onMouseUpHandler,
13169 true
13171 this.getElementDocument().removeEventListener(
13172 'mousemove',
13173 this.onMouseMoveHandler,
13174 true
13177 return false;
13181 * Handle mouse move events.
13183 * @private
13184 * @param {jQuery.Event} e Mouse move event
13186 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
13187 var item;
13189 if ( !this.isDisabled() && this.pressed ) {
13190 item = this.getTargetItem( e );
13191 if ( item && item !== this.selecting && item.isSelectable() ) {
13192 this.pressItem( item );
13193 this.selecting = item;
13196 return false;
13200 * Handle mouse over events.
13202 * @private
13203 * @param {jQuery.Event} e Mouse over event
13205 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
13206 var item;
13208 if ( !this.isDisabled() ) {
13209 item = this.getTargetItem( e );
13210 this.highlightItem( item && item.isHighlightable() ? item : null );
13212 return false;
13216 * Handle mouse leave events.
13218 * @private
13219 * @param {jQuery.Event} e Mouse over event
13221 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
13222 if ( !this.isDisabled() ) {
13223 this.highlightItem( null );
13225 return false;
13229 * Handle key down events.
13231 * @protected
13232 * @param {jQuery.Event} e Key down event
13234 OO.ui.SelectWidget.prototype.onKeyDown = function ( e ) {
13235 var nextItem,
13236 handled = false,
13237 currentItem = this.getHighlightedItem() || this.getSelectedItem();
13239 if ( !this.isDisabled() && this.isVisible() ) {
13240 switch ( e.keyCode ) {
13241 case OO.ui.Keys.ENTER:
13242 if ( currentItem && currentItem.constructor.static.highlightable ) {
13243 // Was only highlighted, now let's select it. No-op if already selected.
13244 this.chooseItem( currentItem );
13245 handled = true;
13247 break;
13248 case OO.ui.Keys.UP:
13249 case OO.ui.Keys.LEFT:
13250 nextItem = this.getRelativeSelectableItem( currentItem, -1 );
13251 handled = true;
13252 break;
13253 case OO.ui.Keys.DOWN:
13254 case OO.ui.Keys.RIGHT:
13255 nextItem = this.getRelativeSelectableItem( currentItem, 1 );
13256 handled = true;
13257 break;
13258 case OO.ui.Keys.ESCAPE:
13259 case OO.ui.Keys.TAB:
13260 if ( currentItem && currentItem.constructor.static.highlightable ) {
13261 currentItem.setHighlighted( false );
13263 this.unbindKeyDownListener();
13264 // Don't prevent tabbing away / defocusing
13265 handled = false;
13266 break;
13269 if ( nextItem ) {
13270 if ( nextItem.constructor.static.highlightable ) {
13271 this.highlightItem( nextItem );
13272 } else {
13273 this.chooseItem( nextItem );
13275 nextItem.scrollElementIntoView();
13278 if ( handled ) {
13279 // Can't just return false, because e is not always a jQuery event
13280 e.preventDefault();
13281 e.stopPropagation();
13287 * Bind key down listener.
13289 OO.ui.SelectWidget.prototype.bindKeyDownListener = function () {
13290 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler, true );
13294 * Unbind key down listener.
13296 OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () {
13297 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler, true );
13301 * Get the closest item to a jQuery.Event.
13303 * @private
13304 * @param {jQuery.Event} e
13305 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
13307 OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) {
13308 var $item = $( e.target ).closest( '.oo-ui-optionWidget' );
13309 if ( $item.length ) {
13310 return $item.data( 'oo-ui-optionWidget' );
13312 return null;
13316 * Get selected item.
13318 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
13320 OO.ui.SelectWidget.prototype.getSelectedItem = function () {
13321 var i, len;
13323 for ( i = 0, len = this.items.length; i < len; i++ ) {
13324 if ( this.items[ i ].isSelected() ) {
13325 return this.items[ i ];
13328 return null;
13332 * Get highlighted item.
13334 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
13336 OO.ui.SelectWidget.prototype.getHighlightedItem = function () {
13337 var i, len;
13339 for ( i = 0, len = this.items.length; i < len; i++ ) {
13340 if ( this.items[ i ].isHighlighted() ) {
13341 return this.items[ i ];
13344 return null;
13348 * Toggle pressed state.
13350 * @param {boolean} pressed An option is being pressed
13352 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
13353 if ( pressed === undefined ) {
13354 pressed = !this.pressed;
13356 if ( pressed !== this.pressed ) {
13357 this.$element
13358 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
13359 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
13360 this.pressed = pressed;
13365 * Highlight an option. If the `item` param is omitted, no options will be highlighted
13366 * and any existing highlight will be removed. The highlight is mutually exclusive.
13368 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
13369 * @fires highlight
13370 * @chainable
13372 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
13373 var i, len, highlighted,
13374 changed = false;
13376 for ( i = 0, len = this.items.length; i < len; i++ ) {
13377 highlighted = this.items[ i ] === item;
13378 if ( this.items[ i ].isHighlighted() !== highlighted ) {
13379 this.items[ i ].setHighlighted( highlighted );
13380 changed = true;
13383 if ( changed ) {
13384 this.emit( 'highlight', item );
13387 return this;
13391 * Programmatically select an option by its reference. If the `item` parameter is omitted,
13392 * all options will be deselected.
13394 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
13395 * @fires select
13396 * @chainable
13398 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
13399 var i, len, selected,
13400 changed = false;
13402 for ( i = 0, len = this.items.length; i < len; i++ ) {
13403 selected = this.items[ i ] === item;
13404 if ( this.items[ i ].isSelected() !== selected ) {
13405 this.items[ i ].setSelected( selected );
13406 changed = true;
13409 if ( changed ) {
13410 this.emit( 'select', item );
13413 return this;
13417 * Press an item.
13419 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
13420 * @fires press
13421 * @chainable
13423 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
13424 var i, len, pressed,
13425 changed = false;
13427 for ( i = 0, len = this.items.length; i < len; i++ ) {
13428 pressed = this.items[ i ] === item;
13429 if ( this.items[ i ].isPressed() !== pressed ) {
13430 this.items[ i ].setPressed( pressed );
13431 changed = true;
13434 if ( changed ) {
13435 this.emit( 'press', item );
13438 return this;
13442 * Choose an item.
13444 * Identical to #selectItem, but may vary in subclasses that want to take additional action when
13445 * an item is selected using the keyboard or mouse.
13447 * @param {OO.ui.OptionWidget} item Item to choose
13448 * @fires choose
13449 * @chainable
13451 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
13452 this.selectItem( item );
13453 this.emit( 'choose', item );
13455 return this;
13459 * Get an option by its position relative to the specified item (or to the start of the option array,
13460 * if item is `null`). The direction in which to search through the option array is specified with a
13461 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
13462 * `null` if there are no options in the array.
13464 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
13465 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
13466 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
13468 OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction ) {
13469 var currentIndex, nextIndex, i,
13470 increase = direction > 0 ? 1 : -1,
13471 len = this.items.length;
13473 if ( item instanceof OO.ui.OptionWidget ) {
13474 currentIndex = $.inArray( item, this.items );
13475 nextIndex = ( currentIndex + increase + len ) % len;
13476 } else {
13477 // If no item is selected and moving forward, start at the beginning.
13478 // If moving backward, start at the end.
13479 nextIndex = direction > 0 ? 0 : len - 1;
13482 for ( i = 0; i < len; i++ ) {
13483 item = this.items[ nextIndex ];
13484 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
13485 return item;
13487 nextIndex = ( nextIndex + increase + len ) % len;
13489 return null;
13493 * Get the next selectable item or `null` if there are no selectable items.
13494 * Disabled options and menu-section markers and breaks are not selectable.
13496 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
13498 OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () {
13499 var i, len, item;
13501 for ( i = 0, len = this.items.length; i < len; i++ ) {
13502 item = this.items[ i ];
13503 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
13504 return item;
13508 return null;
13512 * Add an array of options to the select. Optionally, an index number can be used to
13513 * specify an insertion point.
13515 * @param {OO.ui.OptionWidget[]} items Items to add
13516 * @param {number} [index] Index to insert items after
13517 * @fires add
13518 * @chainable
13520 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
13521 // Mixin method
13522 OO.ui.GroupWidget.prototype.addItems.call( this, items, index );
13524 // Always provide an index, even if it was omitted
13525 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
13527 return this;
13531 * Remove the specified array of options from the select. Options will be detached
13532 * from the DOM, not removed, so they can be reused later. To remove all options from
13533 * the select, you may wish to use the #clearItems method instead.
13535 * @param {OO.ui.OptionWidget[]} items Items to remove
13536 * @fires remove
13537 * @chainable
13539 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
13540 var i, len, item;
13542 // Deselect items being removed
13543 for ( i = 0, len = items.length; i < len; i++ ) {
13544 item = items[ i ];
13545 if ( item.isSelected() ) {
13546 this.selectItem( null );
13550 // Mixin method
13551 OO.ui.GroupWidget.prototype.removeItems.call( this, items );
13553 this.emit( 'remove', items );
13555 return this;
13559 * Clear all options from the select. Options will be detached from the DOM, not removed,
13560 * so that they can be reused later. To remove a subset of options from the select, use
13561 * the #removeItems method.
13563 * @fires remove
13564 * @chainable
13566 OO.ui.SelectWidget.prototype.clearItems = function () {
13567 var items = this.items.slice();
13569 // Mixin method
13570 OO.ui.GroupWidget.prototype.clearItems.call( this );
13572 // Clear selection
13573 this.selectItem( null );
13575 this.emit( 'remove', items );
13577 return this;
13581 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
13582 * button options and is used together with
13583 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
13584 * highlighting, choosing, and selecting mutually exclusive options. Please see
13585 * the [OOjs UI documentation on MediaWiki] [1] for more information.
13587 * @example
13588 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
13589 * var option1 = new OO.ui.ButtonOptionWidget( {
13590 * data: 1,
13591 * label: 'Option 1',
13592 * title:'Button option 1'
13593 * } );
13595 * var option2 = new OO.ui.ButtonOptionWidget( {
13596 * data: 2,
13597 * label: 'Option 2',
13598 * title:'Button option 2'
13599 * } );
13601 * var option3 = new OO.ui.ButtonOptionWidget( {
13602 * data: 3,
13603 * label: 'Option 3',
13604 * title:'Button option 3'
13605 * } );
13607 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
13608 * items: [option1, option2, option3]
13609 * } );
13610 * $('body').append(buttonSelect.$element);
13612 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
13614 * @class
13615 * @extends OO.ui.SelectWidget
13616 * @mixins OO.ui.TabIndexedElement
13618 * @constructor
13619 * @param {Object} [config] Configuration options
13621 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
13622 // Parent constructor
13623 OO.ui.ButtonSelectWidget.super.call( this, config );
13625 // Mixin constructors
13626 OO.ui.TabIndexedElement.call( this, config );
13628 // Events
13629 this.$element.on( {
13630 focus: this.bindKeyDownListener.bind( this ),
13631 blur: this.unbindKeyDownListener.bind( this )
13632 } );
13634 // Initialization
13635 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
13638 /* Setup */
13640 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
13641 OO.mixinClass( OO.ui.ButtonSelectWidget, OO.ui.TabIndexedElement );
13644 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
13645 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
13646 * an interface for adding, removing and selecting options.
13647 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
13649 * @example
13650 * // A RadioSelectWidget with RadioOptions.
13651 * var option1 = new OO.ui.RadioOptionWidget( {
13652 * data: 'a',
13653 * label: 'Selected radio option'
13654 * } );
13656 * var option2 = new OO.ui.RadioOptionWidget( {
13657 * data: 'b',
13658 * label: 'Unselected radio option'
13659 * } );
13661 * var radioSelect=new OO.ui.RadioSelectWidget( {
13662 * items: [option1, option2]
13663 * } );
13665 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
13666 * radioSelect.selectItem( option1 );
13668 * $('body').append(radioSelect.$element);
13670 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
13673 * @class
13674 * @extends OO.ui.SelectWidget
13675 * @mixins OO.ui.TabIndexedElement
13677 * @constructor
13678 * @param {Object} [config] Configuration options
13680 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
13681 // Parent constructor
13682 OO.ui.RadioSelectWidget.super.call( this, config );
13684 // Mixin constructors
13685 OO.ui.TabIndexedElement.call( this, config );
13687 // Events
13688 this.$element.on( {
13689 focus: this.bindKeyDownListener.bind( this ),
13690 blur: this.unbindKeyDownListener.bind( this )
13691 } );
13693 // Initialization
13694 this.$element.addClass( 'oo-ui-radioSelectWidget' );
13697 /* Setup */
13699 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
13700 OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.TabIndexedElement );
13703 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
13704 * is used together with OO.ui.MenuOptionWidget. See {@link OO.ui.DropdownWidget DropdownWidget} and
13705 * {@link OO.ui.ComboBoxWidget ComboBoxWidget} for examples of interfaces that contain menus.
13706 * MenuSelectWidgets themselves are not designed to be instantiated directly, rather subclassed
13707 * and customized to be opened, closed, and displayed as needed.
13709 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
13710 * mouse outside the menu.
13712 * Menus also have support for keyboard interaction:
13714 * - Enter/Return key: choose and select a menu option
13715 * - Up-arrow key: highlight the previous menu option
13716 * - Down-arrow key: highlight the next menu option
13717 * - Esc key: hide the menu
13719 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
13720 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
13722 * @class
13723 * @extends OO.ui.SelectWidget
13724 * @mixins OO.ui.ClippableElement
13726 * @constructor
13727 * @param {Object} [config] Configuration options
13728 * @cfg {OO.ui.TextInputWidget} [input] Input to bind keyboard handlers to
13729 * @cfg {OO.ui.Widget} [widget] Widget to bind mouse handlers to
13730 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu
13732 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
13733 // Configuration initialization
13734 config = config || {};
13736 // Parent constructor
13737 OO.ui.MenuSelectWidget.super.call( this, config );
13739 // Mixin constructors
13740 OO.ui.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
13742 // Properties
13743 this.newItems = null;
13744 this.autoHide = config.autoHide === undefined || !!config.autoHide;
13745 this.$input = config.input ? config.input.$input : null;
13746 this.$widget = config.widget ? config.widget.$element : null;
13747 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
13749 // Initialization
13750 this.$element
13751 .addClass( 'oo-ui-menuSelectWidget' )
13752 .attr( 'role', 'menu' );
13754 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
13755 // that reference properties not initialized at that time of parent class construction
13756 // TODO: Find a better way to handle post-constructor setup
13757 this.visible = false;
13758 this.$element.addClass( 'oo-ui-element-hidden' );
13761 /* Setup */
13763 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
13764 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.ClippableElement );
13766 /* Methods */
13769 * Handles document mouse down events.
13771 * @protected
13772 * @param {jQuery.Event} e Key down event
13774 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
13775 if (
13776 !OO.ui.contains( this.$element[ 0 ], e.target, true ) &&
13777 ( !this.$widget || !OO.ui.contains( this.$widget[ 0 ], e.target, true ) )
13779 this.toggle( false );
13784 * @inheritdoc
13786 OO.ui.MenuSelectWidget.prototype.onKeyDown = function ( e ) {
13787 var currentItem = this.getHighlightedItem() || this.getSelectedItem();
13789 if ( !this.isDisabled() && this.isVisible() ) {
13790 switch ( e.keyCode ) {
13791 case OO.ui.Keys.LEFT:
13792 case OO.ui.Keys.RIGHT:
13793 // Do nothing if a text field is associated, arrow keys will be handled natively
13794 if ( !this.$input ) {
13795 OO.ui.MenuSelectWidget.super.prototype.onKeyDown.call( this, e );
13797 break;
13798 case OO.ui.Keys.ESCAPE:
13799 case OO.ui.Keys.TAB:
13800 if ( currentItem ) {
13801 currentItem.setHighlighted( false );
13803 this.toggle( false );
13804 // Don't prevent tabbing away, prevent defocusing
13805 if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
13806 e.preventDefault();
13807 e.stopPropagation();
13809 break;
13810 default:
13811 OO.ui.MenuSelectWidget.super.prototype.onKeyDown.call( this, e );
13812 return;
13818 * @inheritdoc
13820 OO.ui.MenuSelectWidget.prototype.bindKeyDownListener = function () {
13821 if ( this.$input ) {
13822 this.$input.on( 'keydown', this.onKeyDownHandler );
13823 } else {
13824 OO.ui.MenuSelectWidget.super.prototype.bindKeyDownListener.call( this );
13829 * @inheritdoc
13831 OO.ui.MenuSelectWidget.prototype.unbindKeyDownListener = function () {
13832 if ( this.$input ) {
13833 this.$input.off( 'keydown', this.onKeyDownHandler );
13834 } else {
13835 OO.ui.MenuSelectWidget.super.prototype.unbindKeyDownListener.call( this );
13840 * Choose an item.
13842 * This will close the menu, unlike #selectItem which only changes selection.
13844 * @param {OO.ui.OptionWidget} item Item to choose
13845 * @chainable
13847 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
13848 OO.ui.MenuSelectWidget.super.prototype.chooseItem.call( this, item );
13849 this.toggle( false );
13850 return this;
13854 * @inheritdoc
13856 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
13857 var i, len, item;
13859 // Parent method
13860 OO.ui.MenuSelectWidget.super.prototype.addItems.call( this, items, index );
13862 // Auto-initialize
13863 if ( !this.newItems ) {
13864 this.newItems = [];
13867 for ( i = 0, len = items.length; i < len; i++ ) {
13868 item = items[ i ];
13869 if ( this.isVisible() ) {
13870 // Defer fitting label until item has been attached
13871 item.fitLabel();
13872 } else {
13873 this.newItems.push( item );
13877 // Reevaluate clipping
13878 this.clip();
13880 return this;
13884 * @inheritdoc
13886 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
13887 // Parent method
13888 OO.ui.MenuSelectWidget.super.prototype.removeItems.call( this, items );
13890 // Reevaluate clipping
13891 this.clip();
13893 return this;
13897 * @inheritdoc
13899 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
13900 // Parent method
13901 OO.ui.MenuSelectWidget.super.prototype.clearItems.call( this );
13903 // Reevaluate clipping
13904 this.clip();
13906 return this;
13910 * @inheritdoc
13912 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
13913 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
13915 var i, len,
13916 change = visible !== this.isVisible();
13918 // Parent method
13919 OO.ui.MenuSelectWidget.super.prototype.toggle.call( this, visible );
13921 if ( change ) {
13922 if ( visible ) {
13923 this.bindKeyDownListener();
13925 if ( this.newItems && this.newItems.length ) {
13926 for ( i = 0, len = this.newItems.length; i < len; i++ ) {
13927 this.newItems[ i ].fitLabel();
13929 this.newItems = null;
13931 this.toggleClipping( true );
13933 // Auto-hide
13934 if ( this.autoHide ) {
13935 this.getElementDocument().addEventListener(
13936 'mousedown', this.onDocumentMouseDownHandler, true
13939 } else {
13940 this.unbindKeyDownListener();
13941 this.getElementDocument().removeEventListener(
13942 'mousedown', this.onDocumentMouseDownHandler, true
13944 this.toggleClipping( false );
13948 return this;
13952 * Menu for a text input widget.
13954 * This menu is specially designed to be positioned beneath a text input widget. The menu's position
13955 * is automatically calculated and maintained when the menu is toggled or the window is resized.
13957 * @class
13958 * @extends OO.ui.MenuSelectWidget
13960 * @constructor
13961 * @param {OO.ui.TextInputWidget} inputWidget Text input widget to provide menu for
13962 * @param {Object} [config] Configuration options
13963 * @cfg {jQuery} [$container=input.$element] Element to render menu under
13965 OO.ui.TextInputMenuSelectWidget = function OoUiTextInputMenuSelectWidget( inputWidget, config ) {
13966 // Allow passing positional parameters inside the config object
13967 if ( OO.isPlainObject( inputWidget ) && config === undefined ) {
13968 config = inputWidget;
13969 inputWidget = config.inputWidget;
13972 // Configuration initialization
13973 config = config || {};
13975 // Parent constructor
13976 OO.ui.TextInputMenuSelectWidget.super.call( this, config );
13978 // Properties
13979 this.inputWidget = inputWidget;
13980 this.$container = config.$container || this.inputWidget.$element;
13981 this.onWindowResizeHandler = this.onWindowResize.bind( this );
13983 // Initialization
13984 this.$element.addClass( 'oo-ui-textInputMenuSelectWidget' );
13987 /* Setup */
13989 OO.inheritClass( OO.ui.TextInputMenuSelectWidget, OO.ui.MenuSelectWidget );
13991 /* Methods */
13994 * Handle window resize event.
13996 * @param {jQuery.Event} e Window resize event
13998 OO.ui.TextInputMenuSelectWidget.prototype.onWindowResize = function () {
13999 this.position();
14003 * @inheritdoc
14005 OO.ui.TextInputMenuSelectWidget.prototype.toggle = function ( visible ) {
14006 visible = visible === undefined ? !this.isVisible() : !!visible;
14008 var change = visible !== this.isVisible();
14010 if ( change && visible ) {
14011 // Make sure the width is set before the parent method runs.
14012 // After this we have to call this.position(); again to actually
14013 // position ourselves correctly.
14014 this.position();
14017 // Parent method
14018 OO.ui.TextInputMenuSelectWidget.super.prototype.toggle.call( this, visible );
14020 if ( change ) {
14021 if ( this.isVisible() ) {
14022 this.position();
14023 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
14024 } else {
14025 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
14029 return this;
14033 * Position the menu.
14035 * @chainable
14037 OO.ui.TextInputMenuSelectWidget.prototype.position = function () {
14038 var $container = this.$container,
14039 pos = OO.ui.Element.static.getRelativePosition( $container, this.$element.offsetParent() );
14041 // Position under input
14042 pos.top += $container.height();
14043 this.$element.css( pos );
14045 // Set width
14046 this.setIdealSize( $container.width() );
14047 // We updated the position, so re-evaluate the clipping state
14048 this.clip();
14050 return this;
14054 * Structured list of items.
14056 * Use with OO.ui.OutlineOptionWidget.
14058 * @class
14059 * @extends OO.ui.SelectWidget
14060 * @mixins OO.ui.TabIndexedElement
14062 * @constructor
14063 * @param {Object} [config] Configuration options
14065 OO.ui.OutlineSelectWidget = function OoUiOutlineSelectWidget( config ) {
14066 // Parent constructor
14067 OO.ui.OutlineSelectWidget.super.call( this, config );
14069 // Mixin constructors
14070 OO.ui.TabIndexedElement.call( this, config );
14072 // Events
14073 this.$element.on( {
14074 focus: this.bindKeyDownListener.bind( this ),
14075 blur: this.unbindKeyDownListener.bind( this )
14076 } );
14078 // Initialization
14079 this.$element.addClass( 'oo-ui-outlineSelectWidget' );
14082 /* Setup */
14084 OO.inheritClass( OO.ui.OutlineSelectWidget, OO.ui.SelectWidget );
14085 OO.mixinClass( OO.ui.OutlineSelectWidget, OO.ui.TabIndexedElement );
14088 * Switch that slides on and off.
14090 * @class
14091 * @extends OO.ui.Widget
14092 * @mixins OO.ui.ToggleWidget
14093 * @mixins OO.ui.TabIndexedElement
14095 * @constructor
14096 * @param {Object} [config] Configuration options
14097 * @cfg {boolean} [value=false] Initial value
14099 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
14100 // Parent constructor
14101 OO.ui.ToggleSwitchWidget.super.call( this, config );
14103 // Mixin constructors
14104 OO.ui.ToggleWidget.call( this, config );
14105 OO.ui.TabIndexedElement.call( this, config );
14107 // Properties
14108 this.dragging = false;
14109 this.dragStart = null;
14110 this.sliding = false;
14111 this.$glow = $( '<span>' );
14112 this.$grip = $( '<span>' );
14114 // Events
14115 this.$element.on( {
14116 click: this.onClick.bind( this ),
14117 keypress: this.onKeyPress.bind( this )
14118 } );
14120 // Initialization
14121 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
14122 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
14123 this.$element
14124 .addClass( 'oo-ui-toggleSwitchWidget' )
14125 .attr( 'role', 'checkbox' )
14126 .append( this.$glow, this.$grip );
14129 /* Setup */
14131 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.Widget );
14132 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
14133 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.TabIndexedElement );
14135 /* Methods */
14138 * Handle mouse click events.
14140 * @param {jQuery.Event} e Mouse click event
14142 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
14143 if ( !this.isDisabled() && e.which === 1 ) {
14144 this.setValue( !this.value );
14146 return false;
14150 * Handle key press events.
14152 * @param {jQuery.Event} e Key press event
14154 OO.ui.ToggleSwitchWidget.prototype.onKeyPress = function ( e ) {
14155 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
14156 this.setValue( !this.value );
14158 return false;
14161 }( OO ) );