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-04-12T17:19:06Z
16 * Namespace for all classes, static methods and static properties.
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 () {
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
) {
76 // Known user language
77 langs
= OO
.ui
.getUserLanguages();
78 for ( i
= 0, len
= langs
.length
; i
< len
; i
++ ) {
85 if ( obj
[ fallback
] ) {
86 return obj
[ fallback
];
88 // First existing language
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
) {
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
) ) {
121 * Reconstitute a JavaScript object corresponding to a widget created by
122 * the PHP implementation.
124 * This is an alias for `OO.ui.Element.static.infuse()`.
126 * @param {string|HTMLElement|jQuery} idOrNode
127 * A DOM id (if a string) or node for the widget to infuse.
128 * @return {OO.ui.Element}
129 * The `OO.ui.Element` corresponding to this (infusable) document node.
131 OO
.ui
.infuse = function ( idOrNode
) {
132 return OO
.ui
.Element
.static.infuse( idOrNode
);
137 * Message store for the default implementation of OO.ui.msg
139 * Environments that provide a localization system should not use this, but should override
140 * OO.ui.msg altogether.
145 // Tool tip for a button that moves items in a list down one place
146 'ooui-outline-control-move-down': 'Move item down',
147 // Tool tip for a button that moves items in a list up one place
148 'ooui-outline-control-move-up': 'Move item up',
149 // Tool tip for a button that removes items from a list
150 'ooui-outline-control-remove': 'Remove item',
151 // Label for the toolbar group that contains a list of all other available tools
152 'ooui-toolbar-more': 'More',
153 // Label for the fake tool that expands the full list of tools in a toolbar group
154 'ooui-toolgroup-expand': 'More',
155 // Label for the fake tool that collapses the full list of tools in a toolbar group
156 'ooui-toolgroup-collapse': 'Fewer',
157 // Default label for the accept button of a confirmation dialog
158 'ooui-dialog-message-accept': 'OK',
159 // Default label for the reject button of a confirmation dialog
160 'ooui-dialog-message-reject': 'Cancel',
161 // Title for process dialog error description
162 'ooui-dialog-process-error': 'Something went wrong',
163 // Label for process dialog dismiss error button, visible when describing errors
164 'ooui-dialog-process-dismiss': 'Dismiss',
165 // Label for process dialog retry action button, visible when describing only recoverable errors
166 'ooui-dialog-process-retry': 'Try again',
167 // Label for process dialog retry action button, visible when describing only warnings
168 'ooui-dialog-process-continue': 'Continue'
172 * Get a localized message.
174 * In environments that provide a localization system, this function should be overridden to
175 * return the message translated in the user's language. The default implementation always returns
178 * After the message key, message parameters may optionally be passed. In the default implementation,
179 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
180 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
181 * they support unnamed, ordered message parameters.
184 * @param {string} key Message key
185 * @param {Mixed...} [params] Message parameters
186 * @return {string} Translated message with parameters substituted
188 OO
.ui
.msg = function ( key
) {
189 var message
= messages
[ key
],
190 params
= Array
.prototype.slice
.call( arguments
, 1 );
191 if ( typeof message
=== 'string' ) {
192 // Perform $1 substitution
193 message
= message
.replace( /\$(\d+)/g, function ( unused
, n
) {
194 var i
= parseInt( n
, 10 );
195 return params
[ i
- 1 ] !== undefined ? params
[ i
- 1 ] : '$' + n
;
198 // Return placeholder if message not found
199 message
= '[' + key
+ ']';
205 * Package a message and arguments for deferred resolution.
207 * Use this when you are statically specifying a message and the message may not yet be present.
209 * @param {string} key Message key
210 * @param {Mixed...} [params] Message parameters
211 * @return {Function} Function that returns the resolved message when executed
213 OO
.ui
.deferMsg = function () {
214 var args
= arguments
;
216 return OO
.ui
.msg
.apply( OO
.ui
, args
);
223 * If the message is a function it will be executed, otherwise it will pass through directly.
225 * @param {Function|string} msg Deferred message, or message text
226 * @return {string} Resolved message
228 OO
.ui
.resolveMsg = function ( msg
) {
229 if ( $.isFunction( msg
) ) {
238 * Element that can be marked as pending.
244 * @param {Object} [config] Configuration options
245 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
247 OO
.ui
.PendingElement
= function OoUiPendingElement( config
) {
248 // Configuration initialization
249 config
= config
|| {};
253 this.$pending
= null;
256 this.setPendingElement( config
.$pending
|| this.$element
);
261 OO
.initClass( OO
.ui
.PendingElement
);
266 * Set the pending element (and clean up any existing one).
268 * @param {jQuery} $pending The element to set to pending.
270 OO
.ui
.PendingElement
.prototype.setPendingElement = function ( $pending
) {
271 if ( this.$pending
) {
272 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
275 this.$pending
= $pending
;
276 if ( this.pending
> 0 ) {
277 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
282 * Check if input is pending.
286 OO
.ui
.PendingElement
.prototype.isPending = function () {
287 return !!this.pending
;
291 * Increase the pending stack.
295 OO
.ui
.PendingElement
.prototype.pushPending = function () {
296 if ( this.pending
=== 0 ) {
297 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
298 this.updateThemeClasses();
306 * Reduce the pending stack.
312 OO
.ui
.PendingElement
.prototype.popPending = function () {
313 if ( this.pending
=== 1 ) {
314 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
315 this.updateThemeClasses();
317 this.pending
= Math
.max( 0, this.pending
- 1 );
323 * ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them.
324 * Actions can be made available for specific contexts (modes) and circumstances
325 * (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
327 * ActionSets contain two types of actions:
329 * - Special: Special actions are the first visible actions with special flags, such as 'safe' and 'primary', the default special flags. Additional special flags can be configured in subclasses with the static #specialFlags property.
330 * - Other: Other actions include all non-special visible actions.
332 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
335 * // Example: An action set used in a process dialog
336 * function MyProcessDialog( config ) {
337 * MyProcessDialog.super.call( this, config );
339 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
340 * MyProcessDialog.static.title = 'An action set in a process dialog';
341 * // An action set that uses modes ('edit' and 'help' mode, in this example).
342 * MyProcessDialog.static.actions = [
343 * { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] },
344 * { action: 'help', modes: 'edit', label: 'Help' },
345 * { modes: 'edit', label: 'Cancel', flags: 'safe' },
346 * { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
349 * MyProcessDialog.prototype.initialize = function () {
350 * MyProcessDialog.super.prototype.initialize.apply( this, arguments );
351 * this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
352 * 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>' );
353 * this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
354 * 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>' );
355 * this.stackLayout = new OO.ui.StackLayout( {
356 * items: [ this.panel1, this.panel2 ]
358 * this.$body.append( this.stackLayout.$element );
360 * MyProcessDialog.prototype.getSetupProcess = function ( data ) {
361 * return MyProcessDialog.super.prototype.getSetupProcess.call( this, data )
362 * .next( function () {
363 * this.actions.setMode( 'edit' );
366 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
367 * if ( action === 'help' ) {
368 * this.actions.setMode( 'help' );
369 * this.stackLayout.setItem( this.panel2 );
370 * } else if ( action === 'back' ) {
371 * this.actions.setMode( 'edit' );
372 * this.stackLayout.setItem( this.panel1 );
373 * } else if ( action === 'continue' ) {
375 * return new OO.ui.Process( function () {
379 * return MyProcessDialog.super.prototype.getActionProcess.call( this, action );
381 * MyProcessDialog.prototype.getBodyHeight = function () {
382 * return this.panel1.$element.outerHeight( true );
384 * var windowManager = new OO.ui.WindowManager();
385 * $( 'body' ).append( windowManager.$element );
386 * var dialog = new MyProcessDialog( {
389 * windowManager.addWindows( [ dialog ] );
390 * windowManager.openWindow( dialog );
392 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
396 * @mixins OO.EventEmitter
399 * @param {Object} [config] Configuration options
401 OO
.ui
.ActionSet
= function OoUiActionSet( config
) {
402 // Configuration initialization
403 config
= config
|| {};
405 // Mixin constructors
406 OO
.EventEmitter
.call( this );
411 actions
: 'getAction',
415 this.categorized
= {};
418 this.organized
= false;
419 this.changing
= false;
420 this.changed
= false;
425 OO
.mixinClass( OO
.ui
.ActionSet
, OO
.EventEmitter
);
427 /* Static Properties */
430 * Symbolic name of the flags used to identify special actions. Special actions are displayed in the
431 * header of a {@link OO.ui.ProcessDialog process dialog}.
432 * See the [OOjs UI documentation on MediaWiki][2] for more information and examples.
434 * [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
441 OO
.ui
.ActionSet
.static.specialFlags
= [ 'safe', 'primary' ];
448 * A 'click' event is emitted when an action is clicked.
450 * @param {OO.ui.ActionWidget} action Action that was clicked
456 * A 'resize' event is emitted when an action widget is resized.
458 * @param {OO.ui.ActionWidget} action Action that was resized
464 * An 'add' event is emitted when actions are {@link #method-add added} to the action set.
466 * @param {OO.ui.ActionWidget[]} added Actions added
472 * A 'remove' event is emitted when actions are {@link #method-remove removed}
473 * or {@link #clear cleared}.
475 * @param {OO.ui.ActionWidget[]} added Actions removed
481 * A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
482 * or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed.
489 * Handle action change events.
494 OO
.ui
.ActionSet
.prototype.onActionChange = function () {
495 this.organized
= false;
496 if ( this.changing
) {
499 this.emit( 'change' );
504 * Check if an action is one of the special actions.
506 * @param {OO.ui.ActionWidget} action Action to check
507 * @return {boolean} Action is special
509 OO
.ui
.ActionSet
.prototype.isSpecial = function ( action
) {
512 for ( flag
in this.special
) {
513 if ( action
=== this.special
[ flag
] ) {
522 * Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
525 * @param {Object} [filters] Filters to use, omit to get all actions
526 * @param {string|string[]} [filters.actions] Actions that action widgets must have
527 * @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
528 * @param {string|string[]} [filters.modes] Modes that action widgets must have
529 * @param {boolean} [filters.visible] Action widgets must be visible
530 * @param {boolean} [filters.disabled] Action widgets must be disabled
531 * @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
533 OO
.ui
.ActionSet
.prototype.get = function ( filters
) {
534 var i
, len
, list
, category
, actions
, index
, match
, matches
;
539 // Collect category candidates
541 for ( category
in this.categorized
) {
542 list
= filters
[ category
];
544 if ( !Array
.isArray( list
) ) {
547 for ( i
= 0, len
= list
.length
; i
< len
; i
++ ) {
548 actions
= this.categorized
[ category
][ list
[ i
] ];
549 if ( Array
.isArray( actions
) ) {
550 matches
.push
.apply( matches
, actions
);
555 // Remove by boolean filters
556 for ( i
= 0, len
= matches
.length
; i
< len
; i
++ ) {
557 match
= matches
[ i
];
559 ( filters
.visible
!== undefined && match
.isVisible() !== filters
.visible
) ||
560 ( filters
.disabled
!== undefined && match
.isDisabled() !== filters
.disabled
)
562 matches
.splice( i
, 1 );
568 for ( i
= 0, len
= matches
.length
; i
< len
; i
++ ) {
569 match
= matches
[ i
];
570 index
= matches
.lastIndexOf( match
);
571 while ( index
!== i
) {
572 matches
.splice( index
, 1 );
574 index
= matches
.lastIndexOf( match
);
579 return this.list
.slice();
583 * Get 'special' actions.
585 * Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'.
586 * Special flags can be configured in subclasses by changing the static #specialFlags property.
588 * @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
590 OO
.ui
.ActionSet
.prototype.getSpecial = function () {
592 return $.extend( {}, this.special
);
596 * Get 'other' actions.
598 * Other actions include all non-special visible action widgets.
600 * @return {OO.ui.ActionWidget[]} 'Other' action widgets
602 OO
.ui
.ActionSet
.prototype.getOthers = function () {
604 return this.others
.slice();
608 * Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
609 * to be available in the specified mode will be made visible. All other actions will be hidden.
611 * @param {string} mode The mode. Only actions configured to be available in the specified
612 * mode will be made visible.
617 OO
.ui
.ActionSet
.prototype.setMode = function ( mode
) {
620 this.changing
= true;
621 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
622 action
= this.list
[ i
];
623 action
.toggle( action
.hasMode( mode
) );
626 this.organized
= false;
627 this.changing
= false;
628 this.emit( 'change' );
634 * Set the abilities of the specified actions.
636 * Action widgets that are configured with the specified actions will be enabled
637 * or disabled based on the boolean values specified in the `actions`
640 * @param {Object.<string,boolean>} actions A list keyed by action name with boolean
641 * values that indicate whether or not the action should be enabled.
644 OO
.ui
.ActionSet
.prototype.setAbilities = function ( actions
) {
645 var i
, len
, action
, item
;
647 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
648 item
= this.list
[ i
];
649 action
= item
.getAction();
650 if ( actions
[ action
] !== undefined ) {
651 item
.setDisabled( !actions
[ action
] );
659 * Executes a function once per action.
661 * When making changes to multiple actions, use this method instead of iterating over the actions
662 * manually to defer emitting a #change event until after all actions have been changed.
664 * @param {Object|null} actions Filters to use to determine which actions to iterate over; see #get
665 * @param {Function} callback Callback to run for each action; callback is invoked with three
666 * arguments: the action, the action's index, the list of actions being iterated over
669 OO
.ui
.ActionSet
.prototype.forEach = function ( filter
, callback
) {
670 this.changed
= false;
671 this.changing
= true;
672 this.get( filter
).forEach( callback
);
673 this.changing
= false;
674 if ( this.changed
) {
675 this.emit( 'change' );
682 * Add action widgets to the action set.
684 * @param {OO.ui.ActionWidget[]} actions Action widgets to add
689 OO
.ui
.ActionSet
.prototype.add = function ( actions
) {
692 this.changing
= true;
693 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
694 action
= actions
[ i
];
695 action
.connect( this, {
696 click
: [ 'emit', 'click', action
],
697 resize
: [ 'emit', 'resize', action
],
698 toggle
: [ 'onActionChange' ]
700 this.list
.push( action
);
702 this.organized
= false;
703 this.emit( 'add', actions
);
704 this.changing
= false;
705 this.emit( 'change' );
711 * Remove action widgets from the set.
713 * To remove all actions, you may wish to use the #clear method instead.
715 * @param {OO.ui.ActionWidget[]} actions Action widgets to remove
720 OO
.ui
.ActionSet
.prototype.remove = function ( actions
) {
721 var i
, len
, index
, action
;
723 this.changing
= true;
724 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
725 action
= actions
[ i
];
726 index
= this.list
.indexOf( action
);
727 if ( index
!== -1 ) {
728 action
.disconnect( this );
729 this.list
.splice( index
, 1 );
732 this.organized
= false;
733 this.emit( 'remove', actions
);
734 this.changing
= false;
735 this.emit( 'change' );
741 * Remove all action widets from the set.
743 * To remove only specified actions, use the {@link #method-remove remove} method instead.
749 OO
.ui
.ActionSet
.prototype.clear = function () {
751 removed
= this.list
.slice();
753 this.changing
= true;
754 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
755 action
= this.list
[ i
];
756 action
.disconnect( this );
761 this.organized
= false;
762 this.emit( 'remove', removed
);
763 this.changing
= false;
764 this.emit( 'change' );
772 * This is called whenever organized information is requested. It will only reorganize the actions
773 * if something has changed since the last time it ran.
778 OO
.ui
.ActionSet
.prototype.organize = function () {
779 var i
, iLen
, j
, jLen
, flag
, action
, category
, list
, item
, special
,
780 specialFlags
= this.constructor.static.specialFlags
;
782 if ( !this.organized
) {
783 this.categorized
= {};
786 for ( i
= 0, iLen
= this.list
.length
; i
< iLen
; i
++ ) {
787 action
= this.list
[ i
];
788 if ( action
.isVisible() ) {
789 // Populate categories
790 for ( category
in this.categories
) {
791 if ( !this.categorized
[ category
] ) {
792 this.categorized
[ category
] = {};
794 list
= action
[ this.categories
[ category
] ]();
795 if ( !Array
.isArray( list
) ) {
798 for ( j
= 0, jLen
= list
.length
; j
< jLen
; j
++ ) {
800 if ( !this.categorized
[ category
][ item
] ) {
801 this.categorized
[ category
][ item
] = [];
803 this.categorized
[ category
][ item
].push( action
);
806 // Populate special/others
808 for ( j
= 0, jLen
= specialFlags
.length
; j
< jLen
; j
++ ) {
809 flag
= specialFlags
[ j
];
810 if ( !this.special
[ flag
] && action
.hasFlag( flag
) ) {
811 this.special
[ flag
] = action
;
817 this.others
.push( action
);
821 this.organized
= true;
828 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
829 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
830 * connected to them and can't be interacted with.
836 * @param {Object} [config] Configuration options
837 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
838 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
840 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
841 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
842 * @cfg {string} [text] Text to insert
843 * @cfg {Array} [content] An array of content elements to append (after #text).
844 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
845 * Instances of OO.ui.Element will have their $element appended.
846 * @cfg {jQuery} [$content] Content elements to append (after #text)
847 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
848 * Data can also be specified with the #setData method.
850 OO
.ui
.Element
= function OoUiElement( config
) {
851 // Configuration initialization
852 config
= config
|| {};
857 this.data
= config
.data
;
858 this.$element
= config
.$element
||
859 $( document
.createElement( this.getTagName() ) );
860 this.elementGroup
= null;
861 this.debouncedUpdateThemeClassesHandler
= this.debouncedUpdateThemeClasses
.bind( this );
862 this.updateThemeClassesPending
= false;
865 if ( Array
.isArray( config
.classes
) ) {
866 this.$element
.addClass( config
.classes
.join( ' ' ) );
869 this.$element
.attr( 'id', config
.id
);
872 this.$element
.text( config
.text
);
874 if ( config
.content
) {
875 // The `content` property treats plain strings as text; use an
876 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
877 // appropriate $element appended.
878 this.$element
.append( config
.content
.map( function ( v
) {
879 if ( typeof v
=== 'string' ) {
880 // Escape string so it is properly represented in HTML.
881 return document
.createTextNode( v
);
882 } else if ( v
instanceof OO
.ui
.HtmlSnippet
) {
885 } else if ( v
instanceof OO
.ui
.Element
) {
891 if ( config
.$content
) {
892 // The `$content` property treats plain strings as HTML.
893 this.$element
.append( config
.$content
);
899 OO
.initClass( OO
.ui
.Element
);
901 /* Static Properties */
904 * The name of the HTML tag used by the element.
906 * The static value may be ignored if the #getTagName method is overridden.
912 OO
.ui
.Element
.static.tagName
= 'div';
917 * Reconstitute a JavaScript object corresponding to a widget created
918 * by the PHP implementation.
920 * @param {string|HTMLElement|jQuery} idOrNode
921 * A DOM id (if a string) or node for the widget to infuse.
922 * @return {OO.ui.Element}
923 * The `OO.ui.Element` corresponding to this (infusable) document node.
924 * For `Tag` objects emitted on the HTML side (used occasionally for content)
925 * the value returned is a newly-created Element wrapping around the existing
928 OO
.ui
.Element
.static.infuse = function ( idOrNode
) {
929 var obj
= OO
.ui
.Element
.static.unsafeInfuse( idOrNode
, true );
930 // Verify that the type matches up.
931 // FIXME: uncomment after T89721 is fixed (see T90929)
933 if ( !( obj instanceof this['class'] ) ) {
934 throw new Error( 'Infusion type mismatch!' );
941 * Implementation helper for `infuse`; skips the type check and has an
942 * extra property so that only the top-level invocation touches the DOM.
944 * @param {string|HTMLElement|jQuery} idOrNode
945 * @param {boolean} top True only for top-level invocation.
946 * @return {OO.ui.Element}
948 OO
.ui
.Element
.static.unsafeInfuse = function ( idOrNode
, top
) {
949 // look for a cached result of a previous infusion.
950 var id
, $elem
, data
, cls
, obj
;
951 if ( typeof idOrNode
=== 'string' ) {
953 $elem
= $( document
.getElementById( id
) );
955 $elem
= $( idOrNode
);
956 id
= $elem
.attr( 'id' );
958 data
= $elem
.data( 'ooui-infused' );
961 if ( data
=== true ) {
962 throw new Error( 'Circular dependency! ' + id
);
966 if ( !$elem
.length
) {
967 throw new Error( 'Widget not found: ' + id
);
969 data
= $elem
.attr( 'data-ooui' );
971 throw new Error( 'No infusion data found: ' + id
);
974 data
= $.parseJSON( data
);
978 if ( !( data
&& data
._
) ) {
979 throw new Error( 'No valid infusion data found: ' + id
);
981 if ( data
._
=== 'Tag' ) {
982 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
983 return new OO
.ui
.Element( { $element
: $elem
} );
987 throw new Error( 'Unknown widget type: ' + id
);
989 $elem
.data( 'ooui-infused', true ); // prevent loops
990 data
.id
= id
; // implicit
991 data
= OO
.copy( data
, null, function deserialize( value
) {
992 if ( OO
.isPlainObject( value
) ) {
994 return OO
.ui
.Element
.static.unsafeInfuse( value
.tag
, false );
997 return new OO
.ui
.HtmlSnippet( value
.html
);
1001 // jscs:disable requireCapitalizedConstructors
1002 obj
= new cls( data
); // rebuild widget
1003 // now replace old DOM with this new DOM.
1005 $elem
.replaceWith( obj
.$element
);
1007 obj
.$element
.data( 'ooui-infused', obj
);
1008 // set the 'data-ooui' attribute so we can identify infused widgets
1009 obj
.$element
.attr( 'data-ooui', '' );
1014 * Get a jQuery function within a specific document.
1017 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
1018 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
1020 * @return {Function} Bound jQuery function
1022 OO
.ui
.Element
.static.getJQuery = function ( context
, $iframe
) {
1023 function wrapper( selector
) {
1024 return $( selector
, wrapper
.context
);
1027 wrapper
.context
= this.getDocument( context
);
1030 wrapper
.$iframe
= $iframe
;
1037 * Get the document of an element.
1040 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
1041 * @return {HTMLDocument|null} Document object
1043 OO
.ui
.Element
.static.getDocument = function ( obj
) {
1044 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
1045 return ( obj
[ 0 ] && obj
[ 0 ].ownerDocument
) ||
1046 // Empty jQuery selections might have a context
1049 obj
.ownerDocument
||
1053 ( obj
.nodeType
=== 9 && obj
) ||
1058 * Get the window of an element or document.
1061 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
1062 * @return {Window} Window object
1064 OO
.ui
.Element
.static.getWindow = function ( obj
) {
1065 var doc
= this.getDocument( obj
);
1066 return doc
.parentWindow
|| doc
.defaultView
;
1070 * Get the direction of an element or document.
1073 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
1074 * @return {string} Text direction, either 'ltr' or 'rtl'
1076 OO
.ui
.Element
.static.getDir = function ( obj
) {
1079 if ( obj
instanceof jQuery
) {
1082 isDoc
= obj
.nodeType
=== 9;
1083 isWin
= obj
.document
!== undefined;
1084 if ( isDoc
|| isWin
) {
1090 return $( obj
).css( 'direction' );
1094 * Get the offset between two frames.
1096 * TODO: Make this function not use recursion.
1099 * @param {Window} from Window of the child frame
1100 * @param {Window} [to=window] Window of the parent frame
1101 * @param {Object} [offset] Offset to start with, used internally
1102 * @return {Object} Offset object, containing left and top properties
1104 OO
.ui
.Element
.static.getFrameOffset = function ( from, to
, offset
) {
1105 var i
, len
, frames
, frame
, rect
;
1111 offset
= { top
: 0, left
: 0 };
1113 if ( from.parent
=== from ) {
1117 // Get iframe element
1118 frames
= from.parent
.document
.getElementsByTagName( 'iframe' );
1119 for ( i
= 0, len
= frames
.length
; i
< len
; i
++ ) {
1120 if ( frames
[ i
].contentWindow
=== from ) {
1121 frame
= frames
[ i
];
1126 // Recursively accumulate offset values
1128 rect
= frame
.getBoundingClientRect();
1129 offset
.left
+= rect
.left
;
1130 offset
.top
+= rect
.top
;
1131 if ( from !== to
) {
1132 this.getFrameOffset( from.parent
, offset
);
1139 * Get the offset between two elements.
1141 * The two elements may be in a different frame, but in that case the frame $element is in must
1142 * be contained in the frame $anchor is in.
1145 * @param {jQuery} $element Element whose position to get
1146 * @param {jQuery} $anchor Element to get $element's position relative to
1147 * @return {Object} Translated position coordinates, containing top and left properties
1149 OO
.ui
.Element
.static.getRelativePosition = function ( $element
, $anchor
) {
1150 var iframe
, iframePos
,
1151 pos
= $element
.offset(),
1152 anchorPos
= $anchor
.offset(),
1153 elementDocument
= this.getDocument( $element
),
1154 anchorDocument
= this.getDocument( $anchor
);
1156 // If $element isn't in the same document as $anchor, traverse up
1157 while ( elementDocument
!== anchorDocument
) {
1158 iframe
= elementDocument
.defaultView
.frameElement
;
1160 throw new Error( '$element frame is not contained in $anchor frame' );
1162 iframePos
= $( iframe
).offset();
1163 pos
.left
+= iframePos
.left
;
1164 pos
.top
+= iframePos
.top
;
1165 elementDocument
= iframe
.ownerDocument
;
1167 pos
.left
-= anchorPos
.left
;
1168 pos
.top
-= anchorPos
.top
;
1173 * Get element border sizes.
1176 * @param {HTMLElement} el Element to measure
1177 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1179 OO
.ui
.Element
.static.getBorders = function ( el
) {
1180 var doc
= el
.ownerDocument
,
1181 win
= doc
.parentWindow
|| doc
.defaultView
,
1182 style
= win
&& win
.getComputedStyle
?
1183 win
.getComputedStyle( el
, null ) :
1186 top
= parseFloat( style
? style
.borderTopWidth
: $el
.css( 'borderTopWidth' ) ) || 0,
1187 left
= parseFloat( style
? style
.borderLeftWidth
: $el
.css( 'borderLeftWidth' ) ) || 0,
1188 bottom
= parseFloat( style
? style
.borderBottomWidth
: $el
.css( 'borderBottomWidth' ) ) || 0,
1189 right
= parseFloat( style
? style
.borderRightWidth
: $el
.css( 'borderRightWidth' ) ) || 0;
1200 * Get dimensions of an element or window.
1203 * @param {HTMLElement|Window} el Element to measure
1204 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1206 OO
.ui
.Element
.static.getDimensions = function ( el
) {
1208 doc
= el
.ownerDocument
|| el
.document
,
1209 win
= doc
.parentWindow
|| doc
.defaultView
;
1211 if ( win
=== el
|| el
=== doc
.documentElement
) {
1214 borders
: { top
: 0, left
: 0, bottom
: 0, right
: 0 },
1216 top
: $win
.scrollTop(),
1217 left
: $win
.scrollLeft()
1219 scrollbar
: { right
: 0, bottom
: 0 },
1223 bottom
: $win
.innerHeight(),
1224 right
: $win
.innerWidth()
1230 borders
: this.getBorders( el
),
1232 top
: $el
.scrollTop(),
1233 left
: $el
.scrollLeft()
1236 right
: $el
.innerWidth() - el
.clientWidth
,
1237 bottom
: $el
.innerHeight() - el
.clientHeight
1239 rect
: el
.getBoundingClientRect()
1245 * Get scrollable object parent
1247 * documentElement can't be used to get or set the scrollTop
1248 * property on Blink. Changing and testing its value lets us
1249 * use 'body' or 'documentElement' based on what is working.
1251 * https://code.google.com/p/chromium/issues/detail?id=303131
1254 * @param {HTMLElement} el Element to find scrollable parent for
1255 * @return {HTMLElement} Scrollable parent
1257 OO
.ui
.Element
.static.getRootScrollableElement = function ( el
) {
1258 var scrollTop
, body
;
1260 if ( OO
.ui
.scrollableElement
=== undefined ) {
1261 body
= el
.ownerDocument
.body
;
1262 scrollTop
= body
.scrollTop
;
1265 if ( body
.scrollTop
=== 1 ) {
1266 body
.scrollTop
= scrollTop
;
1267 OO
.ui
.scrollableElement
= 'body';
1269 OO
.ui
.scrollableElement
= 'documentElement';
1273 return el
.ownerDocument
[ OO
.ui
.scrollableElement
];
1277 * Get closest scrollable container.
1279 * Traverses up until either a scrollable element or the root is reached, in which case the window
1283 * @param {HTMLElement} el Element to find scrollable container for
1284 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1285 * @return {HTMLElement} Closest scrollable container
1287 OO
.ui
.Element
.static.getClosestScrollableContainer = function ( el
, dimension
) {
1289 props
= [ 'overflow' ],
1290 $parent
= $( el
).parent();
1292 if ( dimension
=== 'x' || dimension
=== 'y' ) {
1293 props
.push( 'overflow-' + dimension
);
1296 while ( $parent
.length
) {
1297 if ( $parent
[ 0 ] === this.getRootScrollableElement( el
) ) {
1298 return $parent
[ 0 ];
1302 val
= $parent
.css( props
[ i
] );
1303 if ( val
=== 'auto' || val
=== 'scroll' ) {
1304 return $parent
[ 0 ];
1307 $parent
= $parent
.parent();
1309 return this.getDocument( el
).body
;
1313 * Scroll element into view.
1316 * @param {HTMLElement} el Element to scroll into view
1317 * @param {Object} [config] Configuration options
1318 * @param {string} [config.duration] jQuery animation duration value
1319 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1320 * to scroll in both directions
1321 * @param {Function} [config.complete] Function to call when scrolling completes
1323 OO
.ui
.Element
.static.scrollIntoView = function ( el
, config
) {
1324 // Configuration initialization
1325 config
= config
|| {};
1328 callback
= typeof config
.complete
=== 'function' && config
.complete
,
1329 sc
= this.getClosestScrollableContainer( el
, config
.direction
),
1331 eld
= this.getDimensions( el
),
1332 scd
= this.getDimensions( sc
),
1333 $win
= $( this.getWindow( el
) );
1335 // Compute the distances between the edges of el and the edges of the scroll viewport
1336 if ( $sc
.is( 'html, body' ) ) {
1337 // If the scrollable container is the root, this is easy
1340 bottom
: $win
.innerHeight() - eld
.rect
.bottom
,
1341 left
: eld
.rect
.left
,
1342 right
: $win
.innerWidth() - eld
.rect
.right
1345 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1347 top
: eld
.rect
.top
- ( scd
.rect
.top
+ scd
.borders
.top
),
1348 bottom
: scd
.rect
.bottom
- scd
.borders
.bottom
- scd
.scrollbar
.bottom
- eld
.rect
.bottom
,
1349 left
: eld
.rect
.left
- ( scd
.rect
.left
+ scd
.borders
.left
),
1350 right
: scd
.rect
.right
- scd
.borders
.right
- scd
.scrollbar
.right
- eld
.rect
.right
1354 if ( !config
.direction
|| config
.direction
=== 'y' ) {
1355 if ( rel
.top
< 0 ) {
1356 anim
.scrollTop
= scd
.scroll
.top
+ rel
.top
;
1357 } else if ( rel
.top
> 0 && rel
.bottom
< 0 ) {
1358 anim
.scrollTop
= scd
.scroll
.top
+ Math
.min( rel
.top
, -rel
.bottom
);
1361 if ( !config
.direction
|| config
.direction
=== 'x' ) {
1362 if ( rel
.left
< 0 ) {
1363 anim
.scrollLeft
= scd
.scroll
.left
+ rel
.left
;
1364 } else if ( rel
.left
> 0 && rel
.right
< 0 ) {
1365 anim
.scrollLeft
= scd
.scroll
.left
+ Math
.min( rel
.left
, -rel
.right
);
1368 if ( !$.isEmptyObject( anim
) ) {
1369 $sc
.stop( true ).animate( anim
, config
.duration
|| 'fast' );
1371 $sc
.queue( function ( next
) {
1384 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1385 * and reserve space for them, because it probably doesn't.
1387 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1388 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1389 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1390 * and then reattach (or show) them back.
1393 * @param {HTMLElement} el Element to reconsider the scrollbars on
1395 OO
.ui
.Element
.static.reconsiderScrollbars = function ( el
) {
1396 var i
, len
, nodes
= [];
1397 // Detach all children
1398 while ( el
.firstChild
) {
1399 nodes
.push( el
.firstChild
);
1400 el
.removeChild( el
.firstChild
);
1403 void el
.offsetHeight
;
1404 // Reattach all children
1405 for ( i
= 0, len
= nodes
.length
; i
< len
; i
++ ) {
1406 el
.appendChild( nodes
[ i
] );
1413 * Toggle visibility of an element.
1415 * @param {boolean} [show] Make element visible, omit to toggle visibility
1419 OO
.ui
.Element
.prototype.toggle = function ( show
) {
1420 show
= show
=== undefined ? !this.visible
: !!show
;
1422 if ( show
!== this.isVisible() ) {
1423 this.visible
= show
;
1424 this.$element
.toggleClass( 'oo-ui-element-hidden', !this.visible
);
1425 this.emit( 'toggle', show
);
1432 * Check if element is visible.
1434 * @return {boolean} element is visible
1436 OO
.ui
.Element
.prototype.isVisible = function () {
1437 return this.visible
;
1443 * @return {Mixed} Element data
1445 OO
.ui
.Element
.prototype.getData = function () {
1452 * @param {Mixed} Element data
1455 OO
.ui
.Element
.prototype.setData = function ( data
) {
1461 * Check if element supports one or more methods.
1463 * @param {string|string[]} methods Method or list of methods to check
1464 * @return {boolean} All methods are supported
1466 OO
.ui
.Element
.prototype.supports = function ( methods
) {
1470 methods
= Array
.isArray( methods
) ? methods
: [ methods
];
1471 for ( i
= 0, len
= methods
.length
; i
< len
; i
++ ) {
1472 if ( $.isFunction( this[ methods
[ i
] ] ) ) {
1477 return methods
.length
=== support
;
1481 * Update the theme-provided classes.
1483 * @localdoc This is called in element mixins and widget classes any time state changes.
1484 * Updating is debounced, minimizing overhead of changing multiple attributes and
1485 * guaranteeing that theme updates do not occur within an element's constructor
1487 OO
.ui
.Element
.prototype.updateThemeClasses = function () {
1488 if ( !this.updateThemeClassesPending
) {
1489 this.updateThemeClassesPending
= true;
1490 setTimeout( this.debouncedUpdateThemeClassesHandler
);
1497 OO
.ui
.Element
.prototype.debouncedUpdateThemeClasses = function () {
1498 OO
.ui
.theme
.updateElementClasses( this );
1499 this.updateThemeClassesPending
= false;
1503 * Get the HTML tag name.
1505 * Override this method to base the result on instance information.
1507 * @return {string} HTML tag name
1509 OO
.ui
.Element
.prototype.getTagName = function () {
1510 return this.constructor.static.tagName
;
1514 * Check if the element is attached to the DOM
1515 * @return {boolean} The element is attached to the DOM
1517 OO
.ui
.Element
.prototype.isElementAttached = function () {
1518 return $.contains( this.getElementDocument(), this.$element
[ 0 ] );
1522 * Get the DOM document.
1524 * @return {HTMLDocument} Document object
1526 OO
.ui
.Element
.prototype.getElementDocument = function () {
1527 // Don't cache this in other ways either because subclasses could can change this.$element
1528 return OO
.ui
.Element
.static.getDocument( this.$element
);
1532 * Get the DOM window.
1534 * @return {Window} Window object
1536 OO
.ui
.Element
.prototype.getElementWindow = function () {
1537 return OO
.ui
.Element
.static.getWindow( this.$element
);
1541 * Get closest scrollable container.
1543 OO
.ui
.Element
.prototype.getClosestScrollableElementContainer = function () {
1544 return OO
.ui
.Element
.static.getClosestScrollableContainer( this.$element
[ 0 ] );
1548 * Get group element is in.
1550 * @return {OO.ui.GroupElement|null} Group element, null if none
1552 OO
.ui
.Element
.prototype.getElementGroup = function () {
1553 return this.elementGroup
;
1557 * Set group element is in.
1559 * @param {OO.ui.GroupElement|null} group Group element, null if none
1562 OO
.ui
.Element
.prototype.setElementGroup = function ( group
) {
1563 this.elementGroup
= group
;
1568 * Scroll element into view.
1570 * @param {Object} [config] Configuration options
1572 OO
.ui
.Element
.prototype.scrollElementIntoView = function ( config
) {
1573 return OO
.ui
.Element
.static.scrollIntoView( this.$element
[ 0 ], config
);
1577 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1578 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1579 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1580 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1581 * and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1585 * @extends OO.ui.Element
1586 * @mixins OO.EventEmitter
1589 * @param {Object} [config] Configuration options
1591 OO
.ui
.Layout
= function OoUiLayout( config
) {
1592 // Configuration initialization
1593 config
= config
|| {};
1595 // Parent constructor
1596 OO
.ui
.Layout
.super.call( this, config
);
1598 // Mixin constructors
1599 OO
.EventEmitter
.call( this );
1602 this.$element
.addClass( 'oo-ui-layout' );
1607 OO
.inheritClass( OO
.ui
.Layout
, OO
.ui
.Element
);
1608 OO
.mixinClass( OO
.ui
.Layout
, OO
.EventEmitter
);
1611 * Widgets are compositions of one or more OOjs UI elements that users can both view
1612 * and interact with. All widgets can be configured and modified via a standard API,
1613 * and their state can change dynamically according to a model.
1617 * @extends OO.ui.Element
1618 * @mixins OO.EventEmitter
1621 * @param {Object} [config] Configuration options
1622 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1623 * appearance reflects this state.
1625 OO
.ui
.Widget
= function OoUiWidget( config
) {
1626 // Initialize config
1627 config
= $.extend( { disabled
: false }, config
);
1629 // Parent constructor
1630 OO
.ui
.Widget
.super.call( this, config
);
1632 // Mixin constructors
1633 OO
.EventEmitter
.call( this );
1636 this.disabled
= null;
1637 this.wasDisabled
= null;
1640 this.$element
.addClass( 'oo-ui-widget' );
1641 this.setDisabled( !!config
.disabled
);
1646 OO
.inheritClass( OO
.ui
.Widget
, OO
.ui
.Element
);
1647 OO
.mixinClass( OO
.ui
.Widget
, OO
.EventEmitter
);
1654 * A 'disable' event is emitted when a widget is disabled.
1656 * @param {boolean} disabled Widget is disabled
1662 * A 'toggle' event is emitted when the visibility of the widget changes.
1664 * @param {boolean} visible Widget is visible
1670 * Check if the widget is disabled.
1672 * @return {boolean} Widget is disabled
1674 OO
.ui
.Widget
.prototype.isDisabled = function () {
1675 return this.disabled
;
1679 * Set the 'disabled' state of the widget.
1681 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1683 * @param {boolean} disabled Disable widget
1686 OO
.ui
.Widget
.prototype.setDisabled = function ( disabled
) {
1689 this.disabled
= !!disabled
;
1690 isDisabled
= this.isDisabled();
1691 if ( isDisabled
!== this.wasDisabled
) {
1692 this.$element
.toggleClass( 'oo-ui-widget-disabled', isDisabled
);
1693 this.$element
.toggleClass( 'oo-ui-widget-enabled', !isDisabled
);
1694 this.$element
.attr( 'aria-disabled', isDisabled
.toString() );
1695 this.emit( 'disable', isDisabled
);
1696 this.updateThemeClasses();
1698 this.wasDisabled
= isDisabled
;
1704 * Update the disabled state, in case of changes in parent widget.
1708 OO
.ui
.Widget
.prototype.updateDisabled = function () {
1709 this.setDisabled( this.disabled
);
1714 * A window is a container for elements that are in a child frame. They are used with
1715 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
1716 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
1717 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
1718 * the window manager will choose a sensible fallback.
1720 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
1721 * different processes are executed:
1723 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
1724 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
1727 * - {@link #getSetupProcess} method is called and its result executed
1728 * - {@link #getReadyProcess} method is called and its result executed
1730 * **opened**: The window is now open
1732 * **closing**: The closing stage begins when the window manager's
1733 * {@link OO.ui.WindowManager#closeWindow closeWindow}
1734 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
1736 * - {@link #getHoldProcess} method is called and its result executed
1737 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
1739 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
1740 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
1741 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
1742 * processing can complete. Always assume window processes are executed asynchronously.
1744 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
1746 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
1750 * @extends OO.ui.Element
1751 * @mixins OO.EventEmitter
1754 * @param {Object} [config] Configuration options
1755 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
1756 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
1758 OO
.ui
.Window
= function OoUiWindow( config
) {
1759 // Configuration initialization
1760 config
= config
|| {};
1762 // Parent constructor
1763 OO
.ui
.Window
.super.call( this, config
);
1765 // Mixin constructors
1766 OO
.EventEmitter
.call( this );
1769 this.manager
= null;
1770 this.size
= config
.size
|| this.constructor.static.size
;
1771 this.$frame
= $( '<div>' );
1772 this.$overlay
= $( '<div>' );
1773 this.$content
= $( '<div>' );
1776 this.$overlay
.addClass( 'oo-ui-window-overlay' );
1778 .addClass( 'oo-ui-window-content' )
1779 .attr( 'tabIndex', 0 );
1781 .addClass( 'oo-ui-window-frame' )
1782 .append( this.$content
);
1785 .addClass( 'oo-ui-window' )
1786 .append( this.$frame
, this.$overlay
);
1788 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
1789 // that reference properties not initialized at that time of parent class construction
1790 // TODO: Find a better way to handle post-constructor setup
1791 this.visible
= false;
1792 this.$element
.addClass( 'oo-ui-element-hidden' );
1797 OO
.inheritClass( OO
.ui
.Window
, OO
.ui
.Element
);
1798 OO
.mixinClass( OO
.ui
.Window
, OO
.EventEmitter
);
1800 /* Static Properties */
1803 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
1805 * The static size is used if no #size is configured during construction.
1809 * @property {string}
1811 OO
.ui
.Window
.static.size
= 'medium';
1816 * Handle mouse down events.
1819 * @param {jQuery.Event} e Mouse down event
1821 OO
.ui
.Window
.prototype.onMouseDown = function ( e
) {
1822 // Prevent clicking on the click-block from stealing focus
1823 if ( e
.target
=== this.$element
[ 0 ] ) {
1829 * Check if the window has been initialized.
1831 * Initialization occurs when a window is added to a manager.
1833 * @return {boolean} Window has been initialized
1835 OO
.ui
.Window
.prototype.isInitialized = function () {
1836 return !!this.manager
;
1840 * Check if the window is visible.
1842 * @return {boolean} Window is visible
1844 OO
.ui
.Window
.prototype.isVisible = function () {
1845 return this.visible
;
1849 * Check if the window is opening.
1851 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
1854 * @return {boolean} Window is opening
1856 OO
.ui
.Window
.prototype.isOpening = function () {
1857 return this.manager
.isOpening( this );
1861 * Check if the window is closing.
1863 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
1865 * @return {boolean} Window is closing
1867 OO
.ui
.Window
.prototype.isClosing = function () {
1868 return this.manager
.isClosing( this );
1872 * Check if the window is opened.
1874 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
1876 * @return {boolean} Window is opened
1878 OO
.ui
.Window
.prototype.isOpened = function () {
1879 return this.manager
.isOpened( this );
1883 * Get the window manager.
1885 * All windows must be attached to a window manager, which is used to open
1886 * and close the window and control its presentation.
1888 * @return {OO.ui.WindowManager} Manager of window
1890 OO
.ui
.Window
.prototype.getManager = function () {
1891 return this.manager
;
1895 * Get the symbolic name of the window size (e.g., `small` or `medium`).
1897 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
1899 OO
.ui
.Window
.prototype.getSize = function () {
1904 * Disable transitions on window's frame for the duration of the callback function, then enable them
1908 * @param {Function} callback Function to call while transitions are disabled
1910 OO
.ui
.Window
.prototype.withoutSizeTransitions = function ( callback
) {
1911 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
1912 // Disable transitions first, otherwise we'll get values from when the window was animating.
1914 styleObj
= this.$frame
[ 0 ].style
;
1915 oldTransition
= styleObj
.transition
|| styleObj
.OTransition
|| styleObj
.MsTransition
||
1916 styleObj
.MozTransition
|| styleObj
.WebkitTransition
;
1917 styleObj
.transition
= styleObj
.OTransition
= styleObj
.MsTransition
=
1918 styleObj
.MozTransition
= styleObj
.WebkitTransition
= 'none';
1920 // Force reflow to make sure the style changes done inside callback really are not transitioned
1921 this.$frame
.height();
1922 styleObj
.transition
= styleObj
.OTransition
= styleObj
.MsTransition
=
1923 styleObj
.MozTransition
= styleObj
.WebkitTransition
= oldTransition
;
1927 * Get the height of the full window contents (i.e., the window head, body and foot together).
1929 * What consistitutes the head, body, and foot varies depending on the window type.
1930 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
1931 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
1932 * and special actions in the head, and dialog content in the body.
1934 * To get just the height of the dialog body, use the #getBodyHeight method.
1936 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
1938 OO
.ui
.Window
.prototype.getContentHeight = function () {
1941 bodyStyleObj
= this.$body
[ 0 ].style
,
1942 frameStyleObj
= this.$frame
[ 0 ].style
;
1944 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
1945 // Disable transitions first, otherwise we'll get values from when the window was animating.
1946 this.withoutSizeTransitions( function () {
1947 var oldHeight
= frameStyleObj
.height
,
1948 oldPosition
= bodyStyleObj
.position
;
1949 frameStyleObj
.height
= '1px';
1950 // Force body to resize to new width
1951 bodyStyleObj
.position
= 'relative';
1952 bodyHeight
= win
.getBodyHeight();
1953 frameStyleObj
.height
= oldHeight
;
1954 bodyStyleObj
.position
= oldPosition
;
1958 // Add buffer for border
1959 ( this.$frame
.outerHeight() - this.$frame
.innerHeight() ) +
1960 // Use combined heights of children
1961 ( this.$head
.outerHeight( true ) + bodyHeight
+ this.$foot
.outerHeight( true ) )
1966 * Get the height of the window body.
1968 * To get the height of the full window contents (the window body, head, and foot together),
1969 * use #getContentHeight.
1971 * When this function is called, the window will temporarily have been resized
1972 * to height=1px, so .scrollHeight measurements can be taken accurately.
1974 * @return {number} Height of the window body in pixels
1976 OO
.ui
.Window
.prototype.getBodyHeight = function () {
1977 return this.$body
[ 0 ].scrollHeight
;
1981 * Get the directionality of the frame (right-to-left or left-to-right).
1983 * @return {string} Directionality: `'ltr'` or `'rtl'`
1985 OO
.ui
.Window
.prototype.getDir = function () {
1990 * Get the 'setup' process.
1992 * The setup process is used to set up a window for use in a particular context,
1993 * based on the `data` argument. This method is called during the opening phase of the window’s
1996 * Override this method to add additional steps to the ‘setup’ process the parent method provides
1997 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2000 * To add window content that persists between openings, you may wish to use the #initialize method
2004 * @param {Object} [data] Window opening data
2005 * @return {OO.ui.Process} Setup process
2007 OO
.ui
.Window
.prototype.getSetupProcess = function () {
2008 return new OO
.ui
.Process();
2012 * Get the ‘ready’ process.
2014 * The ready process is used to ready a window for use in a particular
2015 * context, based on the `data` argument. This method is called during the opening phase of
2016 * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
2018 * Override this method to add additional steps to the ‘ready’ process the parent method
2019 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
2020 * methods of OO.ui.Process.
2023 * @param {Object} [data] Window opening data
2024 * @return {OO.ui.Process} Ready process
2026 OO
.ui
.Window
.prototype.getReadyProcess = function () {
2027 return new OO
.ui
.Process();
2031 * Get the 'hold' process.
2033 * The hold proccess is used to keep a window from being used in a particular context,
2034 * based on the `data` argument. This method is called during the closing phase of the window’s
2037 * Override this method to add additional steps to the 'hold' process the parent method provides
2038 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2042 * @param {Object} [data] Window closing data
2043 * @return {OO.ui.Process} Hold process
2045 OO
.ui
.Window
.prototype.getHoldProcess = function () {
2046 return new OO
.ui
.Process();
2050 * Get the ‘teardown’ process.
2052 * The teardown process is used to teardown a window after use. During teardown,
2053 * user interactions within the window are conveyed and the window is closed, based on the `data`
2054 * argument. This method is called during the closing phase of the window’s lifecycle.
2056 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
2057 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2061 * @param {Object} [data] Window closing data
2062 * @return {OO.ui.Process} Teardown process
2064 OO
.ui
.Window
.prototype.getTeardownProcess = function () {
2065 return new OO
.ui
.Process();
2069 * Set the window manager.
2071 * This will cause the window to initialize. Calling it more than once will cause an error.
2073 * @param {OO.ui.WindowManager} manager Manager for this window
2074 * @throws {Error} An error is thrown if the method is called more than once
2077 OO
.ui
.Window
.prototype.setManager = function ( manager
) {
2078 if ( this.manager
) {
2079 throw new Error( 'Cannot set window manager, window already has a manager' );
2082 this.manager
= manager
;
2089 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2091 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2095 OO
.ui
.Window
.prototype.setSize = function ( size
) {
2102 * Update the window size.
2104 * @throws {Error} An error is thrown if the window is not attached to a window manager
2107 OO
.ui
.Window
.prototype.updateSize = function () {
2108 if ( !this.manager
) {
2109 throw new Error( 'Cannot update window size, must be attached to a manager' );
2112 this.manager
.updateWindowSize( this );
2118 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2119 * when the window is opening. In general, setDimensions should not be called directly.
2121 * To set the size of the window, use the #setSize method.
2123 * @param {Object} dim CSS dimension properties
2124 * @param {string|number} [dim.width] Width
2125 * @param {string|number} [dim.minWidth] Minimum width
2126 * @param {string|number} [dim.maxWidth] Maximum width
2127 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2128 * @param {string|number} [dim.minWidth] Minimum height
2129 * @param {string|number} [dim.maxWidth] Maximum height
2132 OO
.ui
.Window
.prototype.setDimensions = function ( dim
) {
2135 styleObj
= this.$frame
[ 0 ].style
;
2137 // Calculate the height we need to set using the correct width
2138 if ( dim
.height
=== undefined ) {
2139 this.withoutSizeTransitions( function () {
2140 var oldWidth
= styleObj
.width
;
2141 win
.$frame
.css( 'width', dim
.width
|| '' );
2142 height
= win
.getContentHeight();
2143 styleObj
.width
= oldWidth
;
2146 height
= dim
.height
;
2150 width
: dim
.width
|| '',
2151 minWidth
: dim
.minWidth
|| '',
2152 maxWidth
: dim
.maxWidth
|| '',
2153 height
: height
|| '',
2154 minHeight
: dim
.minHeight
|| '',
2155 maxHeight
: dim
.maxHeight
|| ''
2162 * Initialize window contents.
2164 * Before the window is opened for the first time, #initialize is called so that content that
2165 * persists between openings can be added to the window.
2167 * To set up a window with new content each time the window opens, use #getSetupProcess.
2169 * @throws {Error} An error is thrown if the window is not attached to a window manager
2172 OO
.ui
.Window
.prototype.initialize = function () {
2173 if ( !this.manager
) {
2174 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2178 this.$head
= $( '<div>' );
2179 this.$body
= $( '<div>' );
2180 this.$foot
= $( '<div>' );
2181 this.dir
= OO
.ui
.Element
.static.getDir( this.$content
) || 'ltr';
2182 this.$document
= $( this.getElementDocument() );
2185 this.$element
.on( 'mousedown', this.onMouseDown
.bind( this ) );
2188 this.$head
.addClass( 'oo-ui-window-head' );
2189 this.$body
.addClass( 'oo-ui-window-body' );
2190 this.$foot
.addClass( 'oo-ui-window-foot' );
2191 this.$content
.append( this.$head
, this.$body
, this.$foot
);
2199 * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
2200 * method, which returns a promise resolved when the window is done opening.
2202 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2204 * @param {Object} [data] Window opening data
2205 * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
2206 * if the window fails to open. When the promise is resolved successfully, the first argument of the
2207 * value is a new promise, which is resolved when the window begins closing.
2208 * @throws {Error} An error is thrown if the window is not attached to a window manager
2210 OO
.ui
.Window
.prototype.open = function ( data
) {
2211 if ( !this.manager
) {
2212 throw new Error( 'Cannot open window, must be attached to a manager' );
2215 return this.manager
.openWindow( this, data
);
2221 * This method is a wrapper around a call to the window
2222 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
2223 * which returns a closing promise resolved when the window is done closing.
2225 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2226 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2227 * the window closes.
2229 * @param {Object} [data] Window closing data
2230 * @return {jQuery.Promise} Promise resolved when window is closed
2231 * @throws {Error} An error is thrown if the window is not attached to a window manager
2233 OO
.ui
.Window
.prototype.close = function ( data
) {
2234 if ( !this.manager
) {
2235 throw new Error( 'Cannot close window, must be attached to a manager' );
2238 return this.manager
.closeWindow( this, data
);
2244 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2247 * @param {Object} [data] Window opening data
2248 * @return {jQuery.Promise} Promise resolved when window is setup
2250 OO
.ui
.Window
.prototype.setup = function ( data
) {
2252 deferred
= $.Deferred();
2254 this.toggle( true );
2256 this.getSetupProcess( data
).execute().done( function () {
2257 // Force redraw by asking the browser to measure the elements' widths
2258 win
.$element
.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2259 win
.$content
.addClass( 'oo-ui-window-content-setup' ).width();
2263 return deferred
.promise();
2269 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2272 * @param {Object} [data] Window opening data
2273 * @return {jQuery.Promise} Promise resolved when window is ready
2275 OO
.ui
.Window
.prototype.ready = function ( data
) {
2277 deferred
= $.Deferred();
2279 this.$content
.focus();
2280 this.getReadyProcess( data
).execute().done( function () {
2281 // Force redraw by asking the browser to measure the elements' widths
2282 win
.$element
.addClass( 'oo-ui-window-ready' ).width();
2283 win
.$content
.addClass( 'oo-ui-window-content-ready' ).width();
2287 return deferred
.promise();
2293 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2296 * @param {Object} [data] Window closing data
2297 * @return {jQuery.Promise} Promise resolved when window is held
2299 OO
.ui
.Window
.prototype.hold = function ( data
) {
2301 deferred
= $.Deferred();
2303 this.getHoldProcess( data
).execute().done( function () {
2304 // Get the focused element within the window's content
2305 var $focus
= win
.$content
.find( OO
.ui
.Element
.static.getDocument( win
.$content
).activeElement
);
2307 // Blur the focused element
2308 if ( $focus
.length
) {
2312 // Force redraw by asking the browser to measure the elements' widths
2313 win
.$element
.removeClass( 'oo-ui-window-ready' ).width();
2314 win
.$content
.removeClass( 'oo-ui-window-content-ready' ).width();
2318 return deferred
.promise();
2324 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2327 * @param {Object} [data] Window closing data
2328 * @return {jQuery.Promise} Promise resolved when window is torn down
2330 OO
.ui
.Window
.prototype.teardown = function ( data
) {
2333 return this.getTeardownProcess( data
).execute()
2334 .done( function () {
2335 // Force redraw by asking the browser to measure the elements' widths
2336 win
.$element
.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2337 win
.$content
.removeClass( 'oo-ui-window-content-setup' ).width();
2338 win
.toggle( false );
2343 * The Dialog class serves as the base class for the other types of dialogs.
2344 * Unless extended to include controls, the rendered dialog box is a simple window
2345 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2346 * which opens, closes, and controls the presentation of the window. See the
2347 * [OOjs UI documentation on MediaWiki] [1] for more information.
2350 * // A simple dialog window.
2351 * function MyDialog( config ) {
2352 * MyDialog.super.call( this, config );
2354 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2355 * MyDialog.prototype.initialize = function () {
2356 * MyDialog.super.prototype.initialize.call( this );
2357 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2358 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2359 * this.$body.append( this.content.$element );
2361 * MyDialog.prototype.getBodyHeight = function () {
2362 * return this.content.$element.outerHeight( true );
2364 * var myDialog = new MyDialog( {
2367 * // Create and append a window manager, which opens and closes the window.
2368 * var windowManager = new OO.ui.WindowManager();
2369 * $( 'body' ).append( windowManager.$element );
2370 * windowManager.addWindows( [ myDialog ] );
2371 * // Open the window!
2372 * windowManager.openWindow( myDialog );
2374 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2378 * @extends OO.ui.Window
2379 * @mixins OO.ui.PendingElement
2382 * @param {Object} [config] Configuration options
2384 OO
.ui
.Dialog
= function OoUiDialog( config
) {
2385 // Parent constructor
2386 OO
.ui
.Dialog
.super.call( this, config
);
2388 // Mixin constructors
2389 OO
.ui
.PendingElement
.call( this );
2392 this.actions
= new OO
.ui
.ActionSet();
2393 this.attachedActions
= [];
2394 this.currentAction
= null;
2395 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
2398 this.actions
.connect( this, {
2399 click
: 'onActionClick',
2400 resize
: 'onActionResize',
2401 change
: 'onActionsChange'
2406 .addClass( 'oo-ui-dialog' )
2407 .attr( 'role', 'dialog' );
2412 OO
.inheritClass( OO
.ui
.Dialog
, OO
.ui
.Window
);
2413 OO
.mixinClass( OO
.ui
.Dialog
, OO
.ui
.PendingElement
);
2415 /* Static Properties */
2418 * Symbolic name of dialog.
2420 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2421 * Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
2423 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2428 * @property {string}
2430 OO
.ui
.Dialog
.static.name
= '';
2435 * The title can be specified as a plaintext string, a {@link OO.ui.LabelElement Label} node, or a function
2436 * that will produce a Label node or string. The title can also be specified with data passed to the
2437 * constructor (see #getSetupProcess). In this case, the static value will be overriden.
2442 * @property {jQuery|string|Function}
2444 OO
.ui
.Dialog
.static.title
= '';
2447 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2449 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2450 * value will be overriden.
2452 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
2456 * @property {Object[]}
2458 OO
.ui
.Dialog
.static.actions
= [];
2461 * Close the dialog when the 'Esc' key is pressed.
2466 * @property {boolean}
2468 OO
.ui
.Dialog
.static.escapable
= true;
2473 * Handle frame document key down events.
2476 * @param {jQuery.Event} e Key down event
2478 OO
.ui
.Dialog
.prototype.onDocumentKeyDown = function ( e
) {
2479 if ( e
.which
=== OO
.ui
.Keys
.ESCAPE
) {
2482 e
.stopPropagation();
2487 * Handle action resized events.
2490 * @param {OO.ui.ActionWidget} action Action that was resized
2492 OO
.ui
.Dialog
.prototype.onActionResize = function () {
2493 // Override in subclass
2497 * Handle action click events.
2500 * @param {OO.ui.ActionWidget} action Action that was clicked
2502 OO
.ui
.Dialog
.prototype.onActionClick = function ( action
) {
2503 if ( !this.isPending() ) {
2504 this.executeAction( action
.getAction() );
2509 * Handle actions change event.
2513 OO
.ui
.Dialog
.prototype.onActionsChange = function () {
2514 this.detachActions();
2515 if ( !this.isClosing() ) {
2516 this.attachActions();
2521 * Get the set of actions used by the dialog.
2523 * @return {OO.ui.ActionSet}
2525 OO
.ui
.Dialog
.prototype.getActions = function () {
2526 return this.actions
;
2530 * Get a process for taking action.
2532 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
2533 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
2534 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
2537 * @param {string} [action] Symbolic name of action
2538 * @return {OO.ui.Process} Action process
2540 OO
.ui
.Dialog
.prototype.getActionProcess = function ( action
) {
2541 return new OO
.ui
.Process()
2542 .next( function () {
2544 // An empty action always closes the dialog without data, which should always be
2545 // safe and make no changes
2554 * @param {Object} [data] Dialog opening data
2555 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
2556 * the {@link #static-title static title}
2557 * @param {Object[]} [data.actions] List of configuration options for each
2558 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
2560 OO
.ui
.Dialog
.prototype.getSetupProcess = function ( data
) {
2564 return OO
.ui
.Dialog
.super.prototype.getSetupProcess
.call( this, data
)
2565 .next( function () {
2566 var config
= this.constructor.static,
2567 actions
= data
.actions
!== undefined ? data
.actions
: config
.actions
;
2569 this.title
.setLabel(
2570 data
.title
!== undefined ? data
.title
: this.constructor.static.title
2572 this.actions
.add( this.getActionWidgets( actions
) );
2574 if ( this.constructor.static.escapable
) {
2575 this.$document
.on( 'keydown', this.onDocumentKeyDownHandler
);
2583 OO
.ui
.Dialog
.prototype.getTeardownProcess = function ( data
) {
2585 return OO
.ui
.Dialog
.super.prototype.getTeardownProcess
.call( this, data
)
2586 .first( function () {
2587 if ( this.constructor.static.escapable
) {
2588 this.$document
.off( 'keydown', this.onDocumentKeyDownHandler
);
2591 this.actions
.clear();
2592 this.currentAction
= null;
2599 OO
.ui
.Dialog
.prototype.initialize = function () {
2601 OO
.ui
.Dialog
.super.prototype.initialize
.call( this );
2604 this.title
= new OO
.ui
.LabelWidget();
2607 this.$content
.addClass( 'oo-ui-dialog-content' );
2608 this.setPendingElement( this.$head
);
2612 * Get action widgets from a list of configs
2614 * @param {Object[]} actions Action widget configs
2615 * @return {OO.ui.ActionWidget[]} Action widgets
2617 OO
.ui
.Dialog
.prototype.getActionWidgets = function ( actions
) {
2618 var i
, len
, widgets
= [];
2619 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
2621 new OO
.ui
.ActionWidget( actions
[ i
] )
2628 * Attach action actions.
2632 OO
.ui
.Dialog
.prototype.attachActions = function () {
2633 // Remember the list of potentially attached actions
2634 this.attachedActions
= this.actions
.get();
2638 * Detach action actions.
2643 OO
.ui
.Dialog
.prototype.detachActions = function () {
2646 // Detach all actions that may have been previously attached
2647 for ( i
= 0, len
= this.attachedActions
.length
; i
< len
; i
++ ) {
2648 this.attachedActions
[ i
].$element
.detach();
2650 this.attachedActions
= [];
2654 * Execute an action.
2656 * @param {string} action Symbolic name of action to execute
2657 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
2659 OO
.ui
.Dialog
.prototype.executeAction = function ( action
) {
2661 this.currentAction
= action
;
2662 return this.getActionProcess( action
).execute()
2663 .always( this.popPending
.bind( this ) );
2667 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
2668 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
2669 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
2670 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
2671 * pertinent data and reused.
2673 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
2674 * `opened`, and `closing`, which represent the primary stages of the cycle:
2676 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
2677 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
2679 * - an `opening` event is emitted with an `opening` promise
2680 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
2681 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
2682 * window and its result executed
2683 * - a `setup` progress notification is emitted from the `opening` promise
2684 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
2685 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
2686 * window and its result executed
2687 * - a `ready` progress notification is emitted from the `opening` promise
2688 * - the `opening` promise is resolved with an `opened` promise
2690 * **Opened**: the window is now open.
2692 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
2693 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
2694 * to close the window.
2696 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
2697 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
2698 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
2699 * window and its result executed
2700 * - a `hold` progress notification is emitted from the `closing` promise
2701 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
2702 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
2703 * window and its result executed
2704 * - a `teardown` progress notification is emitted from the `closing` promise
2705 * - the `closing` promise is resolved. The window is now closed
2707 * See the [OOjs UI documentation on MediaWiki][1] for more information.
2709 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2712 * @extends OO.ui.Element
2713 * @mixins OO.EventEmitter
2716 * @param {Object} [config] Configuration options
2717 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
2718 * Note that window classes that are instantiated with a factory must have
2719 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
2720 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
2722 OO
.ui
.WindowManager
= function OoUiWindowManager( config
) {
2723 // Configuration initialization
2724 config
= config
|| {};
2726 // Parent constructor
2727 OO
.ui
.WindowManager
.super.call( this, config
);
2729 // Mixin constructors
2730 OO
.EventEmitter
.call( this );
2733 this.factory
= config
.factory
;
2734 this.modal
= config
.modal
=== undefined || !!config
.modal
;
2736 this.opening
= null;
2738 this.closing
= null;
2739 this.preparingToOpen
= null;
2740 this.preparingToClose
= null;
2741 this.currentWindow
= null;
2742 this.globalEvents
= false;
2743 this.$ariaHidden
= null;
2744 this.onWindowResizeTimeout
= null;
2745 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
2746 this.afterWindowResizeHandler
= this.afterWindowResize
.bind( this );
2750 .addClass( 'oo-ui-windowManager' )
2751 .toggleClass( 'oo-ui-windowManager-modal', this.modal
);
2756 OO
.inheritClass( OO
.ui
.WindowManager
, OO
.ui
.Element
);
2757 OO
.mixinClass( OO
.ui
.WindowManager
, OO
.EventEmitter
);
2762 * An 'opening' event is emitted when the window begins to be opened.
2765 * @param {OO.ui.Window} win Window that's being opened
2766 * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
2767 * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
2768 * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
2769 * @param {Object} data Window opening data
2773 * A 'closing' event is emitted when the window begins to be closed.
2776 * @param {OO.ui.Window} win Window that's being closed
2777 * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
2778 * is closed successfully. The promise emits `hold` and `teardown` notifications when those
2779 * processes are complete. When the `closing` promise is resolved, the first argument of its value
2780 * is the closing data.
2781 * @param {Object} data Window closing data
2785 * A 'resize' event is emitted when a window is resized.
2788 * @param {OO.ui.Window} win Window that was resized
2791 /* Static Properties */
2794 * Map of the symbolic name of each window size and its CSS properties.
2798 * @property {Object}
2800 OO
.ui
.WindowManager
.static.sizes
= {
2814 // These can be non-numeric because they are never used in calculations
2821 * Symbolic name of the default window size.
2823 * The default size is used if the window's requested size is not recognized.
2827 * @property {string}
2829 OO
.ui
.WindowManager
.static.defaultSize
= 'medium';
2834 * Handle window resize events.
2837 * @param {jQuery.Event} e Window resize event
2839 OO
.ui
.WindowManager
.prototype.onWindowResize = function () {
2840 clearTimeout( this.onWindowResizeTimeout
);
2841 this.onWindowResizeTimeout
= setTimeout( this.afterWindowResizeHandler
, 200 );
2845 * Handle window resize events.
2848 * @param {jQuery.Event} e Window resize event
2850 OO
.ui
.WindowManager
.prototype.afterWindowResize = function () {
2851 if ( this.currentWindow
) {
2852 this.updateWindowSize( this.currentWindow
);
2857 * Check if window is opening.
2859 * @return {boolean} Window is opening
2861 OO
.ui
.WindowManager
.prototype.isOpening = function ( win
) {
2862 return win
=== this.currentWindow
&& !!this.opening
&& this.opening
.state() === 'pending';
2866 * Check if window is closing.
2868 * @return {boolean} Window is closing
2870 OO
.ui
.WindowManager
.prototype.isClosing = function ( win
) {
2871 return win
=== this.currentWindow
&& !!this.closing
&& this.closing
.state() === 'pending';
2875 * Check if window is opened.
2877 * @return {boolean} Window is opened
2879 OO
.ui
.WindowManager
.prototype.isOpened = function ( win
) {
2880 return win
=== this.currentWindow
&& !!this.opened
&& this.opened
.state() === 'pending';
2884 * Check if a window is being managed.
2886 * @param {OO.ui.Window} win Window to check
2887 * @return {boolean} Window is being managed
2889 OO
.ui
.WindowManager
.prototype.hasWindow = function ( win
) {
2892 for ( name
in this.windows
) {
2893 if ( this.windows
[ name
] === win
) {
2902 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
2904 * @param {OO.ui.Window} win Window being opened
2905 * @param {Object} [data] Window opening data
2906 * @return {number} Milliseconds to wait
2908 OO
.ui
.WindowManager
.prototype.getSetupDelay = function () {
2913 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
2915 * @param {OO.ui.Window} win Window being opened
2916 * @param {Object} [data] Window opening data
2917 * @return {number} Milliseconds to wait
2919 OO
.ui
.WindowManager
.prototype.getReadyDelay = function () {
2924 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
2926 * @param {OO.ui.Window} win Window being closed
2927 * @param {Object} [data] Window closing data
2928 * @return {number} Milliseconds to wait
2930 OO
.ui
.WindowManager
.prototype.getHoldDelay = function () {
2935 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
2936 * executing the ‘teardown’ process.
2938 * @param {OO.ui.Window} win Window being closed
2939 * @param {Object} [data] Window closing data
2940 * @return {number} Milliseconds to wait
2942 OO
.ui
.WindowManager
.prototype.getTeardownDelay = function () {
2943 return this.modal
? 250 : 0;
2947 * Get a window by its symbolic name.
2949 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
2950 * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
2951 * for more information about using factories.
2952 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2954 * @param {string} name Symbolic name of the window
2955 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
2956 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
2957 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
2959 OO
.ui
.WindowManager
.prototype.getWindow = function ( name
) {
2960 var deferred
= $.Deferred(),
2961 win
= this.windows
[ name
];
2963 if ( !( win
instanceof OO
.ui
.Window
) ) {
2964 if ( this.factory
) {
2965 if ( !this.factory
.lookup( name
) ) {
2966 deferred
.reject( new OO
.ui
.Error(
2967 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
2970 win
= this.factory
.create( name
);
2971 this.addWindows( [ win
] );
2972 deferred
.resolve( win
);
2975 deferred
.reject( new OO
.ui
.Error(
2976 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
2980 deferred
.resolve( win
);
2983 return deferred
.promise();
2987 * Get current window.
2989 * @return {OO.ui.Window|null} Currently opening/opened/closing window
2991 OO
.ui
.WindowManager
.prototype.getCurrentWindow = function () {
2992 return this.currentWindow
;
2998 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
2999 * @param {Object} [data] Window opening data
3000 * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
3001 * See {@link #event-opening 'opening' event} for more information about `opening` promises.
3004 OO
.ui
.WindowManager
.prototype.openWindow = function ( win
, data
) {
3006 opening
= $.Deferred();
3008 // Argument handling
3009 if ( typeof win
=== 'string' ) {
3010 return this.getWindow( win
).then( function ( win
) {
3011 return manager
.openWindow( win
, data
);
3016 if ( !this.hasWindow( win
) ) {
3017 opening
.reject( new OO
.ui
.Error(
3018 'Cannot open window: window is not attached to manager'
3020 } else if ( this.preparingToOpen
|| this.opening
|| this.opened
) {
3021 opening
.reject( new OO
.ui
.Error(
3022 'Cannot open window: another window is opening or open'
3027 if ( opening
.state() !== 'rejected' ) {
3028 // If a window is currently closing, wait for it to complete
3029 this.preparingToOpen
= $.when( this.closing
);
3030 // Ensure handlers get called after preparingToOpen is set
3031 this.preparingToOpen
.done( function () {
3032 if ( manager
.modal
) {
3033 manager
.toggleGlobalEvents( true );
3034 manager
.toggleAriaIsolation( true );
3036 manager
.currentWindow
= win
;
3037 manager
.opening
= opening
;
3038 manager
.preparingToOpen
= null;
3039 manager
.emit( 'opening', win
, opening
, data
);
3040 setTimeout( function () {
3041 win
.setup( data
).then( function () {
3042 manager
.updateWindowSize( win
);
3043 manager
.opening
.notify( { state
: 'setup' } );
3044 setTimeout( function () {
3045 win
.ready( data
).then( function () {
3046 manager
.opening
.notify( { state
: 'ready' } );
3047 manager
.opening
= null;
3048 manager
.opened
= $.Deferred();
3049 opening
.resolve( manager
.opened
.promise(), data
);
3051 }, manager
.getReadyDelay() );
3053 }, manager
.getSetupDelay() );
3057 return opening
.promise();
3063 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3064 * @param {Object} [data] Window closing data
3065 * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
3066 * See {@link #event-closing 'closing' event} for more information about closing promises.
3067 * @throws {Error} An error is thrown if the window is not managed by the window manager.
3070 OO
.ui
.WindowManager
.prototype.closeWindow = function ( win
, data
) {
3072 closing
= $.Deferred(),
3075 // Argument handling
3076 if ( typeof win
=== 'string' ) {
3077 win
= this.windows
[ win
];
3078 } else if ( !this.hasWindow( win
) ) {
3084 closing
.reject( new OO
.ui
.Error(
3085 'Cannot close window: window is not attached to manager'
3087 } else if ( win
!== this.currentWindow
) {
3088 closing
.reject( new OO
.ui
.Error(
3089 'Cannot close window: window already closed with different data'
3091 } else if ( this.preparingToClose
|| this.closing
) {
3092 closing
.reject( new OO
.ui
.Error(
3093 'Cannot close window: window already closing with different data'
3098 if ( closing
.state() !== 'rejected' ) {
3099 // If the window is currently opening, close it when it's done
3100 this.preparingToClose
= $.when( this.opening
);
3101 // Ensure handlers get called after preparingToClose is set
3102 this.preparingToClose
.done( function () {
3103 manager
.closing
= closing
;
3104 manager
.preparingToClose
= null;
3105 manager
.emit( 'closing', win
, closing
, data
);
3106 opened
= manager
.opened
;
3107 manager
.opened
= null;
3108 opened
.resolve( closing
.promise(), data
);
3109 setTimeout( function () {
3110 win
.hold( data
).then( function () {
3111 closing
.notify( { state
: 'hold' } );
3112 setTimeout( function () {
3113 win
.teardown( data
).then( function () {
3114 closing
.notify( { state
: 'teardown' } );
3115 if ( manager
.modal
) {
3116 manager
.toggleGlobalEvents( false );
3117 manager
.toggleAriaIsolation( false );
3119 manager
.closing
= null;
3120 manager
.currentWindow
= null;
3121 closing
.resolve( data
);
3123 }, manager
.getTeardownDelay() );
3125 }, manager
.getHoldDelay() );
3129 return closing
.promise();
3133 * Add windows to the window manager.
3135 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
3136 * See the [OOjs ui documentation on MediaWiki] [2] for examples.
3137 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3139 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
3140 * by reference, symbolic name, or explicitly defined symbolic names.
3141 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
3142 * explicit nor a statically configured symbolic name.
3144 OO
.ui
.WindowManager
.prototype.addWindows = function ( windows
) {
3145 var i
, len
, win
, name
, list
;
3147 if ( Array
.isArray( windows
) ) {
3148 // Convert to map of windows by looking up symbolic names from static configuration
3150 for ( i
= 0, len
= windows
.length
; i
< len
; i
++ ) {
3151 name
= windows
[ i
].constructor.static.name
;
3152 if ( typeof name
!== 'string' ) {
3153 throw new Error( 'Cannot add window' );
3155 list
[ name
] = windows
[ i
];
3157 } else if ( OO
.isPlainObject( windows
) ) {
3162 for ( name
in list
) {
3164 this.windows
[ name
] = win
.toggle( false );
3165 this.$element
.append( win
.$element
);
3166 win
.setManager( this );
3171 * Remove the specified windows from the windows manager.
3173 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
3174 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
3175 * longer listens to events, use the #destroy method.
3177 * @param {string[]} names Symbolic names of windows to remove
3178 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3179 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
3181 OO
.ui
.WindowManager
.prototype.removeWindows = function ( names
) {
3182 var i
, len
, win
, name
, cleanupWindow
,
3185 cleanup = function ( name
, win
) {
3186 delete manager
.windows
[ name
];
3187 win
.$element
.detach();
3190 for ( i
= 0, len
= names
.length
; i
< len
; i
++ ) {
3192 win
= this.windows
[ name
];
3194 throw new Error( 'Cannot remove window' );
3196 cleanupWindow
= cleanup
.bind( null, name
, win
);
3197 promises
.push( this.closeWindow( name
).then( cleanupWindow
, cleanupWindow
) );
3200 return $.when
.apply( $, promises
);
3204 * Remove all windows from the window manager.
3206 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
3207 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
3208 * To remove just a subset of windows, use the #removeWindows method.
3210 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3212 OO
.ui
.WindowManager
.prototype.clearWindows = function () {
3213 return this.removeWindows( Object
.keys( this.windows
) );
3217 * Set dialog size. In general, this method should not be called directly.
3219 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3223 OO
.ui
.WindowManager
.prototype.updateWindowSize = function ( win
) {
3224 // Bypass for non-current, and thus invisible, windows
3225 if ( win
!== this.currentWindow
) {
3229 var viewport
= OO
.ui
.Element
.static.getDimensions( win
.getElementWindow() ),
3230 sizes
= this.constructor.static.sizes
,
3231 size
= win
.getSize();
3233 if ( !sizes
[ size
] ) {
3234 size
= this.constructor.static.defaultSize
;
3236 if ( size
!== 'full' && viewport
.rect
.right
- viewport
.rect
.left
< sizes
[ size
].width
) {
3240 this.$element
.toggleClass( 'oo-ui-windowManager-fullscreen', size
=== 'full' );
3241 this.$element
.toggleClass( 'oo-ui-windowManager-floating', size
!== 'full' );
3242 win
.setDimensions( sizes
[ size
] );
3244 this.emit( 'resize', win
);
3250 * Bind or unbind global events for scrolling.
3253 * @param {boolean} [on] Bind global events
3256 OO
.ui
.WindowManager
.prototype.toggleGlobalEvents = function ( on
) {
3257 on
= on
=== undefined ? !!this.globalEvents
: !!on
;
3259 var scrollWidth
, bodyMargin
,
3260 $body
= $( this.getElementDocument().body
),
3261 // We could have multiple window managers open so only modify
3262 // the body css at the bottom of the stack
3263 stackDepth
= $body
.data( 'windowManagerGlobalEvents' ) || 0 ;
3266 if ( !this.globalEvents
) {
3267 $( this.getElementWindow() ).on( {
3268 // Start listening for top-level window dimension changes
3269 'orientationchange resize': this.onWindowResizeHandler
3271 if ( stackDepth
=== 0 ) {
3272 scrollWidth
= window
.innerWidth
- document
.documentElement
.clientWidth
;
3273 bodyMargin
= parseFloat( $body
.css( 'margin-right' ) ) || 0;
3276 'margin-right': bodyMargin
+ scrollWidth
3280 this.globalEvents
= true;
3282 } else if ( this.globalEvents
) {
3283 $( this.getElementWindow() ).off( {
3284 // Stop listening for top-level window dimension changes
3285 'orientationchange resize': this.onWindowResizeHandler
3288 if ( stackDepth
=== 0 ) {
3294 this.globalEvents
= false;
3296 $body
.data( 'windowManagerGlobalEvents', stackDepth
);
3302 * Toggle screen reader visibility of content other than the window manager.
3305 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3308 OO
.ui
.WindowManager
.prototype.toggleAriaIsolation = function ( isolate
) {
3309 isolate
= isolate
=== undefined ? !this.$ariaHidden
: !!isolate
;
3312 if ( !this.$ariaHidden
) {
3313 // Hide everything other than the window manager from screen readers
3314 this.$ariaHidden
= $( 'body' )
3316 .not( this.$element
.parentsUntil( 'body' ).last() )
3317 .attr( 'aria-hidden', '' );
3319 } else if ( this.$ariaHidden
) {
3320 // Restore screen reader visibility
3321 this.$ariaHidden
.removeAttr( 'aria-hidden' );
3322 this.$ariaHidden
= null;
3329 * Destroy the window manager.
3331 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
3332 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
3335 OO
.ui
.WindowManager
.prototype.destroy = function () {
3336 this.toggleGlobalEvents( false );
3337 this.toggleAriaIsolation( false );
3338 this.clearWindows();
3339 this.$element
.remove();
3343 * Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong
3344 * in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the
3345 * appearance and functionality of the error interface.
3347 * The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error
3348 * is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget
3349 * that initiated the failed process will be disabled.
3351 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the
3354 * For an example of error interfaces, please see the [OOjs UI documentation on MediaWiki][1].
3356 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Processes_and_errors
3361 * @param {string|jQuery} message Description of error
3362 * @param {Object} [config] Configuration options
3363 * @cfg {boolean} [recoverable=true] Error is recoverable.
3364 * By default, errors are recoverable, and users can try the process again.
3365 * @cfg {boolean} [warning=false] Error is a warning.
3366 * If the error is a warning, the error interface will include a
3367 * 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning
3368 * is not triggered a second time if the user chooses to continue.
3370 OO
.ui
.Error
= function OoUiError( message
, config
) {
3371 // Allow passing positional parameters inside the config object
3372 if ( OO
.isPlainObject( message
) && config
=== undefined ) {
3374 message
= config
.message
;
3377 // Configuration initialization
3378 config
= config
|| {};
3381 this.message
= message
instanceof jQuery
? message
: String( message
);
3382 this.recoverable
= config
.recoverable
=== undefined || !!config
.recoverable
;
3383 this.warning
= !!config
.warning
;
3388 OO
.initClass( OO
.ui
.Error
);
3393 * Check if the error is recoverable.
3395 * If the error is recoverable, users are able to try the process again.
3397 * @return {boolean} Error is recoverable
3399 OO
.ui
.Error
.prototype.isRecoverable = function () {
3400 return this.recoverable
;
3404 * Check if the error is a warning.
3406 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
3408 * @return {boolean} Error is warning
3410 OO
.ui
.Error
.prototype.isWarning = function () {
3411 return this.warning
;
3415 * Get error message as DOM nodes.
3417 * @return {jQuery} Error message in DOM nodes
3419 OO
.ui
.Error
.prototype.getMessage = function () {
3420 return this.message
instanceof jQuery
?
3421 this.message
.clone() :
3422 $( '<div>' ).text( this.message
).contents();
3426 * Get the error message text.
3428 * @return {string} Error message
3430 OO
.ui
.Error
.prototype.getMessageText = function () {
3431 return this.message
instanceof jQuery
? this.message
.text() : this.message
;
3435 * Wraps an HTML snippet for use with configuration values which default
3436 * to strings. This bypasses the default html-escaping done to string
3442 * @param {string} [content] HTML content
3444 OO
.ui
.HtmlSnippet
= function OoUiHtmlSnippet( content
) {
3446 this.content
= content
;
3451 OO
.initClass( OO
.ui
.HtmlSnippet
);
3458 * @return {string} Unchanged HTML snippet.
3460 OO
.ui
.HtmlSnippet
.prototype.toString = function () {
3461 return this.content
;
3465 * A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
3468 * - **number**: the process will wait for the specified number of milliseconds before proceeding.
3469 * - **promise**: the process will continue to the next step when the promise is successfully resolved
3470 * or stop if the promise is rejected.
3471 * - **function**: the process will execute the function. The process will stop if the function returns
3472 * either a boolean `false` or a promise that is rejected; if the function returns a number, the process
3473 * will wait for that number of milliseconds before proceeding.
3475 * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
3476 * configured, users can dismiss the error and try the process again, or not. If a process is stopped,
3477 * its remaining steps will not be performed.
3482 * @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
3483 * that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
3484 * @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
3485 * a number or promise.
3486 * @return {Object} Step object, with `callback` and `context` properties
3488 OO
.ui
.Process = function ( step
, context
) {
3493 if ( step
!== undefined ) {
3494 this.next( step
, context
);
3500 OO
.initClass( OO
.ui
.Process
);
3505 * Start the process.
3507 * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
3508 * If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
3509 * and any remaining steps are not performed.
3511 OO
.ui
.Process
.prototype.execute = function () {
3512 var i
, len
, promise
;
3515 * Continue execution.
3518 * @param {Array} step A function and the context it should be called in
3519 * @return {Function} Function that continues the process
3521 function proceed( step
) {
3522 return function () {
3523 // Execute step in the correct context
3525 result
= step
.callback
.call( step
.context
);
3527 if ( result
=== false ) {
3528 // Use rejected promise for boolean false results
3529 return $.Deferred().reject( [] ).promise();
3531 if ( typeof result
=== 'number' ) {
3533 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3535 // Use a delayed promise for numbers, expecting them to be in milliseconds
3536 deferred
= $.Deferred();
3537 setTimeout( deferred
.resolve
, result
);
3538 return deferred
.promise();
3540 if ( result
instanceof OO
.ui
.Error
) {
3541 // Use rejected promise for error
3542 return $.Deferred().reject( [ result
] ).promise();
3544 if ( Array
.isArray( result
) && result
.length
&& result
[ 0 ] instanceof OO
.ui
.Error
) {
3545 // Use rejected promise for list of errors
3546 return $.Deferred().reject( result
).promise();
3548 // Duck-type the object to see if it can produce a promise
3549 if ( result
&& $.isFunction( result
.promise
) ) {
3550 // Use a promise generated from the result
3551 return result
.promise();
3553 // Use resolved promise for other results
3554 return $.Deferred().resolve().promise();
3558 if ( this.steps
.length
) {
3559 // Generate a chain reaction of promises
3560 promise
= proceed( this.steps
[ 0 ] )();
3561 for ( i
= 1, len
= this.steps
.length
; i
< len
; i
++ ) {
3562 promise
= promise
.then( proceed( this.steps
[ i
] ) );
3565 promise
= $.Deferred().resolve().promise();
3572 * Create a process step.
3575 * @param {number|jQuery.Promise|Function} step
3577 * - Number of milliseconds to wait before proceeding
3578 * - Promise that must be resolved before proceeding
3579 * - Function to execute
3580 * - If the function returns a boolean false the process will stop
3581 * - If the function returns a promise, the process will continue to the next
3582 * step when the promise is resolved or stop if the promise is rejected
3583 * - If the function returns a number, the process will wait for that number of
3584 * milliseconds before proceeding
3585 * @param {Object} [context=null] Execution context of the function. The context is
3586 * ignored if the step is a number or promise.
3587 * @return {Object} Step object, with `callback` and `context` properties
3589 OO
.ui
.Process
.prototype.createStep = function ( step
, context
) {
3590 if ( typeof step
=== 'number' || $.isFunction( step
.promise
) ) {
3592 callback: function () {
3598 if ( $.isFunction( step
) ) {
3604 throw new Error( 'Cannot create process step: number, promise or function expected' );
3608 * Add step to the beginning of the process.
3610 * @inheritdoc #createStep
3611 * @return {OO.ui.Process} this
3614 OO
.ui
.Process
.prototype.first = function ( step
, context
) {
3615 this.steps
.unshift( this.createStep( step
, context
) );
3620 * Add step to the end of the process.
3622 * @inheritdoc #createStep
3623 * @return {OO.ui.Process} this
3626 OO
.ui
.Process
.prototype.next = function ( step
, context
) {
3627 this.steps
.push( this.createStep( step
, context
) );
3632 * Factory for tools.
3635 * @extends OO.Factory
3638 OO
.ui
.ToolFactory
= function OoUiToolFactory() {
3639 // Parent constructor
3640 OO
.ui
.ToolFactory
.super.call( this );
3645 OO
.inheritClass( OO
.ui
.ToolFactory
, OO
.Factory
);
3650 * Get tools from the factory
3652 * @param {Array} include Included tools
3653 * @param {Array} exclude Excluded tools
3654 * @param {Array} promote Promoted tools
3655 * @param {Array} demote Demoted tools
3656 * @return {string[]} List of tools
3658 OO
.ui
.ToolFactory
.prototype.getTools = function ( include
, exclude
, promote
, demote
) {
3659 var i
, len
, included
, promoted
, demoted
,
3663 // Collect included and not excluded tools
3664 included
= OO
.simpleArrayDifference( this.extract( include
), this.extract( exclude
) );
3667 promoted
= this.extract( promote
, used
);
3668 demoted
= this.extract( demote
, used
);
3671 for ( i
= 0, len
= included
.length
; i
< len
; i
++ ) {
3672 if ( !used
[ included
[ i
] ] ) {
3673 auto
.push( included
[ i
] );
3677 return promoted
.concat( auto
).concat( demoted
);
3681 * Get a flat list of names from a list of names or groups.
3683 * Tools can be specified in the following ways:
3685 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
3686 * - All tools in a group: `{ group: 'group-name' }`
3687 * - All tools: `'*'`
3690 * @param {Array|string} collection List of tools
3691 * @param {Object} [used] Object with names that should be skipped as properties; extracted
3692 * names will be added as properties
3693 * @return {string[]} List of extracted names
3695 OO
.ui
.ToolFactory
.prototype.extract = function ( collection
, used
) {
3696 var i
, len
, item
, name
, tool
,
3699 if ( collection
=== '*' ) {
3700 for ( name
in this.registry
) {
3701 tool
= this.registry
[ name
];
3703 // Only add tools by group name when auto-add is enabled
3704 tool
.static.autoAddToCatchall
&&
3705 // Exclude already used tools
3706 ( !used
|| !used
[ name
] )
3710 used
[ name
] = true;
3714 } else if ( Array
.isArray( collection
) ) {
3715 for ( i
= 0, len
= collection
.length
; i
< len
; i
++ ) {
3716 item
= collection
[ i
];
3717 // Allow plain strings as shorthand for named tools
3718 if ( typeof item
=== 'string' ) {
3719 item
= { name
: item
};
3721 if ( OO
.isPlainObject( item
) ) {
3723 for ( name
in this.registry
) {
3724 tool
= this.registry
[ name
];
3726 // Include tools with matching group
3727 tool
.static.group
=== item
.group
&&
3728 // Only add tools by group name when auto-add is enabled
3729 tool
.static.autoAddToGroup
&&
3730 // Exclude already used tools
3731 ( !used
|| !used
[ name
] )
3735 used
[ name
] = true;
3739 // Include tools with matching name and exclude already used tools
3740 } else if ( item
.name
&& ( !used
|| !used
[ item
.name
] ) ) {
3741 names
.push( item
.name
);
3743 used
[ item
.name
] = true;
3753 * Factory for tool groups.
3756 * @extends OO.Factory
3759 OO
.ui
.ToolGroupFactory
= function OoUiToolGroupFactory() {
3760 // Parent constructor
3761 OO
.Factory
.call( this );
3764 defaultClasses
= this.constructor.static.getDefaultClasses();
3766 // Register default toolgroups
3767 for ( i
= 0, l
= defaultClasses
.length
; i
< l
; i
++ ) {
3768 this.register( defaultClasses
[ i
] );
3774 OO
.inheritClass( OO
.ui
.ToolGroupFactory
, OO
.Factory
);
3776 /* Static Methods */
3779 * Get a default set of classes to be registered on construction
3781 * @return {Function[]} Default classes
3783 OO
.ui
.ToolGroupFactory
.static.getDefaultClasses = function () {
3786 OO
.ui
.ListToolGroup
,
3798 * @param {Object} [config] Configuration options
3800 OO
.ui
.Theme
= function OoUiTheme( config
) {
3801 // Configuration initialization
3802 config
= config
|| {};
3807 OO
.initClass( OO
.ui
.Theme
);
3812 * Get a list of classes to be applied to a widget.
3814 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
3815 * otherwise state transitions will not work properly.
3817 * @param {OO.ui.Element} element Element for which to get classes
3818 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
3820 OO
.ui
.Theme
.prototype.getElementClasses = function ( /* element */ ) {
3821 return { on
: [], off
: [] };
3825 * Update CSS classes provided by the theme.
3827 * For elements with theme logic hooks, this should be called any time there's a state change.
3829 * @param {OO.ui.Element} element Element for which to update classes
3830 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
3832 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
3833 var classes
= this.getElementClasses( element
);
3836 .removeClass( classes
.off
.join( ' ' ) )
3837 .addClass( classes
.on
.join( ' ' ) );
3841 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
3842 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
3843 * order in which users will navigate through the focusable elements via the "tab" key.
3846 * // TabIndexedElement is mixed into the ButtonWidget class
3847 * // to provide a tabIndex property.
3848 * var button1 = new OO.ui.ButtonWidget( {
3852 * var button2 = new OO.ui.ButtonWidget( {
3856 * var button3 = new OO.ui.ButtonWidget( {
3860 * var button4 = new OO.ui.ButtonWidget( {
3864 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
3870 * @param {Object} [config] Configuration options
3871 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
3872 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
3873 * functionality will be applied to it instead.
3874 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
3875 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
3876 * to remove the element from the tab-navigation flow.
3878 OO
.ui
.TabIndexedElement
= function OoUiTabIndexedElement( config
) {
3879 // Configuration initialization
3880 config
= $.extend( { tabIndex
: 0 }, config
);
3883 this.$tabIndexed
= null;
3884 this.tabIndex
= null;
3887 this.connect( this, { disable
: 'onDisable' } );
3890 this.setTabIndex( config
.tabIndex
);
3891 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
3896 OO
.initClass( OO
.ui
.TabIndexedElement
);
3901 * Set the element that should use the tabindex functionality.
3903 * This method is used to retarget a tabindex mixin so that its functionality applies
3904 * to the specified element. If an element is currently using the functionality, the mixin’s
3905 * effect on that element is removed before the new element is set up.
3907 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
3910 OO
.ui
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
3911 var tabIndex
= this.tabIndex
;
3912 // Remove attributes from old $tabIndexed
3913 this.setTabIndex( null );
3914 // Force update of new $tabIndexed
3915 this.$tabIndexed
= $tabIndexed
;
3916 this.tabIndex
= tabIndex
;
3917 return this.updateTabIndex();
3921 * Set the value of the tabindex.
3923 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
3926 OO
.ui
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
3927 tabIndex
= typeof tabIndex
=== 'number' ? tabIndex
: null;
3929 if ( this.tabIndex
!== tabIndex
) {
3930 this.tabIndex
= tabIndex
;
3931 this.updateTabIndex();
3938 * Update the `tabindex` attribute, in case of changes to tab index or
3944 OO
.ui
.TabIndexedElement
.prototype.updateTabIndex = function () {
3945 if ( this.$tabIndexed
) {
3946 if ( this.tabIndex
!== null ) {
3947 // Do not index over disabled elements
3948 this.$tabIndexed
.attr( {
3949 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
3950 // ChromeVox and NVDA do not seem to inherit this from parent elements
3951 'aria-disabled': this.isDisabled().toString()
3954 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
3961 * Handle disable events.
3964 * @param {boolean} disabled Element is disabled
3966 OO
.ui
.TabIndexedElement
.prototype.onDisable = function () {
3967 this.updateTabIndex();
3971 * Get the value of the tabindex.
3973 * @return {number|null} Tabindex value
3975 OO
.ui
.TabIndexedElement
.prototype.getTabIndex = function () {
3976 return this.tabIndex
;
3980 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
3981 * interface element that can be configured with access keys for accessibility.
3982 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
3984 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
3989 * @param {Object} [config] Configuration options
3990 * @cfg {jQuery} [$button] The button element created by the class.
3991 * If this configuration is omitted, the button element will use a generated `<a>`.
3992 * @cfg {boolean} [framed=true] Render the button with a frame
3993 * @cfg {string} [accessKey] Button's access key
3995 OO
.ui
.ButtonElement
= function OoUiButtonElement( config
) {
3996 // Configuration initialization
3997 config
= config
|| {};
4000 this.$button
= null;
4002 this.accessKey
= null;
4003 this.active
= false;
4004 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
4005 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
4006 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
4007 this.onKeyUpHandler
= this.onKeyUp
.bind( this );
4008 this.onClickHandler
= this.onClick
.bind( this );
4009 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
4012 this.$element
.addClass( 'oo-ui-buttonElement' );
4013 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
4014 this.setAccessKey( config
.accessKey
);
4015 this.setButtonElement( config
.$button
|| $( '<a>' ) );
4020 OO
.initClass( OO
.ui
.ButtonElement
);
4022 /* Static Properties */
4025 * Cancel mouse down events.
4027 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
4028 * Classes such as {@link OO.ui.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
4029 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
4034 * @property {boolean}
4036 OO
.ui
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
4041 * A 'click' event is emitted when the button element is clicked.
4049 * Set the button element.
4051 * This method is used to retarget a button mixin so that its functionality applies to
4052 * the specified button element instead of the one created by the class. If a button element
4053 * is already set, the method will remove the mixin’s effect on that element.
4055 * @param {jQuery} $button Element to use as button
4057 OO
.ui
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
4058 if ( this.$button
) {
4060 .removeClass( 'oo-ui-buttonElement-button' )
4061 .removeAttr( 'role accesskey' )
4063 mousedown
: this.onMouseDownHandler
,
4064 keydown
: this.onKeyDownHandler
,
4065 click
: this.onClickHandler
,
4066 keypress
: this.onKeyPressHandler
4070 this.$button
= $button
4071 .addClass( 'oo-ui-buttonElement-button' )
4072 .attr( { role
: 'button', accesskey
: this.accessKey
} )
4074 mousedown
: this.onMouseDownHandler
,
4075 keydown
: this.onKeyDownHandler
,
4076 click
: this.onClickHandler
,
4077 keypress
: this.onKeyPressHandler
4082 * Handles mouse down events.
4085 * @param {jQuery.Event} e Mouse down event
4087 OO
.ui
.ButtonElement
.prototype.onMouseDown = function ( e
) {
4088 if ( this.isDisabled() || e
.which
!== 1 ) {
4091 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
4092 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4093 // reliably remove the pressed class
4094 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
4095 // Prevent change of focus unless specifically configured otherwise
4096 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
4102 * Handles mouse up events.
4105 * @param {jQuery.Event} e Mouse up event
4107 OO
.ui
.ButtonElement
.prototype.onMouseUp = function ( e
) {
4108 if ( this.isDisabled() || e
.which
!== 1 ) {
4111 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
4112 // Stop listening for mouseup, since we only needed this once
4113 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
4117 * Handles mouse click events.
4120 * @param {jQuery.Event} e Mouse click event
4123 OO
.ui
.ButtonElement
.prototype.onClick = function ( e
) {
4124 if ( !this.isDisabled() && e
.which
=== 1 ) {
4125 this.emit( 'click' );
4131 * Handles key down events.
4134 * @param {jQuery.Event} e Key down event
4136 OO
.ui
.ButtonElement
.prototype.onKeyDown = function ( e
) {
4137 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
4140 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
4141 // Run the keyup handler no matter where the key is when the button is let go, so we can
4142 // reliably remove the pressed class
4143 this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler
, true );
4147 * Handles key up events.
4150 * @param {jQuery.Event} e Key up event
4152 OO
.ui
.ButtonElement
.prototype.onKeyUp = function ( e
) {
4153 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
4156 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
4157 // Stop listening for keyup, since we only needed this once
4158 this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler
, true );
4162 * Handles key press events.
4165 * @param {jQuery.Event} e Key press event
4168 OO
.ui
.ButtonElement
.prototype.onKeyPress = function ( e
) {
4169 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
4170 this.emit( 'click' );
4176 * Check if button has a frame.
4178 * @return {boolean} Button is framed
4180 OO
.ui
.ButtonElement
.prototype.isFramed = function () {
4185 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
4187 * @param {boolean} [framed] Make button framed, omit to toggle
4190 OO
.ui
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
4191 framed
= framed
=== undefined ? !this.framed
: !!framed
;
4192 if ( framed
!== this.framed
) {
4193 this.framed
= framed
;
4195 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
4196 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
4197 this.updateThemeClasses();
4204 * Set the button's access key.
4206 * @param {string} accessKey Button's access key, use empty string to remove
4209 OO
.ui
.ButtonElement
.prototype.setAccessKey = function ( accessKey
) {
4210 accessKey
= typeof accessKey
=== 'string' && accessKey
.length
? accessKey
: null;
4212 if ( this.accessKey
!== accessKey
) {
4213 if ( this.$button
) {
4214 if ( accessKey
!== null ) {
4215 this.$button
.attr( 'accesskey', accessKey
);
4217 this.$button
.removeAttr( 'accesskey' );
4220 this.accessKey
= accessKey
;
4227 * Set the button to its 'active' state.
4229 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
4230 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
4231 * for other button types.
4233 * @param {boolean} [value] Make button active
4236 OO
.ui
.ButtonElement
.prototype.setActive = function ( value
) {
4237 this.$element
.toggleClass( 'oo-ui-buttonElement-active', !!value
);
4242 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4243 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4244 * items from the group is done through the interface the class provides.
4245 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4247 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4253 * @param {Object} [config] Configuration options
4254 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4255 * is omitted, the group element will use a generated `<div>`.
4257 OO
.ui
.GroupElement
= function OoUiGroupElement( config
) {
4258 // Configuration initialization
4259 config
= config
|| {};
4264 this.aggregateItemEvents
= {};
4267 this.setGroupElement( config
.$group
|| $( '<div>' ) );
4273 * Set the group element.
4275 * If an element is already set, items will be moved to the new element.
4277 * @param {jQuery} $group Element to use as group
4279 OO
.ui
.GroupElement
.prototype.setGroupElement = function ( $group
) {
4282 this.$group
= $group
;
4283 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4284 this.$group
.append( this.items
[ i
].$element
);
4289 * Check if a group contains no items.
4291 * @return {boolean} Group is empty
4293 OO
.ui
.GroupElement
.prototype.isEmpty = function () {
4294 return !this.items
.length
;
4298 * Get all items in the group.
4300 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4301 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4304 * @return {OO.ui.Element[]} An array of items.
4306 OO
.ui
.GroupElement
.prototype.getItems = function () {
4307 return this.items
.slice( 0 );
4311 * Get an item by its data.
4313 * Only the first item with matching data will be returned. To return all matching items,
4314 * use the #getItemsFromData method.
4316 * @param {Object} data Item data to search for
4317 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4319 OO
.ui
.GroupElement
.prototype.getItemFromData = function ( data
) {
4321 hash
= OO
.getHash( data
);
4323 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4324 item
= this.items
[ i
];
4325 if ( hash
=== OO
.getHash( item
.getData() ) ) {
4334 * Get items by their data.
4336 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4338 * @param {Object} data Item data to search for
4339 * @return {OO.ui.Element[]} Items with equivalent data
4341 OO
.ui
.GroupElement
.prototype.getItemsFromData = function ( data
) {
4343 hash
= OO
.getHash( data
),
4346 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4347 item
= this.items
[ i
];
4348 if ( hash
=== OO
.getHash( item
.getData() ) ) {
4357 * Aggregate the events emitted by the group.
4359 * When events are aggregated, the group will listen to all contained items for the event,
4360 * and then emit the event under a new name. The new event will contain an additional leading
4361 * parameter containing the item that emitted the original event. Other arguments emitted from
4362 * the original event are passed through.
4364 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
4365 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
4366 * A `null` value will remove aggregated events.
4368 * @throws {Error} An error is thrown if aggregation already exists.
4370 OO
.ui
.GroupElement
.prototype.aggregate = function ( events
) {
4371 var i
, len
, item
, add
, remove
, itemEvent
, groupEvent
;
4373 for ( itemEvent
in events
) {
4374 groupEvent
= events
[ itemEvent
];
4376 // Remove existing aggregated event
4377 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4378 // Don't allow duplicate aggregations
4380 throw new Error( 'Duplicate item event aggregation for ' + itemEvent
);
4382 // Remove event aggregation from existing items
4383 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4384 item
= this.items
[ i
];
4385 if ( item
.connect
&& item
.disconnect
) {
4387 remove
[ itemEvent
] = [ 'emit', groupEvent
, item
];
4388 item
.disconnect( this, remove
);
4391 // Prevent future items from aggregating event
4392 delete this.aggregateItemEvents
[ itemEvent
];
4395 // Add new aggregate event
4397 // Make future items aggregate event
4398 this.aggregateItemEvents
[ itemEvent
] = groupEvent
;
4399 // Add event aggregation to existing items
4400 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4401 item
= this.items
[ i
];
4402 if ( item
.connect
&& item
.disconnect
) {
4404 add
[ itemEvent
] = [ 'emit', groupEvent
, item
];
4405 item
.connect( this, add
);
4413 * Add items to the group.
4415 * Items will be added to the end of the group array unless the optional `index` parameter specifies
4416 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
4418 * @param {OO.ui.Element[]} items An array of items to add to the group
4419 * @param {number} [index] Index of the insertion point
4422 OO
.ui
.GroupElement
.prototype.addItems = function ( items
, index
) {
4423 var i
, len
, item
, event
, events
, currentIndex
,
4426 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
4429 // Check if item exists then remove it first, effectively "moving" it
4430 currentIndex
= $.inArray( item
, this.items
);
4431 if ( currentIndex
>= 0 ) {
4432 this.removeItems( [ item
] );
4433 // Adjust index to compensate for removal
4434 if ( currentIndex
< index
) {
4439 if ( item
.connect
&& item
.disconnect
&& !$.isEmptyObject( this.aggregateItemEvents
) ) {
4441 for ( event
in this.aggregateItemEvents
) {
4442 events
[ event
] = [ 'emit', this.aggregateItemEvents
[ event
], item
];
4444 item
.connect( this, events
);
4446 item
.setElementGroup( this );
4447 itemElements
.push( item
.$element
.get( 0 ) );
4450 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
4451 this.$group
.append( itemElements
);
4452 this.items
.push
.apply( this.items
, items
);
4453 } else if ( index
=== 0 ) {
4454 this.$group
.prepend( itemElements
);
4455 this.items
.unshift
.apply( this.items
, items
);
4457 this.items
[ index
].$element
.before( itemElements
);
4458 this.items
.splice
.apply( this.items
, [ index
, 0 ].concat( items
) );
4465 * Remove the specified items from a group.
4467 * Removed items are detached (not removed) from the DOM so that they may be reused.
4468 * To remove all items from a group, you may wish to use the #clearItems method instead.
4470 * @param {OO.ui.Element[]} items An array of items to remove
4473 OO
.ui
.GroupElement
.prototype.removeItems = function ( items
) {
4474 var i
, len
, item
, index
, remove
, itemEvent
;
4476 // Remove specific items
4477 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
4479 index
= $.inArray( item
, this.items
);
4480 if ( index
!== -1 ) {
4482 item
.connect
&& item
.disconnect
&&
4483 !$.isEmptyObject( this.aggregateItemEvents
)
4486 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4487 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4489 item
.disconnect( this, remove
);
4491 item
.setElementGroup( null );
4492 this.items
.splice( index
, 1 );
4493 item
.$element
.detach();
4501 * Clear all items from the group.
4503 * Cleared items are detached from the DOM, not removed, so that they may be reused.
4504 * To remove only a subset of items from a group, use the #removeItems method.
4508 OO
.ui
.GroupElement
.prototype.clearItems = function () {
4509 var i
, len
, item
, remove
, itemEvent
;
4512 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4513 item
= this.items
[ i
];
4515 item
.connect
&& item
.disconnect
&&
4516 !$.isEmptyObject( this.aggregateItemEvents
)
4519 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4520 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4522 item
.disconnect( this, remove
);
4524 item
.setElementGroup( null );
4525 item
.$element
.detach();
4533 * DraggableElement is a mixin class used to create elements that can be clicked
4534 * and dragged by a mouse to a new position within a group. This class must be used
4535 * in conjunction with OO.ui.DraggableGroupElement, which provides a container for
4536 * the draggable elements.
4543 OO
.ui
.DraggableElement
= function OoUiDraggableElement() {
4547 // Initialize and events
4549 .attr( 'draggable', true )
4550 .addClass( 'oo-ui-draggableElement' )
4552 dragstart
: this.onDragStart
.bind( this ),
4553 dragover
: this.onDragOver
.bind( this ),
4554 dragend
: this.onDragEnd
.bind( this ),
4555 drop
: this.onDrop
.bind( this )
4559 OO
.initClass( OO
.ui
.DraggableElement
);
4566 * A dragstart event is emitted when the user clicks and begins dragging an item.
4567 * @param {OO.ui.DraggableElement} item The item the user has clicked and is dragging with the mouse.
4572 * A dragend event is emitted when the user drags an item and releases the mouse,
4573 * thus terminating the drag operation.
4578 * A drop event is emitted when the user drags an item and then releases the mouse button
4579 * over a valid target.
4582 /* Static Properties */
4585 * @inheritdoc OO.ui.ButtonElement
4587 OO
.ui
.DraggableElement
.static.cancelButtonMouseDownEvents
= false;
4592 * Respond to dragstart event.
4595 * @param {jQuery.Event} event jQuery event
4598 OO
.ui
.DraggableElement
.prototype.onDragStart = function ( e
) {
4599 var dataTransfer
= e
.originalEvent
.dataTransfer
;
4600 // Define drop effect
4601 dataTransfer
.dropEffect
= 'none';
4602 dataTransfer
.effectAllowed
= 'move';
4603 // We must set up a dataTransfer data property or Firefox seems to
4604 // ignore the fact the element is draggable.
4606 dataTransfer
.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
4608 // The above is only for firefox. No need to set a catch clause
4609 // if it fails, move on.
4611 // Add dragging class
4612 this.$element
.addClass( 'oo-ui-draggableElement-dragging' );
4614 this.emit( 'dragstart', this );
4619 * Respond to dragend event.
4624 OO
.ui
.DraggableElement
.prototype.onDragEnd = function () {
4625 this.$element
.removeClass( 'oo-ui-draggableElement-dragging' );
4626 this.emit( 'dragend' );
4630 * Handle drop event.
4633 * @param {jQuery.Event} event jQuery event
4636 OO
.ui
.DraggableElement
.prototype.onDrop = function ( e
) {
4638 this.emit( 'drop', e
);
4642 * In order for drag/drop to work, the dragover event must
4643 * return false and stop propogation.
4647 OO
.ui
.DraggableElement
.prototype.onDragOver = function ( e
) {
4653 * Store it in the DOM so we can access from the widget drag event
4656 * @param {number} Item index
4658 OO
.ui
.DraggableElement
.prototype.setIndex = function ( index
) {
4659 if ( this.index
!== index
) {
4661 this.$element
.data( 'index', index
);
4669 * @return {number} Item index
4671 OO
.ui
.DraggableElement
.prototype.getIndex = function () {
4676 * DraggableGroupElement is a mixin class used to create a group element to
4677 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
4678 * The class is used with OO.ui.DraggableElement.
4682 * @mixins OO.ui.GroupElement
4685 * @param {Object} [config] Configuration options
4686 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
4687 * should match the layout of the items. Items displayed in a single row
4688 * or in several rows should use horizontal orientation. The vertical orientation should only be
4689 * used when the items are displayed in a single column. Defaults to 'vertical'
4691 OO
.ui
.DraggableGroupElement
= function OoUiDraggableGroupElement( config
) {
4692 // Configuration initialization
4693 config
= config
|| {};
4695 // Parent constructor
4696 OO
.ui
.GroupElement
.call( this, config
);
4699 this.orientation
= config
.orientation
|| 'vertical';
4700 this.dragItem
= null;
4701 this.itemDragOver
= null;
4703 this.sideInsertion
= '';
4707 dragstart
: 'itemDragStart',
4708 dragend
: 'itemDragEnd',
4711 this.connect( this, {
4712 itemDragStart
: 'onItemDragStart',
4713 itemDrop
: 'onItemDrop',
4714 itemDragEnd
: 'onItemDragEnd'
4717 dragover
: $.proxy( this.onDragOver
, this ),
4718 dragleave
: $.proxy( this.onDragLeave
, this )
4722 if ( Array
.isArray( config
.items
) ) {
4723 this.addItems( config
.items
);
4725 this.$placeholder
= $( '<div>' )
4726 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
4728 .addClass( 'oo-ui-draggableGroupElement' )
4729 .append( this.$status
)
4730 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation
=== 'horizontal' )
4731 .prepend( this.$placeholder
);
4735 OO
.mixinClass( OO
.ui
.DraggableGroupElement
, OO
.ui
.GroupElement
);
4740 * A 'reorder' event is emitted when the order of items in the group changes.
4743 * @param {OO.ui.DraggableElement} item Reordered item
4744 * @param {number} [newIndex] New index for the item
4750 * Respond to item drag start event
4753 * @param {OO.ui.DraggableElement} item Dragged item
4755 OO
.ui
.DraggableGroupElement
.prototype.onItemDragStart = function ( item
) {
4758 // Map the index of each object
4759 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4760 this.items
[ i
].setIndex( i
);
4763 if ( this.orientation
=== 'horizontal' ) {
4764 // Set the height of the indicator
4765 this.$placeholder
.css( {
4766 height
: item
.$element
.outerHeight(),
4770 // Set the width of the indicator
4771 this.$placeholder
.css( {
4773 width
: item
.$element
.outerWidth()
4776 this.setDragItem( item
);
4780 * Respond to item drag end event
4784 OO
.ui
.DraggableGroupElement
.prototype.onItemDragEnd = function () {
4785 this.unsetDragItem();
4790 * Handle drop event and switch the order of the items accordingly
4793 * @param {OO.ui.DraggableElement} item Dropped item
4796 OO
.ui
.DraggableGroupElement
.prototype.onItemDrop = function ( item
) {
4797 var toIndex
= item
.getIndex();
4798 // Check if the dropped item is from the current group
4799 // TODO: Figure out a way to configure a list of legally droppable
4800 // elements even if they are not yet in the list
4801 if ( this.getDragItem() ) {
4802 // If the insertion point is 'after', the insertion index
4803 // is shifted to the right (or to the left in RTL, hence 'after')
4804 if ( this.sideInsertion
=== 'after' ) {
4807 // Emit change event
4808 this.emit( 'reorder', this.getDragItem(), toIndex
);
4810 this.unsetDragItem();
4811 // Return false to prevent propogation
4816 * Handle dragleave event.
4820 OO
.ui
.DraggableGroupElement
.prototype.onDragLeave = function () {
4821 // This means the item was dragged outside the widget
4824 .addClass( 'oo-ui-element-hidden' );
4828 * Respond to dragover event
4831 * @param {jQuery.Event} event Event details
4833 OO
.ui
.DraggableGroupElement
.prototype.onDragOver = function ( e
) {
4834 var dragOverObj
, $optionWidget
, itemOffset
, itemMidpoint
, itemBoundingRect
,
4835 itemSize
, cssOutput
, dragPosition
, itemIndex
, itemPosition
,
4836 clientX
= e
.originalEvent
.clientX
,
4837 clientY
= e
.originalEvent
.clientY
;
4839 // Get the OptionWidget item we are dragging over
4840 dragOverObj
= this.getElementDocument().elementFromPoint( clientX
, clientY
);
4841 $optionWidget
= $( dragOverObj
).closest( '.oo-ui-draggableElement' );
4842 if ( $optionWidget
[ 0 ] ) {
4843 itemOffset
= $optionWidget
.offset();
4844 itemBoundingRect
= $optionWidget
[ 0 ].getBoundingClientRect();
4845 itemPosition
= $optionWidget
.position();
4846 itemIndex
= $optionWidget
.data( 'index' );
4851 this.isDragging() &&
4852 itemIndex
!== this.getDragItem().getIndex()
4854 if ( this.orientation
=== 'horizontal' ) {
4855 // Calculate where the mouse is relative to the item width
4856 itemSize
= itemBoundingRect
.width
;
4857 itemMidpoint
= itemBoundingRect
.left
+ itemSize
/ 2;
4858 dragPosition
= clientX
;
4859 // Which side of the item we hover over will dictate
4860 // where the placeholder will appear, on the left or
4863 left
: dragPosition
< itemMidpoint
? itemPosition
.left
: itemPosition
.left
+ itemSize
,
4864 top
: itemPosition
.top
4867 // Calculate where the mouse is relative to the item height
4868 itemSize
= itemBoundingRect
.height
;
4869 itemMidpoint
= itemBoundingRect
.top
+ itemSize
/ 2;
4870 dragPosition
= clientY
;
4871 // Which side of the item we hover over will dictate
4872 // where the placeholder will appear, on the top or
4875 top
: dragPosition
< itemMidpoint
? itemPosition
.top
: itemPosition
.top
+ itemSize
,
4876 left
: itemPosition
.left
4879 // Store whether we are before or after an item to rearrange
4880 // For horizontal layout, we need to account for RTL, as this is flipped
4881 if ( this.orientation
=== 'horizontal' && this.$element
.css( 'direction' ) === 'rtl' ) {
4882 this.sideInsertion
= dragPosition
< itemMidpoint
? 'after' : 'before';
4884 this.sideInsertion
= dragPosition
< itemMidpoint
? 'before' : 'after';
4886 // Add drop indicator between objects
4889 .removeClass( 'oo-ui-element-hidden' );
4891 // This means the item was dragged outside the widget
4894 .addClass( 'oo-ui-element-hidden' );
4901 * Set a dragged item
4903 * @param {OO.ui.DraggableElement} item Dragged item
4905 OO
.ui
.DraggableGroupElement
.prototype.setDragItem = function ( item
) {
4906 this.dragItem
= item
;
4910 * Unset the current dragged item
4912 OO
.ui
.DraggableGroupElement
.prototype.unsetDragItem = function () {
4913 this.dragItem
= null;
4914 this.itemDragOver
= null;
4915 this.$placeholder
.addClass( 'oo-ui-element-hidden' );
4916 this.sideInsertion
= '';
4920 * Get the item that is currently being dragged.
4922 * @return {OO.ui.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
4924 OO
.ui
.DraggableGroupElement
.prototype.getDragItem = function () {
4925 return this.dragItem
;
4929 * Check if an item in the group is currently being dragged.
4931 * @return {Boolean} Item is being dragged
4933 OO
.ui
.DraggableGroupElement
.prototype.isDragging = function () {
4934 return this.getDragItem() !== null;
4938 * IconElement is often mixed into other classes to generate an icon.
4939 * Icons are graphics, about the size of normal text. They are used to aid the user
4940 * in locating a control or to convey information in a space-efficient way. See the
4941 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
4942 * included in the library.
4944 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
4950 * @param {Object} [config] Configuration options
4951 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
4952 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
4953 * the icon element be set to an existing icon instead of the one generated by this class, set a
4954 * value using a jQuery selection. For example:
4956 * // Use a <div> tag instead of a <span>
4958 * // Use an existing icon element instead of the one generated by the class
4959 * $icon: this.$element
4960 * // Use an icon element from a child widget
4961 * $icon: this.childwidget.$element
4962 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
4963 * symbolic names. A map is used for i18n purposes and contains a `default` icon
4964 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
4965 * by the user's language.
4967 * Example of an i18n map:
4969 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
4970 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
4971 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
4972 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
4973 * text. The icon title is displayed when users move the mouse over the icon.
4975 OO
.ui
.IconElement
= function OoUiIconElement( config
) {
4976 // Configuration initialization
4977 config
= config
|| {};
4982 this.iconTitle
= null;
4985 this.setIcon( config
.icon
|| this.constructor.static.icon
);
4986 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
4987 this.setIconElement( config
.$icon
|| $( '<span>' ) );
4992 OO
.initClass( OO
.ui
.IconElement
);
4994 /* Static Properties */
4997 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
4998 * for i18n purposes and contains a `default` icon name and additional names keyed by
4999 * language code. The `default` name is used when no icon is keyed by the user's language.
5001 * Example of an i18n map:
5003 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5005 * Note: the static property will be overridden if the #icon configuration is used.
5009 * @property {Object|string}
5011 OO
.ui
.IconElement
.static.icon
= null;
5014 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
5015 * function that returns title text, or `null` for no title.
5017 * The static property will be overridden if the #iconTitle configuration is used.
5021 * @property {string|Function|null}
5023 OO
.ui
.IconElement
.static.iconTitle
= null;
5028 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
5029 * applies to the specified icon element instead of the one created by the class. If an icon
5030 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
5031 * and mixin methods will no longer affect the element.
5033 * @param {jQuery} $icon Element to use as icon
5035 OO
.ui
.IconElement
.prototype.setIconElement = function ( $icon
) {
5038 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
5039 .removeAttr( 'title' );
5043 .addClass( 'oo-ui-iconElement-icon' )
5044 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
5045 if ( this.iconTitle
!== null ) {
5046 this.$icon
.attr( 'title', this.iconTitle
);
5051 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
5052 * The icon parameter can also be set to a map of icon names. See the #icon config setting
5055 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
5056 * by language code, or `null` to remove the icon.
5059 OO
.ui
.IconElement
.prototype.setIcon = function ( icon
) {
5060 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
5061 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
5063 if ( this.icon
!== icon
) {
5065 if ( this.icon
!== null ) {
5066 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
5068 if ( icon
!== null ) {
5069 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
5075 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
5076 this.updateThemeClasses();
5082 * Set the icon title. Use `null` to remove the title.
5084 * @param {string|Function|null} iconTitle A text string used as the icon title,
5085 * a function that returns title text, or `null` for no title.
5088 OO
.ui
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
5089 iconTitle
= typeof iconTitle
=== 'function' ||
5090 ( typeof iconTitle
=== 'string' && iconTitle
.length
) ?
5091 OO
.ui
.resolveMsg( iconTitle
) : null;
5093 if ( this.iconTitle
!== iconTitle
) {
5094 this.iconTitle
= iconTitle
;
5096 if ( this.iconTitle
!== null ) {
5097 this.$icon
.attr( 'title', iconTitle
);
5099 this.$icon
.removeAttr( 'title' );
5108 * Get the symbolic name of the icon.
5110 * @return {string} Icon name
5112 OO
.ui
.IconElement
.prototype.getIcon = function () {
5117 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5119 * @return {string} Icon title text
5121 OO
.ui
.IconElement
.prototype.getIconTitle = function () {
5122 return this.iconTitle
;
5126 * IndicatorElement is often mixed into other classes to generate an indicator.
5127 * Indicators are small graphics that are generally used in two ways:
5129 * - To draw attention to the status of an item. For example, an indicator might be
5130 * used to show that an item in a list has errors that need to be resolved.
5131 * - To clarify the function of a control that acts in an exceptional way (a button
5132 * that opens a menu instead of performing an action directly, for example).
5134 * For a list of indicators included in the library, please see the
5135 * [OOjs UI documentation on MediaWiki] [1].
5137 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5143 * @param {Object} [config] Configuration options
5144 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5145 * configuration is omitted, the indicator element will use a generated `<span>`.
5146 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5147 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5149 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5150 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5151 * or a function that returns title text. The indicator title is displayed when users move
5152 * the mouse over the indicator.
5154 OO
.ui
.IndicatorElement
= function OoUiIndicatorElement( config
) {
5155 // Configuration initialization
5156 config
= config
|| {};
5159 this.$indicator
= null;
5160 this.indicator
= null;
5161 this.indicatorTitle
= null;
5164 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
5165 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
5166 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
5171 OO
.initClass( OO
.ui
.IndicatorElement
);
5173 /* Static Properties */
5176 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5177 * The static property will be overridden if the #indicator configuration is used.
5181 * @property {string|null}
5183 OO
.ui
.IndicatorElement
.static.indicator
= null;
5186 * A text string used as the indicator title, a function that returns title text, or `null`
5187 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5191 * @property {string|Function|null}
5193 OO
.ui
.IndicatorElement
.static.indicatorTitle
= null;
5198 * Set the indicator element.
5200 * If an element is already set, it will be cleaned up before setting up the new element.
5202 * @param {jQuery} $indicator Element to use as indicator
5204 OO
.ui
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
5205 if ( this.$indicator
) {
5207 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
5208 .removeAttr( 'title' );
5211 this.$indicator
= $indicator
5212 .addClass( 'oo-ui-indicatorElement-indicator' )
5213 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
5214 if ( this.indicatorTitle
!== null ) {
5215 this.$indicator
.attr( 'title', this.indicatorTitle
);
5220 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5222 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5225 OO
.ui
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
5226 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
5228 if ( this.indicator
!== indicator
) {
5229 if ( this.$indicator
) {
5230 if ( this.indicator
!== null ) {
5231 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
5233 if ( indicator
!== null ) {
5234 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
5237 this.indicator
= indicator
;
5240 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
5241 this.updateThemeClasses();
5247 * Set the indicator title.
5249 * The title is displayed when a user moves the mouse over the indicator.
5251 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5252 * `null` for no indicator title
5255 OO
.ui
.IndicatorElement
.prototype.setIndicatorTitle = function ( indicatorTitle
) {
5256 indicatorTitle
= typeof indicatorTitle
=== 'function' ||
5257 ( typeof indicatorTitle
=== 'string' && indicatorTitle
.length
) ?
5258 OO
.ui
.resolveMsg( indicatorTitle
) : null;
5260 if ( this.indicatorTitle
!== indicatorTitle
) {
5261 this.indicatorTitle
= indicatorTitle
;
5262 if ( this.$indicator
) {
5263 if ( this.indicatorTitle
!== null ) {
5264 this.$indicator
.attr( 'title', indicatorTitle
);
5266 this.$indicator
.removeAttr( 'title' );
5275 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5277 * @return {string} Symbolic name of indicator
5279 OO
.ui
.IndicatorElement
.prototype.getIndicator = function () {
5280 return this.indicator
;
5284 * Get the indicator title.
5286 * The title is displayed when a user moves the mouse over the indicator.
5288 * @return {string} Indicator title text
5290 OO
.ui
.IndicatorElement
.prototype.getIndicatorTitle = function () {
5291 return this.indicatorTitle
;
5295 * LabelElement is often mixed into other classes to generate a label, which
5296 * helps identify the function of an interface element.
5297 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5299 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5305 * @param {Object} [config] Configuration options
5306 * @cfg {jQuery} [$label] The label element created by the class. If this
5307 * configuration is omitted, the label element will use a generated `<span>`.
5308 * @cfg {jQuery|string|Function} [label] The label text. The label can be specified as a plaintext string,
5309 * a jQuery selection of elements, or a function that will produce a string in the future. See the
5310 * [OOjs UI documentation on MediaWiki] [2] for examples.
5311 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5312 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5313 * The label will be truncated to fit if necessary.
5315 OO
.ui
.LabelElement
= function OoUiLabelElement( config
) {
5316 // Configuration initialization
5317 config
= config
|| {};
5322 this.autoFitLabel
= config
.autoFitLabel
=== undefined || !!config
.autoFitLabel
;
5325 this.setLabel( config
.label
|| this.constructor.static.label
);
5326 this.setLabelElement( config
.$label
|| $( '<span>' ) );
5331 OO
.initClass( OO
.ui
.LabelElement
);
5336 * @event labelChange
5337 * @param {string} value
5340 /* Static Properties */
5343 * The label text. The label can be specified as a plaintext string, a function that will
5344 * produce a string in the future, or `null` for no label. The static value will
5345 * be overridden if a label is specified with the #label config option.
5349 * @property {string|Function|null}
5351 OO
.ui
.LabelElement
.static.label
= null;
5356 * Set the label element.
5358 * If an element is already set, it will be cleaned up before setting up the new element.
5360 * @param {jQuery} $label Element to use as label
5362 OO
.ui
.LabelElement
.prototype.setLabelElement = function ( $label
) {
5363 if ( this.$label
) {
5364 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
5367 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
5368 this.setLabelContent( this.label
);
5374 * An empty string will result in the label being hidden. A string containing only whitespace will
5375 * be converted to a single ` `.
5377 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
5378 * text; or null for no label
5381 OO
.ui
.LabelElement
.prototype.setLabel = function ( label
) {
5382 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
5383 label
= ( ( typeof label
=== 'string' && label
.length
) || label
instanceof jQuery
|| label
instanceof OO
.ui
.HtmlSnippet
) ? label
: null;
5385 this.$element
.toggleClass( 'oo-ui-labelElement', !!label
);
5387 if ( this.label
!== label
) {
5388 if ( this.$label
) {
5389 this.setLabelContent( label
);
5392 this.emit( 'labelChange' );
5401 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
5402 * text; or null for no label
5404 OO
.ui
.LabelElement
.prototype.getLabel = function () {
5413 OO
.ui
.LabelElement
.prototype.fitLabel = function () {
5414 if ( this.$label
&& this.$label
.autoEllipsis
&& this.autoFitLabel
) {
5415 this.$label
.autoEllipsis( { hasSpan
: false, tooltip
: true } );
5422 * Set the content of the label.
5424 * Do not call this method until after the label element has been set by #setLabelElement.
5427 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5428 * text; or null for no label
5430 OO
.ui
.LabelElement
.prototype.setLabelContent = function ( label
) {
5431 if ( typeof label
=== 'string' ) {
5432 if ( label
.match( /^\s*$/ ) ) {
5433 // Convert whitespace only string to a single non-breaking space
5434 this.$label
.html( ' ' );
5436 this.$label
.text( label
);
5438 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
5439 this.$label
.html( label
.toString() );
5440 } else if ( label
instanceof jQuery
) {
5441 this.$label
.empty().append( label
);
5443 this.$label
.empty();
5448 * LookupElement is a mixin that creates a {@link OO.ui.TextInputMenuSelectWidget menu} of suggested values for
5449 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
5450 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
5451 * from the lookup menu, that value becomes the value of the input field.
5453 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
5454 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
5455 * re-enable lookups.
5457 * See the [OOjs UI demos][1] for an example.
5459 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
5465 * @param {Object} [config] Configuration options
5466 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
5467 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
5468 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
5469 * By default, the lookup menu is not generated and displayed until the user begins to type.
5471 OO
.ui
.LookupElement
= function OoUiLookupElement( config
) {
5472 // Configuration initialization
5473 config
= config
|| {};
5476 this.$overlay
= config
.$overlay
|| this.$element
;
5477 this.lookupMenu
= new OO
.ui
.TextInputMenuSelectWidget( this, {
5480 $container
: config
.$container
5483 this.allowSuggestionsWhenEmpty
= config
.allowSuggestionsWhenEmpty
|| false;
5485 this.lookupCache
= {};
5486 this.lookupQuery
= null;
5487 this.lookupRequest
= null;
5488 this.lookupsDisabled
= false;
5489 this.lookupInputFocused
= false;
5493 focus
: this.onLookupInputFocus
.bind( this ),
5494 blur
: this.onLookupInputBlur
.bind( this ),
5495 mousedown
: this.onLookupInputMouseDown
.bind( this )
5497 this.connect( this, { change
: 'onLookupInputChange' } );
5498 this.lookupMenu
.connect( this, {
5499 toggle
: 'onLookupMenuToggle',
5500 choose
: 'onLookupMenuItemChoose'
5504 this.$element
.addClass( 'oo-ui-lookupElement' );
5505 this.lookupMenu
.$element
.addClass( 'oo-ui-lookupElement-menu' );
5506 this.$overlay
.append( this.lookupMenu
.$element
);
5512 * Handle input focus event.
5515 * @param {jQuery.Event} e Input focus event
5517 OO
.ui
.LookupElement
.prototype.onLookupInputFocus = function () {
5518 this.lookupInputFocused
= true;
5519 this.populateLookupMenu();
5523 * Handle input blur event.
5526 * @param {jQuery.Event} e Input blur event
5528 OO
.ui
.LookupElement
.prototype.onLookupInputBlur = function () {
5529 this.closeLookupMenu();
5530 this.lookupInputFocused
= false;
5534 * Handle input mouse down event.
5537 * @param {jQuery.Event} e Input mouse down event
5539 OO
.ui
.LookupElement
.prototype.onLookupInputMouseDown = function () {
5540 // Only open the menu if the input was already focused.
5541 // This way we allow the user to open the menu again after closing it with Esc
5542 // by clicking in the input. Opening (and populating) the menu when initially
5543 // clicking into the input is handled by the focus handler.
5544 if ( this.lookupInputFocused
&& !this.lookupMenu
.isVisible() ) {
5545 this.populateLookupMenu();
5550 * Handle input change event.
5553 * @param {string} value New input value
5555 OO
.ui
.LookupElement
.prototype.onLookupInputChange = function () {
5556 if ( this.lookupInputFocused
) {
5557 this.populateLookupMenu();
5562 * Handle the lookup menu being shown/hidden.
5565 * @param {boolean} visible Whether the lookup menu is now visible.
5567 OO
.ui
.LookupElement
.prototype.onLookupMenuToggle = function ( visible
) {
5569 // When the menu is hidden, abort any active request and clear the menu.
5570 // This has to be done here in addition to closeLookupMenu(), because
5571 // MenuSelectWidget will close itself when the user presses Esc.
5572 this.abortLookupRequest();
5573 this.lookupMenu
.clearItems();
5578 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
5581 * @param {OO.ui.MenuOptionWidget} item Selected item
5583 OO
.ui
.LookupElement
.prototype.onLookupMenuItemChoose = function ( item
) {
5584 this.setValue( item
.getData() );
5591 * @return {OO.ui.TextInputMenuSelectWidget}
5593 OO
.ui
.LookupElement
.prototype.getLookupMenu = function () {
5594 return this.lookupMenu
;
5598 * Disable or re-enable lookups.
5600 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
5602 * @param {boolean} disabled Disable lookups
5604 OO
.ui
.LookupElement
.prototype.setLookupsDisabled = function ( disabled
) {
5605 this.lookupsDisabled
= !!disabled
;
5609 * Open the menu. If there are no entries in the menu, this does nothing.
5614 OO
.ui
.LookupElement
.prototype.openLookupMenu = function () {
5615 if ( !this.lookupMenu
.isEmpty() ) {
5616 this.lookupMenu
.toggle( true );
5622 * Close the menu, empty it, and abort any pending request.
5627 OO
.ui
.LookupElement
.prototype.closeLookupMenu = function () {
5628 this.lookupMenu
.toggle( false );
5629 this.abortLookupRequest();
5630 this.lookupMenu
.clearItems();
5635 * Request menu items based on the input's current value, and when they arrive,
5636 * populate the menu with these items and show the menu.
5638 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
5643 OO
.ui
.LookupElement
.prototype.populateLookupMenu = function () {
5645 value
= this.getValue();
5647 if ( this.lookupsDisabled
) {
5651 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
5652 if ( !this.allowSuggestionsWhenEmpty
&& value
=== '' ) {
5653 this.closeLookupMenu();
5654 // Skip population if there is already a request pending for the current value
5655 } else if ( value
!== this.lookupQuery
) {
5656 this.getLookupMenuItems()
5657 .done( function ( items
) {
5658 widget
.lookupMenu
.clearItems();
5659 if ( items
.length
) {
5663 widget
.initializeLookupMenuSelection();
5665 widget
.lookupMenu
.toggle( false );
5668 .fail( function () {
5669 widget
.lookupMenu
.clearItems();
5677 * Select and highlight the first selectable item in the menu.
5682 OO
.ui
.LookupElement
.prototype.initializeLookupMenuSelection = function () {
5683 if ( !this.lookupMenu
.getSelectedItem() ) {
5684 this.lookupMenu
.selectItem( this.lookupMenu
.getFirstSelectableItem() );
5686 this.lookupMenu
.highlightItem( this.lookupMenu
.getSelectedItem() );
5690 * Get lookup menu items for the current query.
5693 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
5694 * the done event. If the request was aborted to make way for a subsequent request, this promise
5695 * will not be rejected: it will remain pending forever.
5697 OO
.ui
.LookupElement
.prototype.getLookupMenuItems = function () {
5699 value
= this.getValue(),
5700 deferred
= $.Deferred(),
5703 this.abortLookupRequest();
5704 if ( Object
.prototype.hasOwnProperty
.call( this.lookupCache
, value
) ) {
5705 deferred
.resolve( this.getLookupMenuOptionsFromData( this.lookupCache
[ value
] ) );
5708 this.lookupQuery
= value
;
5709 ourRequest
= this.lookupRequest
= this.getLookupRequest();
5711 .always( function () {
5712 // We need to pop pending even if this is an old request, otherwise
5713 // the widget will remain pending forever.
5714 // TODO: this assumes that an aborted request will fail or succeed soon after
5715 // being aborted, or at least eventually. It would be nice if we could popPending()
5716 // at abort time, but only if we knew that we hadn't already called popPending()
5717 // for that request.
5718 widget
.popPending();
5720 .done( function ( response
) {
5721 // If this is an old request (and aborting it somehow caused it to still succeed),
5722 // ignore its success completely
5723 if ( ourRequest
=== widget
.lookupRequest
) {
5724 widget
.lookupQuery
= null;
5725 widget
.lookupRequest
= null;
5726 widget
.lookupCache
[ value
] = widget
.getLookupCacheDataFromResponse( response
);
5727 deferred
.resolve( widget
.getLookupMenuOptionsFromData( widget
.lookupCache
[ value
] ) );
5730 .fail( function () {
5731 // If this is an old request (or a request failing because it's being aborted),
5732 // ignore its failure completely
5733 if ( ourRequest
=== widget
.lookupRequest
) {
5734 widget
.lookupQuery
= null;
5735 widget
.lookupRequest
= null;
5740 return deferred
.promise();
5744 * Abort the currently pending lookup request, if any.
5748 OO
.ui
.LookupElement
.prototype.abortLookupRequest = function () {
5749 var oldRequest
= this.lookupRequest
;
5751 // First unset this.lookupRequest to the fail handler will notice
5752 // that the request is no longer current
5753 this.lookupRequest
= null;
5754 this.lookupQuery
= null;
5760 * Get a new request object of the current lookup query value.
5764 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
5766 OO
.ui
.LookupElement
.prototype.getLookupRequest = function () {
5767 // Stub, implemented in subclass
5772 * Pre-process data returned by the request from #getLookupRequest.
5774 * The return value of this function will be cached, and any further queries for the given value
5775 * will use the cache rather than doing API requests.
5779 * @param {Mixed} response Response from server
5780 * @return {Mixed} Cached result data
5782 OO
.ui
.LookupElement
.prototype.getLookupCacheDataFromResponse = function () {
5783 // Stub, implemented in subclass
5788 * Get a list of menu option widgets from the (possibly cached) data returned by
5789 * #getLookupCacheDataFromResponse.
5793 * @param {Mixed} data Cached result data, usually an array
5794 * @return {OO.ui.MenuOptionWidget[]} Menu items
5796 OO
.ui
.LookupElement
.prototype.getLookupMenuOptionsFromData = function () {
5797 // Stub, implemented in subclass
5802 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5803 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5804 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5805 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5811 * @param {Object} [config] Configuration options
5812 * @cfg {Object} [popup] Configuration to pass to popup
5813 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5815 OO
.ui
.PopupElement
= function OoUiPopupElement( config
) {
5816 // Configuration initialization
5817 config
= config
|| {};
5820 this.popup
= new OO
.ui
.PopupWidget( $.extend(
5821 { autoClose
: true },
5823 { $autoCloseIgnore
: this.$element
}
5832 * @return {OO.ui.PopupWidget} Popup widget
5834 OO
.ui
.PopupElement
.prototype.getPopup = function () {
5839 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
5840 * additional functionality to an element created by another class. The class provides
5841 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
5842 * which are used to customize the look and feel of a widget to better describe its
5843 * importance and functionality.
5845 * The library currently contains the following styling flags for general use:
5847 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
5848 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
5849 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
5851 * The flags affect the appearance of the buttons:
5854 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
5855 * var button1 = new OO.ui.ButtonWidget( {
5856 * label: 'Constructive',
5857 * flags: 'constructive'
5859 * var button2 = new OO.ui.ButtonWidget( {
5860 * label: 'Destructive',
5861 * flags: 'destructive'
5863 * var button3 = new OO.ui.ButtonWidget( {
5864 * label: 'Progressive',
5865 * flags: 'progressive'
5867 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
5869 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
5870 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
5872 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
5878 * @param {Object} [config] Configuration options
5879 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
5880 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
5881 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
5882 * @cfg {jQuery} [$flagged] The flagged element. By default,
5883 * the flagged functionality is applied to the element created by the class ($element).
5884 * If a different element is specified, the flagged functionality will be applied to it instead.
5886 OO
.ui
.FlaggedElement
= function OoUiFlaggedElement( config
) {
5887 // Configuration initialization
5888 config
= config
|| {};
5892 this.$flagged
= null;
5895 this.setFlags( config
.flags
);
5896 this.setFlaggedElement( config
.$flagged
|| this.$element
);
5903 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
5904 * parameter contains the name of each modified flag and indicates whether it was
5907 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
5908 * that the flag was added, `false` that the flag was removed.
5914 * Set the flagged element.
5916 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
5917 * If an element is already set, the method will remove the mixin’s effect on that element.
5919 * @param {jQuery} $flagged Element that should be flagged
5921 OO
.ui
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
5922 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
5923 return 'oo-ui-flaggedElement-' + flag
;
5926 if ( this.$flagged
) {
5927 this.$flagged
.removeClass( classNames
);
5930 this.$flagged
= $flagged
.addClass( classNames
);
5934 * Check if the specified flag is set.
5936 * @param {string} flag Name of flag
5937 * @return {boolean} The flag is set
5939 OO
.ui
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
5940 return flag
in this.flags
;
5944 * Get the names of all flags set.
5946 * @return {string[]} Flag names
5948 OO
.ui
.FlaggedElement
.prototype.getFlags = function () {
5949 return Object
.keys( this.flags
);
5958 OO
.ui
.FlaggedElement
.prototype.clearFlags = function () {
5959 var flag
, className
,
5962 classPrefix
= 'oo-ui-flaggedElement-';
5964 for ( flag
in this.flags
) {
5965 className
= classPrefix
+ flag
;
5966 changes
[ flag
] = false;
5967 delete this.flags
[ flag
];
5968 remove
.push( className
);
5971 if ( this.$flagged
) {
5972 this.$flagged
.removeClass( remove
.join( ' ' ) );
5975 this.updateThemeClasses();
5976 this.emit( 'flag', changes
);
5982 * Add one or more flags.
5984 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
5985 * or an object keyed by flag name with a boolean value that indicates whether the flag should
5986 * be added (`true`) or removed (`false`).
5990 OO
.ui
.FlaggedElement
.prototype.setFlags = function ( flags
) {
5991 var i
, len
, flag
, className
,
5995 classPrefix
= 'oo-ui-flaggedElement-';
5997 if ( typeof flags
=== 'string' ) {
5998 className
= classPrefix
+ flags
;
6000 if ( !this.flags
[ flags
] ) {
6001 this.flags
[ flags
] = true;
6002 add
.push( className
);
6004 } else if ( Array
.isArray( flags
) ) {
6005 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
6007 className
= classPrefix
+ flag
;
6009 if ( !this.flags
[ flag
] ) {
6010 changes
[ flag
] = true;
6011 this.flags
[ flag
] = true;
6012 add
.push( className
);
6015 } else if ( OO
.isPlainObject( flags
) ) {
6016 for ( flag
in flags
) {
6017 className
= classPrefix
+ flag
;
6018 if ( flags
[ flag
] ) {
6020 if ( !this.flags
[ flag
] ) {
6021 changes
[ flag
] = true;
6022 this.flags
[ flag
] = true;
6023 add
.push( className
);
6027 if ( this.flags
[ flag
] ) {
6028 changes
[ flag
] = false;
6029 delete this.flags
[ flag
];
6030 remove
.push( className
);
6036 if ( this.$flagged
) {
6038 .addClass( add
.join( ' ' ) )
6039 .removeClass( remove
.join( ' ' ) );
6042 this.updateThemeClasses();
6043 this.emit( 'flag', changes
);
6049 * TitledElement is mixed into other classes to provide a `title` attribute.
6050 * Titles are rendered by the browser and are made visible when the user moves
6051 * the mouse over the element. Titles are not visible on touch devices.
6054 * // TitledElement provides a 'title' attribute to the
6055 * // ButtonWidget class
6056 * var button = new OO.ui.ButtonWidget( {
6057 * label: 'Button with Title',
6058 * title: 'I am a button'
6060 * $( 'body' ).append( button.$element );
6066 * @param {Object} [config] Configuration options
6067 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
6068 * If this config is omitted, the title functionality is applied to $element, the
6069 * element created by the class.
6070 * @cfg {string|Function} [title] The title text or a function that returns text. If
6071 * this config is omitted, the value of the {@link #static-title static title} property is used.
6073 OO
.ui
.TitledElement
= function OoUiTitledElement( config
) {
6074 // Configuration initialization
6075 config
= config
|| {};
6078 this.$titled
= null;
6082 this.setTitle( config
.title
|| this.constructor.static.title
);
6083 this.setTitledElement( config
.$titled
|| this.$element
);
6088 OO
.initClass( OO
.ui
.TitledElement
);
6090 /* Static Properties */
6093 * The title text, a function that returns text, or `null` for no title. The value of the static property
6094 * is overridden if the #title config option is used.
6098 * @property {string|Function|null}
6100 OO
.ui
.TitledElement
.static.title
= null;
6105 * Set the titled element.
6107 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6108 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6110 * @param {jQuery} $titled Element that should use the 'titled' functionality
6112 OO
.ui
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
6113 if ( this.$titled
) {
6114 this.$titled
.removeAttr( 'title' );
6117 this.$titled
= $titled
;
6119 this.$titled
.attr( 'title', this.title
);
6126 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6129 OO
.ui
.TitledElement
.prototype.setTitle = function ( title
) {
6130 title
= typeof title
=== 'string' ? OO
.ui
.resolveMsg( title
) : null;
6132 if ( this.title
!== title
) {
6133 if ( this.$titled
) {
6134 if ( title
!== null ) {
6135 this.$titled
.attr( 'title', title
);
6137 this.$titled
.removeAttr( 'title' );
6149 * @return {string} Title string
6151 OO
.ui
.TitledElement
.prototype.getTitle = function () {
6156 * Element that can be automatically clipped to visible boundaries.
6158 * Whenever the element's natural height changes, you have to call
6159 * #clip to make sure it's still clipping correctly.
6165 * @param {Object} [config] Configuration options
6166 * @cfg {jQuery} [$clippable] Nodes to clip, assigned to #$clippable, omit to use #$element
6168 OO
.ui
.ClippableElement
= function OoUiClippableElement( config
) {
6169 // Configuration initialization
6170 config
= config
|| {};
6173 this.$clippable
= null;
6174 this.clipping
= false;
6175 this.clippedHorizontally
= false;
6176 this.clippedVertically
= false;
6177 this.$clippableContainer
= null;
6178 this.$clippableScroller
= null;
6179 this.$clippableWindow
= null;
6180 this.idealWidth
= null;
6181 this.idealHeight
= null;
6182 this.onClippableContainerScrollHandler
= this.clip
.bind( this );
6183 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
6186 this.setClippableElement( config
.$clippable
|| this.$element
);
6192 * Set clippable element.
6194 * If an element is already set, it will be cleaned up before setting up the new element.
6196 * @param {jQuery} $clippable Element to make clippable
6198 OO
.ui
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
6199 if ( this.$clippable
) {
6200 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
6201 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
6202 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6205 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
6212 * Do not turn clipping on until after the element is attached to the DOM and visible.
6214 * @param {boolean} [clipping] Enable clipping, omit to toggle
6217 OO
.ui
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
6218 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
6220 if ( this.clipping
!== clipping
) {
6221 this.clipping
= clipping
;
6223 this.$clippableContainer
= $( this.getClosestScrollableElementContainer() );
6224 // If the clippable container is the root, we have to listen to scroll events and check
6225 // jQuery.scrollTop on the window because of browser inconsistencies
6226 this.$clippableScroller
= this.$clippableContainer
.is( 'html, body' ) ?
6227 $( OO
.ui
.Element
.static.getWindow( this.$clippableContainer
) ) :
6228 this.$clippableContainer
;
6229 this.$clippableScroller
.on( 'scroll', this.onClippableContainerScrollHandler
);
6230 this.$clippableWindow
= $( this.getElementWindow() )
6231 .on( 'resize', this.onClippableWindowResizeHandler
);
6232 // Initial clip after visible
6235 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
6236 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6238 this.$clippableContainer
= null;
6239 this.$clippableScroller
.off( 'scroll', this.onClippableContainerScrollHandler
);
6240 this.$clippableScroller
= null;
6241 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
6242 this.$clippableWindow
= null;
6250 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6252 * @return {boolean} Element will be clipped to the visible area
6254 OO
.ui
.ClippableElement
.prototype.isClipping = function () {
6255 return this.clipping
;
6259 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6261 * @return {boolean} Part of the element is being clipped
6263 OO
.ui
.ClippableElement
.prototype.isClipped = function () {
6264 return this.clippedHorizontally
|| this.clippedVertically
;
6268 * Check if the right of the element is being clipped by the nearest scrollable container.
6270 * @return {boolean} Part of the element is being clipped
6272 OO
.ui
.ClippableElement
.prototype.isClippedHorizontally = function () {
6273 return this.clippedHorizontally
;
6277 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6279 * @return {boolean} Part of the element is being clipped
6281 OO
.ui
.ClippableElement
.prototype.isClippedVertically = function () {
6282 return this.clippedVertically
;
6286 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6288 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6289 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6291 OO
.ui
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
6292 this.idealWidth
= width
;
6293 this.idealHeight
= height
;
6295 if ( !this.clipping
) {
6296 // Update dimensions
6297 this.$clippable
.css( { width
: width
, height
: height
} );
6299 // While clipping, idealWidth and idealHeight are not considered
6303 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6304 * the element's natural height changes.
6306 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6307 * overlapped by, the visible area of the nearest scrollable container.
6311 OO
.ui
.ClippableElement
.prototype.clip = function () {
6312 if ( !this.clipping
) {
6313 // this.$clippableContainer and this.$clippableWindow are null, so the below will fail
6317 var buffer
= 7, // Chosen by fair dice roll
6318 cOffset
= this.$clippable
.offset(),
6319 $container
= this.$clippableContainer
.is( 'html, body' ) ?
6320 this.$clippableWindow
: this.$clippableContainer
,
6321 ccOffset
= $container
.offset() || { top
: 0, left
: 0 },
6322 ccHeight
= $container
.innerHeight() - buffer
,
6323 ccWidth
= $container
.innerWidth() - buffer
,
6324 cHeight
= this.$clippable
.outerHeight() + buffer
,
6325 cWidth
= this.$clippable
.outerWidth() + buffer
,
6326 scrollTop
= this.$clippableScroller
.scrollTop(),
6327 scrollLeft
= this.$clippableScroller
.scrollLeft(),
6328 desiredWidth
= cOffset
.left
< 0 ?
6329 cWidth
+ cOffset
.left
:
6330 ( ccOffset
.left
+ scrollLeft
+ ccWidth
) - cOffset
.left
,
6331 desiredHeight
= cOffset
.top
< 0 ?
6332 cHeight
+ cOffset
.top
:
6333 ( ccOffset
.top
+ scrollTop
+ ccHeight
) - cOffset
.top
,
6334 naturalWidth
= this.$clippable
.prop( 'scrollWidth' ),
6335 naturalHeight
= this.$clippable
.prop( 'scrollHeight' ),
6336 clipWidth
= desiredWidth
< naturalWidth
,
6337 clipHeight
= desiredHeight
< naturalHeight
;
6340 this.$clippable
.css( { overflowX
: 'scroll', width
: desiredWidth
} );
6342 this.$clippable
.css( { width
: this.idealWidth
|| '', overflowX
: '' } );
6345 this.$clippable
.css( { overflowY
: 'scroll', height
: desiredHeight
} );
6347 this.$clippable
.css( { height
: this.idealHeight
|| '', overflowY
: '' } );
6350 // If we stopped clipping in at least one of the dimensions
6351 if ( !clipWidth
|| !clipHeight
) {
6352 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6355 this.clippedHorizontally
= clipWidth
;
6356 this.clippedVertically
= clipHeight
;
6362 * Generic toolbar tool.
6366 * @extends OO.ui.Widget
6367 * @mixins OO.ui.IconElement
6368 * @mixins OO.ui.FlaggedElement
6371 * @param {OO.ui.ToolGroup} toolGroup
6372 * @param {Object} [config] Configuration options
6373 * @cfg {string|Function} [title] Title text or a function that returns text
6375 OO
.ui
.Tool
= function OoUiTool( toolGroup
, config
) {
6376 // Allow passing positional parameters inside the config object
6377 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
6379 toolGroup
= config
.toolGroup
;
6382 // Configuration initialization
6383 config
= config
|| {};
6385 // Parent constructor
6386 OO
.ui
.Tool
.super.call( this, config
);
6388 // Mixin constructors
6389 OO
.ui
.IconElement
.call( this, config
);
6390 OO
.ui
.FlaggedElement
.call( this, config
);
6393 this.toolGroup
= toolGroup
;
6394 this.toolbar
= this.toolGroup
.getToolbar();
6395 this.active
= false;
6396 this.$title
= $( '<span>' );
6397 this.$accel
= $( '<span>' );
6398 this.$link
= $( '<a>' );
6402 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
6405 this.$title
.addClass( 'oo-ui-tool-title' );
6407 .addClass( 'oo-ui-tool-accel' )
6409 // This may need to be changed if the key names are ever localized,
6410 // but for now they are essentially written in English
6415 .addClass( 'oo-ui-tool-link' )
6416 .append( this.$icon
, this.$title
, this.$accel
)
6417 .prop( 'tabIndex', 0 )
6418 .attr( 'role', 'button' );
6420 .data( 'oo-ui-tool', this )
6422 'oo-ui-tool ' + 'oo-ui-tool-name-' +
6423 this.constructor.static.name
.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
6425 .append( this.$link
);
6426 this.setTitle( config
.title
|| this.constructor.static.title
);
6431 OO
.inheritClass( OO
.ui
.Tool
, OO
.ui
.Widget
);
6432 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.IconElement
);
6433 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.FlaggedElement
);
6441 /* Static Properties */
6447 OO
.ui
.Tool
.static.tagName
= 'span';
6450 * Symbolic name of tool.
6455 * @property {string}
6457 OO
.ui
.Tool
.static.name
= '';
6465 * @property {string}
6467 OO
.ui
.Tool
.static.group
= '';
6472 * Title is used as a tooltip when the tool is part of a bar tool group, or a label when the tool
6473 * is part of a list or menu tool group. If a trigger is associated with an action by the same name
6474 * as the tool, a description of its keyboard shortcut for the appropriate platform will be
6475 * appended to the title if the tool is part of a bar tool group.
6480 * @property {string|Function} Title text or a function that returns text
6482 OO
.ui
.Tool
.static.title
= '';
6485 * Tool can be automatically added to catch-all groups.
6489 * @property {boolean}
6491 OO
.ui
.Tool
.static.autoAddToCatchall
= true;
6494 * Tool can be automatically added to named groups.
6497 * @property {boolean}
6500 OO
.ui
.Tool
.static.autoAddToGroup
= true;
6503 * Check if this tool is compatible with given data.
6507 * @param {Mixed} data Data to check
6508 * @return {boolean} Tool can be used with data
6510 OO
.ui
.Tool
.static.isCompatibleWith = function () {
6517 * Handle the toolbar state being updated.
6519 * This is an abstract method that must be overridden in a concrete subclass.
6523 OO
.ui
.Tool
.prototype.onUpdateState = function () {
6525 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
6530 * Handle the tool being selected.
6532 * This is an abstract method that must be overridden in a concrete subclass.
6536 OO
.ui
.Tool
.prototype.onSelect = function () {
6538 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
6543 * Check if the button is active.
6545 * @return {boolean} Button is active
6547 OO
.ui
.Tool
.prototype.isActive = function () {
6552 * Make the button appear active or inactive.
6554 * @param {boolean} state Make button appear active
6556 OO
.ui
.Tool
.prototype.setActive = function ( state
) {
6557 this.active
= !!state
;
6558 if ( this.active
) {
6559 this.$element
.addClass( 'oo-ui-tool-active' );
6561 this.$element
.removeClass( 'oo-ui-tool-active' );
6566 * Get the tool title.
6568 * @param {string|Function} title Title text or a function that returns text
6571 OO
.ui
.Tool
.prototype.setTitle = function ( title
) {
6572 this.title
= OO
.ui
.resolveMsg( title
);
6578 * Get the tool title.
6580 * @return {string} Title text
6582 OO
.ui
.Tool
.prototype.getTitle = function () {
6587 * Get the tool's symbolic name.
6589 * @return {string} Symbolic name of tool
6591 OO
.ui
.Tool
.prototype.getName = function () {
6592 return this.constructor.static.name
;
6598 OO
.ui
.Tool
.prototype.updateTitle = function () {
6599 var titleTooltips
= this.toolGroup
.constructor.static.titleTooltips
,
6600 accelTooltips
= this.toolGroup
.constructor.static.accelTooltips
,
6601 accel
= this.toolbar
.getToolAccelerator( this.constructor.static.name
),
6604 this.$title
.text( this.title
);
6605 this.$accel
.text( accel
);
6607 if ( titleTooltips
&& typeof this.title
=== 'string' && this.title
.length
) {
6608 tooltipParts
.push( this.title
);
6610 if ( accelTooltips
&& typeof accel
=== 'string' && accel
.length
) {
6611 tooltipParts
.push( accel
);
6613 if ( tooltipParts
.length
) {
6614 this.$link
.attr( 'title', tooltipParts
.join( ' ' ) );
6616 this.$link
.removeAttr( 'title' );
6623 OO
.ui
.Tool
.prototype.destroy = function () {
6624 this.toolbar
.disconnect( this );
6625 this.$element
.remove();
6629 * Collection of tool groups.
6632 * @extends OO.ui.Element
6633 * @mixins OO.EventEmitter
6634 * @mixins OO.ui.GroupElement
6637 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
6638 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating tool groups
6639 * @param {Object} [config] Configuration options
6640 * @cfg {boolean} [actions] Add an actions section opposite to the tools
6641 * @cfg {boolean} [shadow] Add a shadow below the toolbar
6643 OO
.ui
.Toolbar
= function OoUiToolbar( toolFactory
, toolGroupFactory
, config
) {
6644 // Allow passing positional parameters inside the config object
6645 if ( OO
.isPlainObject( toolFactory
) && config
=== undefined ) {
6646 config
= toolFactory
;
6647 toolFactory
= config
.toolFactory
;
6648 toolGroupFactory
= config
.toolGroupFactory
;
6651 // Configuration initialization
6652 config
= config
|| {};
6654 // Parent constructor
6655 OO
.ui
.Toolbar
.super.call( this, config
);
6657 // Mixin constructors
6658 OO
.EventEmitter
.call( this );
6659 OO
.ui
.GroupElement
.call( this, config
);
6662 this.toolFactory
= toolFactory
;
6663 this.toolGroupFactory
= toolGroupFactory
;
6666 this.$bar
= $( '<div>' );
6667 this.$actions
= $( '<div>' );
6668 this.initialized
= false;
6669 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
6673 .add( this.$bar
).add( this.$group
).add( this.$actions
)
6674 .on( 'mousedown', this.onPointerDown
.bind( this ) );
6677 this.$group
.addClass( 'oo-ui-toolbar-tools' );
6678 if ( config
.actions
) {
6679 this.$bar
.append( this.$actions
.addClass( 'oo-ui-toolbar-actions' ) );
6682 .addClass( 'oo-ui-toolbar-bar' )
6683 .append( this.$group
, '<div style="clear:both"></div>' );
6684 if ( config
.shadow
) {
6685 this.$bar
.append( '<div class="oo-ui-toolbar-shadow"></div>' );
6687 this.$element
.addClass( 'oo-ui-toolbar' ).append( this.$bar
);
6692 OO
.inheritClass( OO
.ui
.Toolbar
, OO
.ui
.Element
);
6693 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.EventEmitter
);
6694 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.ui
.GroupElement
);
6699 * Get the tool factory.
6701 * @return {OO.ui.ToolFactory} Tool factory
6703 OO
.ui
.Toolbar
.prototype.getToolFactory = function () {
6704 return this.toolFactory
;
6708 * Get the tool group factory.
6710 * @return {OO.Factory} Tool group factory
6712 OO
.ui
.Toolbar
.prototype.getToolGroupFactory = function () {
6713 return this.toolGroupFactory
;
6717 * Handles mouse down events.
6719 * @param {jQuery.Event} e Mouse down event
6721 OO
.ui
.Toolbar
.prototype.onPointerDown = function ( e
) {
6722 var $closestWidgetToEvent
= $( e
.target
).closest( '.oo-ui-widget' ),
6723 $closestWidgetToToolbar
= this.$element
.closest( '.oo-ui-widget' );
6724 if ( !$closestWidgetToEvent
.length
|| $closestWidgetToEvent
[ 0 ] === $closestWidgetToToolbar
[ 0 ] ) {
6730 * Handle window resize event.
6733 * @param {jQuery.Event} e Window resize event
6735 OO
.ui
.Toolbar
.prototype.onWindowResize = function () {
6736 this.$element
.toggleClass(
6737 'oo-ui-toolbar-narrow',
6738 this.$bar
.width() <= this.narrowThreshold
6743 * Sets up handles and preloads required information for the toolbar to work.
6744 * This must be called after it is attached to a visible document and before doing anything else.
6746 OO
.ui
.Toolbar
.prototype.initialize = function () {
6747 this.initialized
= true;
6748 this.narrowThreshold
= this.$group
.width() + this.$actions
.width();
6749 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler
);
6750 this.onWindowResize();
6756 * Tools can be specified in the following ways:
6758 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
6759 * - All tools in a group: `{ group: 'group-name' }`
6760 * - All tools: `'*'` - Using this will make the group a list with a "More" label by default
6762 * @param {Object.<string,Array>} groups List of tool group configurations
6763 * @param {Array|string} [groups.include] Tools to include
6764 * @param {Array|string} [groups.exclude] Tools to exclude
6765 * @param {Array|string} [groups.promote] Tools to promote to the beginning
6766 * @param {Array|string} [groups.demote] Tools to demote to the end
6768 OO
.ui
.Toolbar
.prototype.setup = function ( groups
) {
6769 var i
, len
, type
, group
,
6771 defaultType
= 'bar';
6773 // Cleanup previous groups
6776 // Build out new groups
6777 for ( i
= 0, len
= groups
.length
; i
< len
; i
++ ) {
6778 group
= groups
[ i
];
6779 if ( group
.include
=== '*' ) {
6780 // Apply defaults to catch-all groups
6781 if ( group
.type
=== undefined ) {
6782 group
.type
= 'list';
6784 if ( group
.label
=== undefined ) {
6785 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
6788 // Check type has been registered
6789 type
= this.getToolGroupFactory().lookup( group
.type
) ? group
.type
: defaultType
;
6791 this.getToolGroupFactory().create( type
, this, group
)
6794 this.addItems( items
);
6798 * Remove all tools and groups from the toolbar.
6800 OO
.ui
.Toolbar
.prototype.reset = function () {
6805 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6806 this.items
[ i
].destroy();
6812 * Destroys toolbar, removing event handlers and DOM elements.
6814 * Call this whenever you are done using a toolbar.
6816 OO
.ui
.Toolbar
.prototype.destroy = function () {
6817 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler
);
6819 this.$element
.remove();
6823 * Check if tool has not been used yet.
6825 * @param {string} name Symbolic name of tool
6826 * @return {boolean} Tool is available
6828 OO
.ui
.Toolbar
.prototype.isToolAvailable = function ( name
) {
6829 return !this.tools
[ name
];
6833 * Prevent tool from being used again.
6835 * @param {OO.ui.Tool} tool Tool to reserve
6837 OO
.ui
.Toolbar
.prototype.reserveTool = function ( tool
) {
6838 this.tools
[ tool
.getName() ] = tool
;
6842 * Allow tool to be used again.
6844 * @param {OO.ui.Tool} tool Tool to release
6846 OO
.ui
.Toolbar
.prototype.releaseTool = function ( tool
) {
6847 delete this.tools
[ tool
.getName() ];
6851 * Get accelerator label for tool.
6853 * This is a stub that should be overridden to provide access to accelerator information.
6855 * @param {string} name Symbolic name of tool
6856 * @return {string|undefined} Tool accelerator label if available
6858 OO
.ui
.Toolbar
.prototype.getToolAccelerator = function () {
6863 * Collection of tools.
6865 * Tools can be specified in the following ways:
6867 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
6868 * - All tools in a group: `{ group: 'group-name' }`
6869 * - All tools: `'*'`
6873 * @extends OO.ui.Widget
6874 * @mixins OO.ui.GroupElement
6877 * @param {OO.ui.Toolbar} toolbar
6878 * @param {Object} [config] Configuration options
6879 * @cfg {Array|string} [include=[]] List of tools to include
6880 * @cfg {Array|string} [exclude=[]] List of tools to exclude
6881 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning
6882 * @cfg {Array|string} [demote=[]] List of tools to demote to the end
6884 OO
.ui
.ToolGroup
= function OoUiToolGroup( toolbar
, config
) {
6885 // Allow passing positional parameters inside the config object
6886 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
6888 toolbar
= config
.toolbar
;
6891 // Configuration initialization
6892 config
= config
|| {};
6894 // Parent constructor
6895 OO
.ui
.ToolGroup
.super.call( this, config
);
6897 // Mixin constructors
6898 OO
.ui
.GroupElement
.call( this, config
);
6901 this.toolbar
= toolbar
;
6903 this.pressed
= null;
6904 this.autoDisabled
= false;
6905 this.include
= config
.include
|| [];
6906 this.exclude
= config
.exclude
|| [];
6907 this.promote
= config
.promote
|| [];
6908 this.demote
= config
.demote
|| [];
6909 this.onCapturedMouseUpHandler
= this.onCapturedMouseUp
.bind( this );
6913 mousedown
: this.onPointerDown
.bind( this ),
6914 mouseup
: this.onPointerUp
.bind( this ),
6915 mouseover
: this.onMouseOver
.bind( this ),
6916 mouseout
: this.onMouseOut
.bind( this )
6918 this.toolbar
.getToolFactory().connect( this, { register
: 'onToolFactoryRegister' } );
6919 this.aggregate( { disable
: 'itemDisable' } );
6920 this.connect( this, { itemDisable
: 'updateDisabled' } );
6923 this.$group
.addClass( 'oo-ui-toolGroup-tools' );
6925 .addClass( 'oo-ui-toolGroup' )
6926 .append( this.$group
);
6932 OO
.inheritClass( OO
.ui
.ToolGroup
, OO
.ui
.Widget
);
6933 OO
.mixinClass( OO
.ui
.ToolGroup
, OO
.ui
.GroupElement
);
6941 /* Static Properties */
6944 * Show labels in tooltips.
6948 * @property {boolean}
6950 OO
.ui
.ToolGroup
.static.titleTooltips
= false;
6953 * Show acceleration labels in tooltips.
6957 * @property {boolean}
6959 OO
.ui
.ToolGroup
.static.accelTooltips
= false;
6962 * Automatically disable the toolgroup when all tools are disabled
6966 * @property {boolean}
6968 OO
.ui
.ToolGroup
.static.autoDisable
= true;
6975 OO
.ui
.ToolGroup
.prototype.isDisabled = function () {
6976 return this.autoDisabled
|| OO
.ui
.ToolGroup
.super.prototype.isDisabled
.apply( this, arguments
);
6982 OO
.ui
.ToolGroup
.prototype.updateDisabled = function () {
6983 var i
, item
, allDisabled
= true;
6985 if ( this.constructor.static.autoDisable
) {
6986 for ( i
= this.items
.length
- 1; i
>= 0; i
-- ) {
6987 item
= this.items
[ i
];
6988 if ( !item
.isDisabled() ) {
6989 allDisabled
= false;
6993 this.autoDisabled
= allDisabled
;
6995 OO
.ui
.ToolGroup
.super.prototype.updateDisabled
.apply( this, arguments
);
6999 * Handle mouse down events.
7001 * @param {jQuery.Event} e Mouse down event
7003 OO
.ui
.ToolGroup
.prototype.onPointerDown = function ( e
) {
7004 if ( !this.isDisabled() && e
.which
=== 1 ) {
7005 this.pressed
= this.getTargetTool( e
);
7006 if ( this.pressed
) {
7007 this.pressed
.setActive( true );
7008 this.getElementDocument().addEventListener(
7009 'mouseup', this.onCapturedMouseUpHandler
, true
7017 * Handle captured mouse up events.
7019 * @param {Event} e Mouse up event
7021 OO
.ui
.ToolGroup
.prototype.onCapturedMouseUp = function ( e
) {
7022 this.getElementDocument().removeEventListener( 'mouseup', this.onCapturedMouseUpHandler
, true );
7023 // onPointerUp may be called a second time, depending on where the mouse is when the button is
7024 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
7025 this.onPointerUp( e
);
7029 * Handle mouse up events.
7031 * @param {jQuery.Event} e Mouse up event
7033 OO
.ui
.ToolGroup
.prototype.onPointerUp = function ( e
) {
7034 var tool
= this.getTargetTool( e
);
7036 if ( !this.isDisabled() && e
.which
=== 1 && this.pressed
&& this.pressed
=== tool
) {
7037 this.pressed
.onSelect();
7040 this.pressed
= null;
7045 * Handle mouse over events.
7047 * @param {jQuery.Event} e Mouse over event
7049 OO
.ui
.ToolGroup
.prototype.onMouseOver = function ( e
) {
7050 var tool
= this.getTargetTool( e
);
7052 if ( this.pressed
&& this.pressed
=== tool
) {
7053 this.pressed
.setActive( true );
7058 * Handle mouse out events.
7060 * @param {jQuery.Event} e Mouse out event
7062 OO
.ui
.ToolGroup
.prototype.onMouseOut = function ( e
) {
7063 var tool
= this.getTargetTool( e
);
7065 if ( this.pressed
&& this.pressed
=== tool
) {
7066 this.pressed
.setActive( false );
7071 * Get the closest tool to a jQuery.Event.
7073 * Only tool links are considered, which prevents other elements in the tool such as popups from
7074 * triggering tool group interactions.
7077 * @param {jQuery.Event} e
7078 * @return {OO.ui.Tool|null} Tool, `null` if none was found
7080 OO
.ui
.ToolGroup
.prototype.getTargetTool = function ( e
) {
7082 $item
= $( e
.target
).closest( '.oo-ui-tool-link' );
7084 if ( $item
.length
) {
7085 tool
= $item
.parent().data( 'oo-ui-tool' );
7088 return tool
&& !tool
.isDisabled() ? tool
: null;
7092 * Handle tool registry register events.
7094 * If a tool is registered after the group is created, we must repopulate the list to account for:
7096 * - a tool being added that may be included
7097 * - a tool already included being overridden
7099 * @param {string} name Symbolic name of tool
7101 OO
.ui
.ToolGroup
.prototype.onToolFactoryRegister = function () {
7106 * Get the toolbar this group is in.
7108 * @return {OO.ui.Toolbar} Toolbar of group
7110 OO
.ui
.ToolGroup
.prototype.getToolbar = function () {
7111 return this.toolbar
;
7115 * Add and remove tools based on configuration.
7117 OO
.ui
.ToolGroup
.prototype.populate = function () {
7118 var i
, len
, name
, tool
,
7119 toolFactory
= this.toolbar
.getToolFactory(),
7123 list
= this.toolbar
.getToolFactory().getTools(
7124 this.include
, this.exclude
, this.promote
, this.demote
7127 // Build a list of needed tools
7128 for ( i
= 0, len
= list
.length
; i
< len
; i
++ ) {
7132 toolFactory
.lookup( name
) &&
7133 // Tool is available or is already in this group
7134 ( this.toolbar
.isToolAvailable( name
) || this.tools
[ name
] )
7136 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
7137 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
7138 this.toolbar
.tools
[ name
] = true;
7139 tool
= this.tools
[ name
];
7141 // Auto-initialize tools on first use
7142 this.tools
[ name
] = tool
= toolFactory
.create( name
, this );
7145 this.toolbar
.reserveTool( tool
);
7147 names
[ name
] = true;
7150 // Remove tools that are no longer needed
7151 for ( name
in this.tools
) {
7152 if ( !names
[ name
] ) {
7153 this.tools
[ name
].destroy();
7154 this.toolbar
.releaseTool( this.tools
[ name
] );
7155 remove
.push( this.tools
[ name
] );
7156 delete this.tools
[ name
];
7159 if ( remove
.length
) {
7160 this.removeItems( remove
);
7162 // Update emptiness state
7164 this.$element
.removeClass( 'oo-ui-toolGroup-empty' );
7166 this.$element
.addClass( 'oo-ui-toolGroup-empty' );
7168 // Re-add tools (moving existing ones to new locations)
7169 this.addItems( add
);
7170 // Disabled state may depend on items
7171 this.updateDisabled();
7175 * Destroy tool group.
7177 OO
.ui
.ToolGroup
.prototype.destroy = function () {
7181 this.toolbar
.getToolFactory().disconnect( this );
7182 for ( name
in this.tools
) {
7183 this.toolbar
.releaseTool( this.tools
[ name
] );
7184 this.tools
[ name
].disconnect( this ).destroy();
7185 delete this.tools
[ name
];
7187 this.$element
.remove();
7191 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
7192 * consists of a header that contains the dialog title, a body with the message, and a footer that
7193 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
7194 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
7196 * There are two basic types of message dialogs, confirmation and alert:
7198 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
7199 * more details about the consequences.
7200 * - **alert**: the dialog title describes which event occurred and the message provides more information
7201 * about why the event occurred.
7203 * The MessageDialog class specifies two actions: ‘accept’, the primary
7204 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
7205 * passing along the selected action.
7207 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
7210 * // Example: Creating and opening a message dialog window.
7211 * var messageDialog = new OO.ui.MessageDialog();
7213 * // Create and append a window manager.
7214 * var windowManager = new OO.ui.WindowManager();
7215 * $( 'body' ).append( windowManager.$element );
7216 * windowManager.addWindows( [ messageDialog ] );
7217 * // Open the window.
7218 * windowManager.openWindow( messageDialog, {
7219 * title: 'Basic message dialog',
7220 * message: 'This is the message'
7223 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
7226 * @extends OO.ui.Dialog
7229 * @param {Object} [config] Configuration options
7231 OO
.ui
.MessageDialog
= function OoUiMessageDialog( config
) {
7232 // Parent constructor
7233 OO
.ui
.MessageDialog
.super.call( this, config
);
7236 this.verticalActionLayout
= null;
7239 this.$element
.addClass( 'oo-ui-messageDialog' );
7244 OO
.inheritClass( OO
.ui
.MessageDialog
, OO
.ui
.Dialog
);
7246 /* Static Properties */
7248 OO
.ui
.MessageDialog
.static.name
= 'message';
7250 OO
.ui
.MessageDialog
.static.size
= 'small';
7252 OO
.ui
.MessageDialog
.static.verbose
= false;
7257 * The title of a confirmation dialog describes what a progressive action will do. The
7258 * title of an alert dialog describes which event occurred.
7262 * @property {jQuery|string|Function|null}
7264 OO
.ui
.MessageDialog
.static.title
= null;
7267 * The message displayed in the dialog body.
7269 * A confirmation message describes the consequences of a progressive action. An alert
7270 * message describes why an event occurred.
7274 * @property {jQuery|string|Function|null}
7276 OO
.ui
.MessageDialog
.static.message
= null;
7278 OO
.ui
.MessageDialog
.static.actions
= [
7279 { action
: 'accept', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-accept' ), flags
: 'primary' },
7280 { action
: 'reject', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-reject' ), flags
: 'safe' }
7288 OO
.ui
.MessageDialog
.prototype.setManager = function ( manager
) {
7289 OO
.ui
.MessageDialog
.super.prototype.setManager
.call( this, manager
);
7292 this.manager
.connect( this, {
7302 OO
.ui
.MessageDialog
.prototype.onActionResize = function ( action
) {
7304 return OO
.ui
.MessageDialog
.super.prototype.onActionResize
.call( this, action
);
7308 * Handle window resized events.
7312 OO
.ui
.MessageDialog
.prototype.onResize = function () {
7314 dialog
.fitActions();
7315 // Wait for CSS transition to finish and do it again :(
7316 setTimeout( function () {
7317 dialog
.fitActions();
7322 * Toggle action layout between vertical and horizontal.
7326 * @param {boolean} [value] Layout actions vertically, omit to toggle
7329 OO
.ui
.MessageDialog
.prototype.toggleVerticalActionLayout = function ( value
) {
7330 value
= value
=== undefined ? !this.verticalActionLayout
: !!value
;
7332 if ( value
!== this.verticalActionLayout
) {
7333 this.verticalActionLayout
= value
;
7335 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value
)
7336 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value
);
7345 OO
.ui
.MessageDialog
.prototype.getActionProcess = function ( action
) {
7347 return new OO
.ui
.Process( function () {
7348 this.close( { action
: action
} );
7351 return OO
.ui
.MessageDialog
.super.prototype.getActionProcess
.call( this, action
);
7357 * @param {Object} [data] Dialog opening data
7358 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
7359 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
7360 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
7361 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
7364 OO
.ui
.MessageDialog
.prototype.getSetupProcess = function ( data
) {
7368 return OO
.ui
.MessageDialog
.super.prototype.getSetupProcess
.call( this, data
)
7369 .next( function () {
7370 this.title
.setLabel(
7371 data
.title
!== undefined ? data
.title
: this.constructor.static.title
7373 this.message
.setLabel(
7374 data
.message
!== undefined ? data
.message
: this.constructor.static.message
7376 this.message
.$element
.toggleClass(
7377 'oo-ui-messageDialog-message-verbose',
7378 data
.verbose
!== undefined ? data
.verbose
: this.constructor.static.verbose
7386 OO
.ui
.MessageDialog
.prototype.getBodyHeight = function () {
7387 var bodyHeight
, oldOverflow
,
7388 $scrollable
= this.container
.$element
;
7390 oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
7391 $scrollable
[ 0 ].style
.overflow
= 'hidden';
7393 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
7395 bodyHeight
= this.text
.$element
.outerHeight( true );
7396 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
7404 OO
.ui
.MessageDialog
.prototype.setDimensions = function ( dim
) {
7405 var $scrollable
= this.container
.$element
;
7406 OO
.ui
.MessageDialog
.super.prototype.setDimensions
.call( this, dim
);
7408 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
7409 // Need to do it after transition completes (250ms), add 50ms just in case.
7410 setTimeout( function () {
7411 var oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
7412 $scrollable
[ 0 ].style
.overflow
= 'hidden';
7414 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
7416 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
7425 OO
.ui
.MessageDialog
.prototype.initialize = function () {
7427 OO
.ui
.MessageDialog
.super.prototype.initialize
.call( this );
7430 this.$actions
= $( '<div>' );
7431 this.container
= new OO
.ui
.PanelLayout( {
7432 scrollable
: true, classes
: [ 'oo-ui-messageDialog-container' ]
7434 this.text
= new OO
.ui
.PanelLayout( {
7435 padded
: true, expanded
: false, classes
: [ 'oo-ui-messageDialog-text' ]
7437 this.message
= new OO
.ui
.LabelWidget( {
7438 classes
: [ 'oo-ui-messageDialog-message' ]
7442 this.title
.$element
.addClass( 'oo-ui-messageDialog-title' );
7443 this.$content
.addClass( 'oo-ui-messageDialog-content' );
7444 this.container
.$element
.append( this.text
.$element
);
7445 this.text
.$element
.append( this.title
.$element
, this.message
.$element
);
7446 this.$body
.append( this.container
.$element
);
7447 this.$actions
.addClass( 'oo-ui-messageDialog-actions' );
7448 this.$foot
.append( this.$actions
);
7454 OO
.ui
.MessageDialog
.prototype.attachActions = function () {
7455 var i
, len
, other
, special
, others
;
7458 OO
.ui
.MessageDialog
.super.prototype.attachActions
.call( this );
7460 special
= this.actions
.getSpecial();
7461 others
= this.actions
.getOthers();
7462 if ( special
.safe
) {
7463 this.$actions
.append( special
.safe
.$element
);
7464 special
.safe
.toggleFramed( false );
7466 if ( others
.length
) {
7467 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
7468 other
= others
[ i
];
7469 this.$actions
.append( other
.$element
);
7470 other
.toggleFramed( false );
7473 if ( special
.primary
) {
7474 this.$actions
.append( special
.primary
.$element
);
7475 special
.primary
.toggleFramed( false );
7478 if ( !this.isOpening() ) {
7479 // If the dialog is currently opening, this will be called automatically soon.
7480 // This also calls #fitActions.
7486 * Fit action actions into columns or rows.
7488 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
7492 OO
.ui
.MessageDialog
.prototype.fitActions = function () {
7494 previous
= this.verticalActionLayout
,
7495 actions
= this.actions
.get();
7498 this.toggleVerticalActionLayout( false );
7499 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
7500 action
= actions
[ i
];
7501 if ( action
.$element
.innerWidth() < action
.$label
.outerWidth( true ) ) {
7502 this.toggleVerticalActionLayout( true );
7507 // Move the body out of the way of the foot
7508 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
7510 if ( this.verticalActionLayout
!== previous
) {
7511 // We changed the layout, window height might need to be updated.
7517 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
7518 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
7519 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
7520 * relevant. The ProcessDialog class is always extended and customized with the actions and content
7521 * required for each process.
7523 * The process dialog box consists of a header that visually represents the ‘working’ state of long
7524 * processes with an animation. The header contains the dialog title as well as
7525 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
7526 * a ‘primary’ action on the right (e.g., ‘Done’).
7528 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
7529 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
7532 * // Example: Creating and opening a process dialog window.
7533 * function MyProcessDialog( config ) {
7534 * MyProcessDialog.super.call( this, config );
7536 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
7538 * MyProcessDialog.static.title = 'Process dialog';
7539 * MyProcessDialog.static.actions = [
7540 * { action: 'save', label: 'Done', flags: 'primary' },
7541 * { label: 'Cancel', flags: 'safe' }
7544 * MyProcessDialog.prototype.initialize = function () {
7545 * MyProcessDialog.super.prototype.initialize.apply( this, arguments );
7546 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
7547 * this.content.$element.append( '<p>This is a process dialog window. The header contains the title and two buttons: \'Cancel\' (a safe action) on the left and \'Done\' (a primary action) on the right.</p>' );
7548 * this.$body.append( this.content.$element );
7550 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
7551 * var dialog = this;
7553 * return new OO.ui.Process( function () {
7554 * dialog.close( { action: action } );
7557 * return MyProcessDialog.super.prototype.getActionProcess.call( this, action );
7560 * var windowManager = new OO.ui.WindowManager();
7561 * $( 'body' ).append( windowManager.$element );
7563 * var dialog = new MyProcessDialog();
7564 * windowManager.addWindows( [ dialog ] );
7565 * windowManager.openWindow( dialog );
7567 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
7571 * @extends OO.ui.Dialog
7574 * @param {Object} [config] Configuration options
7576 OO
.ui
.ProcessDialog
= function OoUiProcessDialog( config
) {
7577 // Parent constructor
7578 OO
.ui
.ProcessDialog
.super.call( this, config
);
7581 this.$element
.addClass( 'oo-ui-processDialog' );
7586 OO
.inheritClass( OO
.ui
.ProcessDialog
, OO
.ui
.Dialog
);
7591 * Handle dismiss button click events.
7597 OO
.ui
.ProcessDialog
.prototype.onDismissErrorButtonClick = function () {
7602 * Handle retry button click events.
7604 * Hides errors and then tries again.
7608 OO
.ui
.ProcessDialog
.prototype.onRetryButtonClick = function () {
7610 this.executeAction( this.currentAction
);
7616 OO
.ui
.ProcessDialog
.prototype.onActionResize = function ( action
) {
7617 if ( this.actions
.isSpecial( action
) ) {
7620 return OO
.ui
.ProcessDialog
.super.prototype.onActionResize
.call( this, action
);
7626 OO
.ui
.ProcessDialog
.prototype.initialize = function () {
7628 OO
.ui
.ProcessDialog
.super.prototype.initialize
.call( this );
7631 this.$navigation
= $( '<div>' );
7632 this.$location
= $( '<div>' );
7633 this.$safeActions
= $( '<div>' );
7634 this.$primaryActions
= $( '<div>' );
7635 this.$otherActions
= $( '<div>' );
7636 this.dismissButton
= new OO
.ui
.ButtonWidget( {
7637 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' )
7639 this.retryButton
= new OO
.ui
.ButtonWidget();
7640 this.$errors
= $( '<div>' );
7641 this.$errorsTitle
= $( '<div>' );
7644 this.dismissButton
.connect( this, { click
: 'onDismissErrorButtonClick' } );
7645 this.retryButton
.connect( this, { click
: 'onRetryButtonClick' } );
7648 this.title
.$element
.addClass( 'oo-ui-processDialog-title' );
7650 .append( this.title
.$element
)
7651 .addClass( 'oo-ui-processDialog-location' );
7652 this.$safeActions
.addClass( 'oo-ui-processDialog-actions-safe' );
7653 this.$primaryActions
.addClass( 'oo-ui-processDialog-actions-primary' );
7654 this.$otherActions
.addClass( 'oo-ui-processDialog-actions-other' );
7656 .addClass( 'oo-ui-processDialog-errors-title' )
7657 .text( OO
.ui
.msg( 'ooui-dialog-process-error' ) );
7659 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
7660 .append( this.$errorsTitle
, this.dismissButton
.$element
, this.retryButton
.$element
);
7662 .addClass( 'oo-ui-processDialog-content' )
7663 .append( this.$errors
);
7665 .addClass( 'oo-ui-processDialog-navigation' )
7666 .append( this.$safeActions
, this.$location
, this.$primaryActions
);
7667 this.$head
.append( this.$navigation
);
7668 this.$foot
.append( this.$otherActions
);
7674 OO
.ui
.ProcessDialog
.prototype.getActionWidgets = function ( actions
) {
7675 var i
, len
, widgets
= [];
7676 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
7678 new OO
.ui
.ActionWidget( $.extend( { framed
: true }, actions
[ i
] ) )
7687 OO
.ui
.ProcessDialog
.prototype.attachActions = function () {
7688 var i
, len
, other
, special
, others
;
7691 OO
.ui
.ProcessDialog
.super.prototype.attachActions
.call( this );
7693 special
= this.actions
.getSpecial();
7694 others
= this.actions
.getOthers();
7695 if ( special
.primary
) {
7696 this.$primaryActions
.append( special
.primary
.$element
);
7698 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
7699 other
= others
[ i
];
7700 this.$otherActions
.append( other
.$element
);
7702 if ( special
.safe
) {
7703 this.$safeActions
.append( special
.safe
.$element
);
7707 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
7713 OO
.ui
.ProcessDialog
.prototype.executeAction = function ( action
) {
7715 return OO
.ui
.ProcessDialog
.super.prototype.executeAction
.call( this, action
)
7716 .fail( function ( errors
) {
7717 process
.showErrors( errors
|| [] );
7722 * Fit label between actions.
7727 OO
.ui
.ProcessDialog
.prototype.fitLabel = function () {
7728 var width
= Math
.max(
7729 this.$safeActions
.is( ':visible' ) ? this.$safeActions
.width() : 0,
7730 this.$primaryActions
.is( ':visible' ) ? this.$primaryActions
.width() : 0
7732 this.$location
.css( { paddingLeft
: width
, paddingRight
: width
} );
7738 * Handle errors that occurred during accept or reject processes.
7741 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
7743 OO
.ui
.ProcessDialog
.prototype.showErrors = function ( errors
) {
7744 var i
, len
, $item
, actions
,
7750 if ( errors
instanceof OO
.ui
.Error
) {
7751 errors
= [ errors
];
7754 for ( i
= 0, len
= errors
.length
; i
< len
; i
++ ) {
7755 if ( !errors
[ i
].isRecoverable() ) {
7756 recoverable
= false;
7758 if ( errors
[ i
].isWarning() ) {
7761 $item
= $( '<div>' )
7762 .addClass( 'oo-ui-processDialog-error' )
7763 .append( errors
[ i
].getMessage() );
7764 items
.push( $item
[ 0 ] );
7766 this.$errorItems
= $( items
);
7767 if ( recoverable
) {
7768 abilities
[this.currentAction
] = true;
7769 // Copy the flags from the first matching action
7770 actions
= this.actions
.get( { actions
: this.currentAction
} );
7771 if ( actions
.length
) {
7772 this.retryButton
.clearFlags().setFlags( actions
[0].getFlags() );
7775 abilities
[this.currentAction
] = false;
7776 this.actions
.setAbilities( abilities
);
7779 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-continue' ) );
7781 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-retry' ) );
7783 this.retryButton
.toggle( recoverable
);
7784 this.$errorsTitle
.after( this.$errorItems
);
7785 this.$errors
.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
7793 OO
.ui
.ProcessDialog
.prototype.hideErrors = function () {
7794 this.$errors
.addClass( 'oo-ui-element-hidden' );
7795 if ( this.$errorItems
) {
7796 this.$errorItems
.remove();
7797 this.$errorItems
= null;
7804 OO
.ui
.ProcessDialog
.prototype.getTeardownProcess = function ( data
) {
7806 return OO
.ui
.ProcessDialog
.super.prototype.getTeardownProcess
.call( this, data
)
7807 .first( function () {
7808 // Make sure to hide errors
7814 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
7815 * which is a widget that is specified by reference before any optional configuration settings.
7817 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
7819 * - **left**: The label is placed before the field-widget and aligned with the left margin.
7820 * A left-alignment is used for forms with many fields.
7821 * - **right**: The label is placed before the field-widget and aligned to the right margin.
7822 * A right-alignment is used for long but familiar forms which users tab through,
7823 * verifying the current field with a quick glance at the label.
7824 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
7825 * that users fill out from top to bottom.
7826 * - **inline**: The label is placed after the field-widget and aligned to the left.
7827 * An inline-alignment is best used with checkboxes or radio buttons.
7829 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
7830 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
7832 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
7834 * @extends OO.ui.Layout
7835 * @mixins OO.ui.LabelElement
7838 * @param {OO.ui.Widget} fieldWidget Field widget
7839 * @param {Object} [config] Configuration options
7840 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
7841 * @cfg {string} [help] Help text. When help text is specified, a help icon will appear
7842 * in the upper-right corner of the rendered field.
7844 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
7845 // Allow passing positional parameters inside the config object
7846 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
7847 config
= fieldWidget
;
7848 fieldWidget
= config
.fieldWidget
;
7851 var hasInputWidget
= fieldWidget
instanceof OO
.ui
.InputWidget
;
7853 // Configuration initialization
7854 config
= $.extend( { align
: 'left' }, config
);
7856 // Parent constructor
7857 OO
.ui
.FieldLayout
.super.call( this, config
);
7859 // Mixin constructors
7860 OO
.ui
.LabelElement
.call( this, config
);
7863 this.fieldWidget
= fieldWidget
;
7864 this.$field
= $( '<div>' );
7865 this.$body
= $( '<' + ( hasInputWidget
? 'label' : 'div' ) + '>' );
7867 if ( config
.help
) {
7868 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
7869 classes
: [ 'oo-ui-fieldLayout-help' ],
7874 this.popupButtonWidget
.getPopup().$body
.append(
7876 .text( config
.help
)
7877 .addClass( 'oo-ui-fieldLayout-help-content' )
7879 this.$help
= this.popupButtonWidget
.$element
;
7881 this.$help
= $( [] );
7885 if ( hasInputWidget
) {
7886 this.$label
.on( 'click', this.onLabelClick
.bind( this ) );
7888 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
7892 .addClass( 'oo-ui-fieldLayout' )
7893 .append( this.$help
, this.$body
);
7894 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
7896 .addClass( 'oo-ui-fieldLayout-field' )
7897 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget
.isDisabled() )
7898 .append( this.fieldWidget
.$element
);
7900 this.setAlignment( config
.align
);
7905 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
7906 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.LabelElement
);
7911 * Handle field disable events.
7914 * @param {boolean} value Field is disabled
7916 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
7917 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
7921 * Handle label mouse click events.
7924 * @param {jQuery.Event} e Mouse click event
7926 OO
.ui
.FieldLayout
.prototype.onLabelClick = function () {
7927 this.fieldWidget
.simulateLabelClick();
7932 * Get the widget contained by the field.
7934 * @return {OO.ui.Widget} Field widget
7936 OO
.ui
.FieldLayout
.prototype.getField = function () {
7937 return this.fieldWidget
;
7941 * Set the field alignment mode.
7944 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
7947 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
7948 if ( value
!== this.align
) {
7949 // Default to 'left'
7950 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
7954 if ( value
=== 'inline' ) {
7955 this.$body
.append( this.$field
, this.$label
);
7957 this.$body
.append( this.$label
, this.$field
);
7959 // Set classes. The following classes can be used here:
7960 // * oo-ui-fieldLayout-align-left
7961 // * oo-ui-fieldLayout-align-right
7962 // * oo-ui-fieldLayout-align-top
7963 // * oo-ui-fieldLayout-align-inline
7965 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
7967 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
7975 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
7976 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
7977 * is required and is specified before any optional configuration settings.
7979 * Labels can be aligned in one of four ways:
7981 * - **left**: The label is placed before the field-widget and aligned with the left margin.
7982 * A left-alignment is used for forms with many fields.
7983 * - **right**: The label is placed before the field-widget and aligned to the right margin.
7984 * A right-alignment is used for long but familiar forms which users tab through,
7985 * verifying the current field with a quick glance at the label.
7986 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
7987 * that users fill out from top to bottom.
7988 * - **inline**: The label is placed after the field-widget and aligned to the left.
7989 * An inline-alignment is best used with checkboxes or radio buttons.
7991 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
7992 * text is specified.
7995 * // Example of an ActionFieldLayout
7996 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
7997 * new OO.ui.TextInputWidget( {
7998 * placeholder: 'Field widget'
8000 * new OO.ui.ButtonWidget( {
8004 * label: 'An ActionFieldLayout. This label is aligned top',
8006 * help: 'This is help text'
8010 * $( 'body' ).append( actionFieldLayout.$element );
8014 * @extends OO.ui.FieldLayout
8017 * @param {OO.ui.Widget} fieldWidget Field widget
8018 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
8019 * @param {Object} [config] Configuration options
8020 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
8021 * @cfg {string} [help] Help text. When help text is specified, a help icon will appear in the
8022 * upper-right corner of the rendered field.
8024 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
8025 // Allow passing positional parameters inside the config object
8026 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
8027 config
= fieldWidget
;
8028 fieldWidget
= config
.fieldWidget
;
8029 buttonWidget
= config
.buttonWidget
;
8032 // Configuration initialization
8033 config
= $.extend( { align
: 'left' }, config
);
8035 // Parent constructor
8036 OO
.ui
.ActionFieldLayout
.super.call( this, fieldWidget
, config
);
8039 this.fieldWidget
= fieldWidget
;
8040 this.buttonWidget
= buttonWidget
;
8041 this.$button
= $( '<div>' )
8042 .addClass( 'oo-ui-actionFieldLayout-button' )
8043 .append( this.buttonWidget
.$element
);
8044 this.$input
= $( '<div>' )
8045 .addClass( 'oo-ui-actionFieldLayout-input' )
8046 .append( this.fieldWidget
.$element
);
8048 .addClass( 'oo-ui-actionFieldLayout' )
8049 .append( this.$input
, this.$button
);
8054 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
8057 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
8058 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
8059 * configured with a label as well. For more information and examples,
8060 * please see the [OOjs UI documentation on MediaWiki][1].
8063 * // Example of a fieldset layout
8064 * var input1 = new OO.ui.TextInputWidget( {
8065 * placeholder: 'A text input field'
8068 * var input2 = new OO.ui.TextInputWidget( {
8069 * placeholder: 'A text input field'
8072 * var fieldset = new OO.ui.FieldsetLayout( {
8073 * label: 'Example of a fieldset layout'
8076 * fieldset.addItems( [
8077 * new OO.ui.FieldLayout( input1, {
8078 * label: 'Field One'
8080 * new OO.ui.FieldLayout( input2, {
8081 * label: 'Field Two'
8084 * $( 'body' ).append( fieldset.$element );
8086 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8089 * @extends OO.ui.Layout
8090 * @mixins OO.ui.IconElement
8091 * @mixins OO.ui.LabelElement
8092 * @mixins OO.ui.GroupElement
8095 * @param {Object} [config] Configuration options
8096 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
8098 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
8099 // Configuration initialization
8100 config
= config
|| {};
8102 // Parent constructor
8103 OO
.ui
.FieldsetLayout
.super.call( this, config
);
8105 // Mixin constructors
8106 OO
.ui
.IconElement
.call( this, config
);
8107 OO
.ui
.LabelElement
.call( this, config
);
8108 OO
.ui
.GroupElement
.call( this, config
);
8110 if ( config
.help
) {
8111 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
8112 classes
: [ 'oo-ui-fieldsetLayout-help' ],
8117 this.popupButtonWidget
.getPopup().$body
.append(
8119 .text( config
.help
)
8120 .addClass( 'oo-ui-fieldsetLayout-help-content' )
8122 this.$help
= this.popupButtonWidget
.$element
;
8124 this.$help
= $( [] );
8129 .addClass( 'oo-ui-fieldsetLayout' )
8130 .prepend( this.$help
, this.$icon
, this.$label
, this.$group
);
8131 if ( Array
.isArray( config
.items
) ) {
8132 this.addItems( config
.items
);
8138 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
8139 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.IconElement
);
8140 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.LabelElement
);
8141 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.GroupElement
);
8144 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
8145 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
8146 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
8149 * // Example of a form layout that wraps a fieldset layout
8150 * var input1 = new OO.ui.TextInputWidget( {
8151 * placeholder: 'Username'
8153 * var input2 = new OO.ui.TextInputWidget( {
8154 * placeholder: 'Password',
8157 * var submit = new OO.ui.ButtonInputWidget( {
8161 * var fieldset = new OO.ui.FieldsetLayout( {
8162 * label: 'A form layout'
8164 * fieldset.addItems( [
8165 * new OO.ui.FieldLayout( input1, {
8166 * label: 'Username',
8169 * new OO.ui.FieldLayout( input2, {
8170 * label: 'Password',
8173 * new OO.ui.FieldLayout( submit )
8175 * var form = new OO.ui.FormLayout( {
8176 * items: [ fieldset ],
8177 * action: '/api/formhandler',
8180 * $( 'body' ).append( form.$element );
8183 * @extends OO.ui.Layout
8184 * @mixins OO.ui.GroupElement
8187 * @param {Object} [config] Configuration options
8188 * @cfg {string} [method] HTML form `method` attribute
8189 * @cfg {string} [action] HTML form `action` attribute
8190 * @cfg {string} [enctype] HTML form `enctype` attribute
8191 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
8193 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
8194 // Configuration initialization
8195 config
= config
|| {};
8197 // Parent constructor
8198 OO
.ui
.FormLayout
.super.call( this, config
);
8200 // Mixin constructors
8201 OO
.ui
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
8204 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
8208 .addClass( 'oo-ui-formLayout' )
8210 method
: config
.method
,
8211 action
: config
.action
,
8212 enctype
: config
.enctype
8214 if ( Array
.isArray( config
.items
) ) {
8215 this.addItems( config
.items
);
8221 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
8222 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.GroupElement
);
8227 * A 'submit' event is emitted when the form is submitted.
8232 /* Static Properties */
8234 OO
.ui
.FormLayout
.static.tagName
= 'form';
8239 * Handle form submit events.
8242 * @param {jQuery.Event} e Submit event
8245 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
8246 this.emit( 'submit' );
8251 * Layout with a content and menu area.
8253 * The menu area can be positioned at the top, after, bottom or before. The content area will fill
8254 * all remaining space.
8257 * @extends OO.ui.Layout
8260 * @param {Object} [config] Configuration options
8261 * @cfg {number|string} [menuSize='18em'] Size of menu in pixels or any CSS unit
8262 * @cfg {boolean} [showMenu=true] Show menu
8263 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
8265 OO
.ui
.MenuLayout
= function OoUiMenuLayout( config
) {
8266 var positions
= this.constructor.static.menuPositions
;
8268 // Configuration initialization
8269 config
= config
|| {};
8271 // Parent constructor
8272 OO
.ui
.MenuLayout
.super.call( this, config
);
8275 this.showMenu
= config
.showMenu
!== false;
8276 this.menuSize
= config
.menuSize
|| '18em';
8277 this.menuPosition
= positions
[ config
.menuPosition
] || positions
.before
;
8282 * @property {jQuery}
8284 this.$menu
= $( '<div>' );
8288 * @property {jQuery}
8290 this.$content
= $( '<div>' );
8293 this.toggleMenu( this.showMenu
);
8296 .addClass( 'oo-ui-menuLayout-menu' )
8297 .css( this.menuPosition
.sizeProperty
, this.menuSize
);
8298 this.$content
.addClass( 'oo-ui-menuLayout-content' );
8300 .addClass( 'oo-ui-menuLayout ' + this.menuPosition
.className
)
8301 .append( this.$content
, this.$menu
);
8306 OO
.inheritClass( OO
.ui
.MenuLayout
, OO
.ui
.Layout
);
8308 /* Static Properties */
8310 OO
.ui
.MenuLayout
.static.menuPositions
= {
8312 sizeProperty
: 'height',
8313 className
: 'oo-ui-menuLayout-top'
8316 sizeProperty
: 'width',
8317 className
: 'oo-ui-menuLayout-after'
8320 sizeProperty
: 'height',
8321 className
: 'oo-ui-menuLayout-bottom'
8324 sizeProperty
: 'width',
8325 className
: 'oo-ui-menuLayout-before'
8334 * @param {boolean} showMenu Show menu, omit to toggle
8337 OO
.ui
.MenuLayout
.prototype.toggleMenu = function ( showMenu
) {
8338 showMenu
= showMenu
=== undefined ? !this.showMenu
: !!showMenu
;
8340 if ( this.showMenu
!== showMenu
) {
8341 this.showMenu
= showMenu
;
8349 * Check if menu is visible
8351 * @return {boolean} Menu is visible
8353 OO
.ui
.MenuLayout
.prototype.isMenuVisible = function () {
8354 return this.showMenu
;
8360 * @param {number|string} size Size of menu in pixels or any CSS unit
8363 OO
.ui
.MenuLayout
.prototype.setMenuSize = function ( size
) {
8364 this.menuSize
= size
;
8371 * Update menu and content CSS based on current menu size and visibility
8373 * This method is called internally when size or position is changed.
8375 OO
.ui
.MenuLayout
.prototype.updateSizes = function () {
8376 if ( this.showMenu
) {
8378 .css( this.menuPosition
.sizeProperty
, this.menuSize
)
8379 .css( 'overflow', '' );
8380 // Set offsets on all sides. CSS resets all but one with
8381 // 'important' rules so directionality flips are supported
8382 this.$content
.css( {
8384 right
: this.menuSize
,
8385 bottom
: this.menuSize
,
8390 .css( this.menuPosition
.sizeProperty
, 0 )
8391 .css( 'overflow', 'hidden' );
8392 this.$content
.css( {
8404 * @return {number|string} Menu size
8406 OO
.ui
.MenuLayout
.prototype.getMenuSize = function () {
8407 return this.menuSize
;
8411 * Set menu position.
8413 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
8414 * @throws {Error} If position value is not supported
8417 OO
.ui
.MenuLayout
.prototype.setMenuPosition = function ( position
) {
8418 var positions
= this.constructor.static.menuPositions
;
8420 if ( !positions
[ position
] ) {
8421 throw new Error( 'Cannot set position; unsupported position value: ' + position
);
8424 this.$menu
.css( this.menuPosition
.sizeProperty
, '' );
8425 this.$element
.removeClass( this.menuPosition
.className
);
8427 this.menuPosition
= positions
[ position
];
8430 this.$element
.addClass( this.menuPosition
.className
);
8436 * Get menu position.
8438 * @return {string} Menu position
8440 OO
.ui
.MenuLayout
.prototype.getMenuPosition = function () {
8441 return this.menuPosition
;
8445 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
8446 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
8447 * through the pages and select which one to display. By default, only one page is
8448 * displayed at a time and the outline is hidden. When a user navigates to a new page,
8449 * the booklet layout automatically focuses on the first focusable element, unless the
8450 * default setting is changed. Optionally, booklets can be configured to show
8451 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
8454 * // Example of a BookletLayout that contains two PageLayouts.
8456 * function PageOneLayout( name, config ) {
8457 * PageOneLayout.super.call( this, name, config );
8458 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
8460 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
8461 * PageOneLayout.prototype.setupOutlineItem = function () {
8462 * this.outlineItem.setLabel( 'Page One' );
8465 * function PageTwoLayout( name, config ) {
8466 * PageTwoLayout.super.call( this, name, config );
8467 * this.$element.append( '<p>Second page</p>' );
8469 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
8470 * PageTwoLayout.prototype.setupOutlineItem = function () {
8471 * this.outlineItem.setLabel( 'Page Two' );
8474 * var page1 = new PageOneLayout( 'one' ),
8475 * page2 = new PageTwoLayout( 'two' );
8477 * var booklet = new OO.ui.BookletLayout( {
8481 * booklet.addPages ( [ page1, page2 ] );
8482 * $( 'body' ).append( booklet.$element );
8485 * @extends OO.ui.MenuLayout
8488 * @param {Object} [config] Configuration options
8489 * @cfg {boolean} [continuous=false] Show all pages, one after another
8490 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
8491 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
8492 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
8494 OO
.ui
.BookletLayout
= function OoUiBookletLayout( config
) {
8495 // Configuration initialization
8496 config
= config
|| {};
8498 // Parent constructor
8499 OO
.ui
.BookletLayout
.super.call( this, config
);
8502 this.currentPageName
= null;
8504 this.ignoreFocus
= false;
8505 this.stackLayout
= new OO
.ui
.StackLayout( { continuous
: !!config
.continuous
} );
8506 this.$content
.append( this.stackLayout
.$element
);
8507 this.autoFocus
= config
.autoFocus
=== undefined || !!config
.autoFocus
;
8508 this.outlineVisible
= false;
8509 this.outlined
= !!config
.outlined
;
8510 if ( this.outlined
) {
8511 this.editable
= !!config
.editable
;
8512 this.outlineControlsWidget
= null;
8513 this.outlineSelectWidget
= new OO
.ui
.OutlineSelectWidget();
8514 this.outlinePanel
= new OO
.ui
.PanelLayout( { scrollable
: true } );
8515 this.$menu
.append( this.outlinePanel
.$element
);
8516 this.outlineVisible
= true;
8517 if ( this.editable
) {
8518 this.outlineControlsWidget
= new OO
.ui
.OutlineControlsWidget(
8519 this.outlineSelectWidget
8523 this.toggleMenu( this.outlined
);
8526 this.stackLayout
.connect( this, { set: 'onStackLayoutSet' } );
8527 if ( this.outlined
) {
8528 this.outlineSelectWidget
.connect( this, { select
: 'onOutlineSelectWidgetSelect' } );
8530 if ( this.autoFocus
) {
8531 // Event 'focus' does not bubble, but 'focusin' does
8532 this.stackLayout
.$element
.on( 'focusin', this.onStackLayoutFocus
.bind( this ) );
8536 this.$element
.addClass( 'oo-ui-bookletLayout' );
8537 this.stackLayout
.$element
.addClass( 'oo-ui-bookletLayout-stackLayout' );
8538 if ( this.outlined
) {
8539 this.outlinePanel
.$element
8540 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
8541 .append( this.outlineSelectWidget
.$element
);
8542 if ( this.editable
) {
8543 this.outlinePanel
.$element
8544 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
8545 .append( this.outlineControlsWidget
.$element
);
8552 OO
.inheritClass( OO
.ui
.BookletLayout
, OO
.ui
.MenuLayout
);
8557 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
8559 * @param {OO.ui.PageLayout} page Current page
8563 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
8566 * @param {OO.ui.PageLayout[]} page Added pages
8567 * @param {number} index Index pages were added at
8571 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
8572 * {@link #removePages removed} from the booklet.
8575 * @param {OO.ui.PageLayout[]} pages Removed pages
8581 * Handle stack layout focus.
8584 * @param {jQuery.Event} e Focusin event
8586 OO
.ui
.BookletLayout
.prototype.onStackLayoutFocus = function ( e
) {
8589 // Find the page that an element was focused within
8590 $target
= $( e
.target
).closest( '.oo-ui-pageLayout' );
8591 for ( name
in this.pages
) {
8592 // Check for page match, exclude current page to find only page changes
8593 if ( this.pages
[ name
].$element
[ 0 ] === $target
[ 0 ] && name
!== this.currentPageName
) {
8594 this.setPage( name
);
8601 * Handle stack layout set events.
8604 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
8606 OO
.ui
.BookletLayout
.prototype.onStackLayoutSet = function ( page
) {
8609 page
.scrollElementIntoView( { complete: function () {
8610 if ( layout
.autoFocus
) {
8618 * Focus the first input in the current page.
8620 * If no page is selected, the first selectable page will be selected.
8621 * If the focus is already in an element on the current page, nothing will happen.
8622 * @param {number} [itemIndex] A specific item to focus on
8624 OO
.ui
.BookletLayout
.prototype.focus = function ( itemIndex
) {
8626 items
= this.stackLayout
.getItems();
8628 if ( itemIndex
!== undefined && items
[ itemIndex
] ) {
8629 page
= items
[ itemIndex
];
8631 page
= this.stackLayout
.getCurrentItem();
8634 if ( !page
&& this.outlined
) {
8635 this.selectFirstSelectablePage();
8636 page
= this.stackLayout
.getCurrentItem();
8641 // Only change the focus if is not already in the current page
8642 if ( !page
.$element
.find( ':focus' ).length
) {
8643 $input
= page
.$element
.find( ':input:first' );
8644 if ( $input
.length
) {
8645 $input
[ 0 ].focus();
8651 * Handle outline widget select events.
8654 * @param {OO.ui.OptionWidget|null} item Selected item
8656 OO
.ui
.BookletLayout
.prototype.onOutlineSelectWidgetSelect = function ( item
) {
8658 this.setPage( item
.getData() );
8663 * Check if booklet has an outline.
8665 * @return {boolean} Booklet has an outline
8667 OO
.ui
.BookletLayout
.prototype.isOutlined = function () {
8668 return this.outlined
;
8672 * Check if booklet has editing controls.
8674 * @return {boolean} Booklet is editable
8676 OO
.ui
.BookletLayout
.prototype.isEditable = function () {
8677 return this.editable
;
8681 * Check if booklet has a visible outline.
8683 * @return {boolean} Outline is visible
8685 OO
.ui
.BookletLayout
.prototype.isOutlineVisible = function () {
8686 return this.outlined
&& this.outlineVisible
;
8690 * Hide or show the outline.
8692 * @param {boolean} [show] Show outline, omit to invert current state
8695 OO
.ui
.BookletLayout
.prototype.toggleOutline = function ( show
) {
8696 if ( this.outlined
) {
8697 show
= show
=== undefined ? !this.outlineVisible
: !!show
;
8698 this.outlineVisible
= show
;
8699 this.toggleMenu( show
);
8706 * Get the page closest to the specified page.
8708 * @param {OO.ui.PageLayout} page Page to use as a reference point
8709 * @return {OO.ui.PageLayout|null} Page closest to the specified page
8711 OO
.ui
.BookletLayout
.prototype.getClosestPage = function ( page
) {
8712 var next
, prev
, level
,
8713 pages
= this.stackLayout
.getItems(),
8714 index
= $.inArray( page
, pages
);
8716 if ( index
!== -1 ) {
8717 next
= pages
[ index
+ 1 ];
8718 prev
= pages
[ index
- 1 ];
8719 // Prefer adjacent pages at the same level
8720 if ( this.outlined
) {
8721 level
= this.outlineSelectWidget
.getItemFromData( page
.getName() ).getLevel();
8724 level
=== this.outlineSelectWidget
.getItemFromData( prev
.getName() ).getLevel()
8730 level
=== this.outlineSelectWidget
.getItemFromData( next
.getName() ).getLevel()
8736 return prev
|| next
|| null;
8740 * Get the outline widget.
8742 * If the booklet is not outlined, the method will return `null`.
8744 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
8746 OO
.ui
.BookletLayout
.prototype.getOutline = function () {
8747 return this.outlineSelectWidget
;
8751 * Get the outline controls widget.
8753 * If the outline is not editable, the method will return `null`.
8755 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
8757 OO
.ui
.BookletLayout
.prototype.getOutlineControls = function () {
8758 return this.outlineControlsWidget
;
8762 * Get a page by its symbolic name.
8764 * @param {string} name Symbolic name of page
8765 * @return {OO.ui.PageLayout|undefined} Page, if found
8767 OO
.ui
.BookletLayout
.prototype.getPage = function ( name
) {
8768 return this.pages
[ name
];
8772 * Get the current page.
8774 * @return {OO.ui.PageLayout|undefined} Current page, if found
8776 OO
.ui
.BookletLayout
.prototype.getCurrentPage = function () {
8777 var name
= this.getCurrentPageName();
8778 return name
? this.getPage( name
) : undefined;
8782 * Get the symbolic name of the current page.
8784 * @return {string|null} Symbolic name of the current page
8786 OO
.ui
.BookletLayout
.prototype.getCurrentPageName = function () {
8787 return this.currentPageName
;
8791 * Add pages to the booklet layout
8793 * When pages are added with the same names as existing pages, the existing pages will be
8794 * automatically removed before the new pages are added.
8796 * @param {OO.ui.PageLayout[]} pages Pages to add
8797 * @param {number} index Index of the insertion point
8801 OO
.ui
.BookletLayout
.prototype.addPages = function ( pages
, index
) {
8802 var i
, len
, name
, page
, item
, currentIndex
,
8803 stackLayoutPages
= this.stackLayout
.getItems(),
8807 // Remove pages with same names
8808 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
8810 name
= page
.getName();
8812 if ( Object
.prototype.hasOwnProperty
.call( this.pages
, name
) ) {
8813 // Correct the insertion index
8814 currentIndex
= $.inArray( this.pages
[ name
], stackLayoutPages
);
8815 if ( currentIndex
!== -1 && currentIndex
+ 1 < index
) {
8818 remove
.push( this.pages
[ name
] );
8821 if ( remove
.length
) {
8822 this.removePages( remove
);
8826 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
8828 name
= page
.getName();
8829 this.pages
[ page
.getName() ] = page
;
8830 if ( this.outlined
) {
8831 item
= new OO
.ui
.OutlineOptionWidget( { data
: name
} );
8832 page
.setOutlineItem( item
);
8837 if ( this.outlined
&& items
.length
) {
8838 this.outlineSelectWidget
.addItems( items
, index
);
8839 this.selectFirstSelectablePage();
8841 this.stackLayout
.addItems( pages
, index
);
8842 this.emit( 'add', pages
, index
);
8848 * Remove the specified pages from the booklet layout.
8850 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
8852 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
8856 OO
.ui
.BookletLayout
.prototype.removePages = function ( pages
) {
8857 var i
, len
, name
, page
,
8860 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
8862 name
= page
.getName();
8863 delete this.pages
[ name
];
8864 if ( this.outlined
) {
8865 items
.push( this.outlineSelectWidget
.getItemFromData( name
) );
8866 page
.setOutlineItem( null );
8869 if ( this.outlined
&& items
.length
) {
8870 this.outlineSelectWidget
.removeItems( items
);
8871 this.selectFirstSelectablePage();
8873 this.stackLayout
.removeItems( pages
);
8874 this.emit( 'remove', pages
);
8880 * Clear all pages from the booklet layout.
8882 * To remove only a subset of pages from the booklet, use the #removePages method.
8887 OO
.ui
.BookletLayout
.prototype.clearPages = function () {
8889 pages
= this.stackLayout
.getItems();
8892 this.currentPageName
= null;
8893 if ( this.outlined
) {
8894 this.outlineSelectWidget
.clearItems();
8895 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
8896 pages
[ i
].setOutlineItem( null );
8899 this.stackLayout
.clearItems();
8901 this.emit( 'remove', pages
);
8907 * Set the current page by symbolic name.
8910 * @param {string} name Symbolic name of page
8912 OO
.ui
.BookletLayout
.prototype.setPage = function ( name
) {
8915 page
= this.pages
[ name
];
8917 if ( name
!== this.currentPageName
) {
8918 if ( this.outlined
) {
8919 selectedItem
= this.outlineSelectWidget
.getSelectedItem();
8920 if ( selectedItem
&& selectedItem
.getData() !== name
) {
8921 this.outlineSelectWidget
.selectItem( this.outlineSelectWidget
.getItemFromData( name
) );
8925 if ( this.currentPageName
&& this.pages
[ this.currentPageName
] ) {
8926 this.pages
[ this.currentPageName
].setActive( false );
8927 // Blur anything focused if the next page doesn't have anything focusable - this
8928 // is not needed if the next page has something focusable because once it is focused
8929 // this blur happens automatically
8930 if ( this.autoFocus
&& !page
.$element
.find( ':input' ).length
) {
8931 $focused
= this.pages
[ this.currentPageName
].$element
.find( ':focus' );
8932 if ( $focused
.length
) {
8933 $focused
[ 0 ].blur();
8937 this.currentPageName
= name
;
8938 this.stackLayout
.setItem( page
);
8939 page
.setActive( true );
8940 this.emit( 'set', page
);
8946 * Select the first selectable page.
8950 OO
.ui
.BookletLayout
.prototype.selectFirstSelectablePage = function () {
8951 if ( !this.outlineSelectWidget
.getSelectedItem() ) {
8952 this.outlineSelectWidget
.selectItem( this.outlineSelectWidget
.getFirstSelectableItem() );
8959 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
8960 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
8963 * // Example of a panel layout
8964 * var panel = new OO.ui.PanelLayout( {
8968 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
8970 * $( 'body' ).append( panel.$element );
8973 * @extends OO.ui.Layout
8976 * @param {Object} [config] Configuration options
8977 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
8978 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
8979 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
8980 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
8982 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
8983 // Configuration initialization
8984 config
= $.extend( {
8991 // Parent constructor
8992 OO
.ui
.PanelLayout
.super.call( this, config
);
8995 this.$element
.addClass( 'oo-ui-panelLayout' );
8996 if ( config
.scrollable
) {
8997 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
8999 if ( config
.padded
) {
9000 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
9002 if ( config
.expanded
) {
9003 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
9005 if ( config
.framed
) {
9006 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
9012 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
9015 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
9016 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
9017 * rather extended to include the required content and functionality.
9019 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
9020 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
9021 * {@link OO.ui.BookletLayout BookletLayout} for an example.
9024 * @extends OO.ui.PanelLayout
9027 * @param {string} name Unique symbolic name of page
9028 * @param {Object} [config] Configuration options
9030 OO
.ui
.PageLayout
= function OoUiPageLayout( name
, config
) {
9031 // Allow passing positional parameters inside the config object
9032 if ( OO
.isPlainObject( name
) && config
=== undefined ) {
9037 // Configuration initialization
9038 config
= $.extend( { scrollable
: true }, config
);
9040 // Parent constructor
9041 OO
.ui
.PageLayout
.super.call( this, config
);
9045 this.outlineItem
= null;
9046 this.active
= false;
9049 this.$element
.addClass( 'oo-ui-pageLayout' );
9054 OO
.inheritClass( OO
.ui
.PageLayout
, OO
.ui
.PanelLayout
);
9059 * An 'active' event is emitted when the page becomes active. Pages become active when they are
9060 * shown in a booklet layout that is configured to display only one page at a time.
9063 * @param {boolean} active Page is active
9069 * Get the symbolic name of the page.
9071 * @return {string} Symbolic name of page
9073 OO
.ui
.PageLayout
.prototype.getName = function () {
9078 * Check if page is active.
9080 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
9081 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
9083 * @return {boolean} Page is active
9085 OO
.ui
.PageLayout
.prototype.isActive = function () {
9092 * The outline item allows users to access the page from the booklet's outline
9093 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
9095 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
9097 OO
.ui
.PageLayout
.prototype.getOutlineItem = function () {
9098 return this.outlineItem
;
9102 * Set or unset the outline item.
9104 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
9105 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
9106 * level), use #setupOutlineItem instead of this method.
9108 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
9111 OO
.ui
.PageLayout
.prototype.setOutlineItem = function ( outlineItem
) {
9112 this.outlineItem
= outlineItem
|| null;
9113 if ( outlineItem
) {
9114 this.setupOutlineItem();
9120 * Set up the outline item.
9122 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
9123 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
9124 * the #setOutlineItem method instead.
9126 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
9129 OO
.ui
.PageLayout
.prototype.setupOutlineItem = function () {
9134 * Set the page to its 'active' state.
9136 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
9137 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
9138 * context, setting the active state on a page does nothing.
9140 * @param {boolean} value Page is active
9143 OO
.ui
.PageLayout
.prototype.setActive = function ( active
) {
9146 if ( active
!== this.active
) {
9147 this.active
= active
;
9148 this.$element
.toggleClass( 'oo-ui-pageLayout-active', active
);
9149 this.emit( 'active', this.active
);
9154 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
9155 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
9156 * by setting the #continuous option to 'true'.
9159 * // A stack layout with two panels, configured to be displayed continously
9160 * var myStack = new OO.ui.StackLayout( {
9162 * new OO.ui.PanelLayout( {
9163 * $content: $( '<p>Panel One</p>' ),
9167 * new OO.ui.PanelLayout( {
9168 * $content: $( '<p>Panel Two</p>' ),
9175 * $( 'body' ).append( myStack.$element );
9178 * @extends OO.ui.PanelLayout
9179 * @mixins OO.ui.GroupElement
9182 * @param {Object} [config] Configuration options
9183 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
9184 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
9186 OO
.ui
.StackLayout
= function OoUiStackLayout( config
) {
9187 // Configuration initialization
9188 config
= $.extend( { scrollable
: true }, config
);
9190 // Parent constructor
9191 OO
.ui
.StackLayout
.super.call( this, config
);
9193 // Mixin constructors
9194 OO
.ui
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
9197 this.currentItem
= null;
9198 this.continuous
= !!config
.continuous
;
9201 this.$element
.addClass( 'oo-ui-stackLayout' );
9202 if ( this.continuous
) {
9203 this.$element
.addClass( 'oo-ui-stackLayout-continuous' );
9205 if ( Array
.isArray( config
.items
) ) {
9206 this.addItems( config
.items
);
9212 OO
.inheritClass( OO
.ui
.StackLayout
, OO
.ui
.PanelLayout
);
9213 OO
.mixinClass( OO
.ui
.StackLayout
, OO
.ui
.GroupElement
);
9218 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
9219 * {@link #clearItems cleared} or {@link #setItem displayed}.
9222 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
9228 * Get the current panel.
9230 * @return {OO.ui.Layout|null}
9232 OO
.ui
.StackLayout
.prototype.getCurrentItem = function () {
9233 return this.currentItem
;
9237 * Unset the current item.
9240 * @param {OO.ui.StackLayout} layout
9243 OO
.ui
.StackLayout
.prototype.unsetCurrentItem = function () {
9244 var prevItem
= this.currentItem
;
9245 if ( prevItem
=== null ) {
9249 this.currentItem
= null;
9250 this.emit( 'set', null );
9254 * Add panel layouts to the stack layout.
9256 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
9257 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
9260 * @param {OO.ui.Layout[]} items Panels to add
9261 * @param {number} [index] Index of the insertion point
9264 OO
.ui
.StackLayout
.prototype.addItems = function ( items
, index
) {
9265 // Update the visibility
9266 this.updateHiddenState( items
, this.currentItem
);
9269 OO
.ui
.GroupElement
.prototype.addItems
.call( this, items
, index
);
9271 if ( !this.currentItem
&& items
.length
) {
9272 this.setItem( items
[ 0 ] );
9279 * Remove the specified panels from the stack layout.
9281 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
9282 * you may wish to use the #clearItems method instead.
9284 * @param {OO.ui.Layout[]} items Panels to remove
9288 OO
.ui
.StackLayout
.prototype.removeItems = function ( items
) {
9290 OO
.ui
.GroupElement
.prototype.removeItems
.call( this, items
);
9292 if ( $.inArray( this.currentItem
, items
) !== -1 ) {
9293 if ( this.items
.length
) {
9294 this.setItem( this.items
[ 0 ] );
9296 this.unsetCurrentItem();
9304 * Clear all panels from the stack layout.
9306 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
9307 * a subset of panels, use the #removeItems method.
9312 OO
.ui
.StackLayout
.prototype.clearItems = function () {
9313 this.unsetCurrentItem();
9314 OO
.ui
.GroupElement
.prototype.clearItems
.call( this );
9320 * Show the specified panel.
9322 * If another panel is currently displayed, it will be hidden.
9324 * @param {OO.ui.Layout} item Panel to show
9328 OO
.ui
.StackLayout
.prototype.setItem = function ( item
) {
9329 if ( item
!== this.currentItem
) {
9330 this.updateHiddenState( this.items
, item
);
9332 if ( $.inArray( item
, this.items
) !== -1 ) {
9333 this.currentItem
= item
;
9334 this.emit( 'set', item
);
9336 this.unsetCurrentItem();
9344 * Update the visibility of all items in case of non-continuous view.
9346 * Ensure all items are hidden except for the selected one.
9347 * This method does nothing when the stack is continuous.
9350 * @param {OO.ui.Layout[]} items Item list iterate over
9351 * @param {OO.ui.Layout} [selectedItem] Selected item to show
9353 OO
.ui
.StackLayout
.prototype.updateHiddenState = function ( items
, selectedItem
) {
9356 if ( !this.continuous
) {
9357 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
9358 if ( !selectedItem
|| selectedItem
!== items
[ i
] ) {
9359 items
[ i
].$element
.addClass( 'oo-ui-element-hidden' );
9362 if ( selectedItem
) {
9363 selectedItem
.$element
.removeClass( 'oo-ui-element-hidden' );
9369 * Horizontal bar layout of tools as icon buttons.
9372 * @extends OO.ui.ToolGroup
9375 * @param {OO.ui.Toolbar} toolbar
9376 * @param {Object} [config] Configuration options
9378 OO
.ui
.BarToolGroup
= function OoUiBarToolGroup( toolbar
, config
) {
9379 // Allow passing positional parameters inside the config object
9380 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
9382 toolbar
= config
.toolbar
;
9385 // Parent constructor
9386 OO
.ui
.BarToolGroup
.super.call( this, toolbar
, config
);
9389 this.$element
.addClass( 'oo-ui-barToolGroup' );
9394 OO
.inheritClass( OO
.ui
.BarToolGroup
, OO
.ui
.ToolGroup
);
9396 /* Static Properties */
9398 OO
.ui
.BarToolGroup
.static.titleTooltips
= true;
9400 OO
.ui
.BarToolGroup
.static.accelTooltips
= true;
9402 OO
.ui
.BarToolGroup
.static.name
= 'bar';
9405 * Popup list of tools with an icon and optional label.
9409 * @extends OO.ui.ToolGroup
9410 * @mixins OO.ui.IconElement
9411 * @mixins OO.ui.IndicatorElement
9412 * @mixins OO.ui.LabelElement
9413 * @mixins OO.ui.TitledElement
9414 * @mixins OO.ui.ClippableElement
9417 * @param {OO.ui.Toolbar} toolbar
9418 * @param {Object} [config] Configuration options
9419 * @cfg {string} [header] Text to display at the top of the pop-up
9421 OO
.ui
.PopupToolGroup
= function OoUiPopupToolGroup( toolbar
, config
) {
9422 // Allow passing positional parameters inside the config object
9423 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
9425 toolbar
= config
.toolbar
;
9428 // Configuration initialization
9429 config
= config
|| {};
9431 // Parent constructor
9432 OO
.ui
.PopupToolGroup
.super.call( this, toolbar
, config
);
9434 // Mixin constructors
9435 OO
.ui
.IconElement
.call( this, config
);
9436 OO
.ui
.IndicatorElement
.call( this, config
);
9437 OO
.ui
.LabelElement
.call( this, config
);
9438 OO
.ui
.TitledElement
.call( this, config
);
9439 OO
.ui
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
9442 this.active
= false;
9443 this.dragging
= false;
9444 this.onBlurHandler
= this.onBlur
.bind( this );
9445 this.$handle
= $( '<span>' );
9449 mousedown
: this.onHandlePointerDown
.bind( this ),
9450 mouseup
: this.onHandlePointerUp
.bind( this )
9455 .addClass( 'oo-ui-popupToolGroup-handle' )
9456 .append( this.$icon
, this.$label
, this.$indicator
);
9457 // If the pop-up should have a header, add it to the top of the toolGroup.
9458 // Note: If this feature is useful for other widgets, we could abstract it into an
9459 // OO.ui.HeaderedElement mixin constructor.
9460 if ( config
.header
!== undefined ) {
9462 .prepend( $( '<span>' )
9463 .addClass( 'oo-ui-popupToolGroup-header' )
9464 .text( config
.header
)
9468 .addClass( 'oo-ui-popupToolGroup' )
9469 .prepend( this.$handle
);
9474 OO
.inheritClass( OO
.ui
.PopupToolGroup
, OO
.ui
.ToolGroup
);
9475 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.IconElement
);
9476 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.IndicatorElement
);
9477 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.LabelElement
);
9478 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.TitledElement
);
9479 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.ClippableElement
);
9481 /* Static Properties */
9488 OO
.ui
.PopupToolGroup
.prototype.setDisabled = function () {
9490 OO
.ui
.PopupToolGroup
.super.prototype.setDisabled
.apply( this, arguments
);
9492 if ( this.isDisabled() && this.isElementAttached() ) {
9493 this.setActive( false );
9498 * Handle focus being lost.
9500 * The event is actually generated from a mouseup, so it is not a normal blur event object.
9502 * @param {jQuery.Event} e Mouse up event
9504 OO
.ui
.PopupToolGroup
.prototype.onBlur = function ( e
) {
9505 // Only deactivate when clicking outside the dropdown element
9506 if ( $( e
.target
).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element
[ 0 ] ) {
9507 this.setActive( false );
9514 OO
.ui
.PopupToolGroup
.prototype.onPointerUp = function ( e
) {
9515 // Only close toolgroup when a tool was actually selected
9516 if ( !this.isDisabled() && e
.which
=== 1 && this.pressed
&& this.pressed
=== this.getTargetTool( e
) ) {
9517 this.setActive( false );
9519 return OO
.ui
.PopupToolGroup
.super.prototype.onPointerUp
.call( this, e
);
9523 * Handle mouse up events.
9525 * @param {jQuery.Event} e Mouse up event
9527 OO
.ui
.PopupToolGroup
.prototype.onHandlePointerUp = function () {
9532 * Handle mouse down events.
9534 * @param {jQuery.Event} e Mouse down event
9536 OO
.ui
.PopupToolGroup
.prototype.onHandlePointerDown = function ( e
) {
9537 if ( !this.isDisabled() && e
.which
=== 1 ) {
9538 this.setActive( !this.active
);
9544 * Switch into active mode.
9546 * When active, mouseup events anywhere in the document will trigger deactivation.
9548 OO
.ui
.PopupToolGroup
.prototype.setActive = function ( value
) {
9550 if ( this.active
!== value
) {
9551 this.active
= value
;
9553 this.getElementDocument().addEventListener( 'mouseup', this.onBlurHandler
, true );
9555 // Try anchoring the popup to the left first
9556 this.$element
.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
9557 this.toggleClipping( true );
9558 if ( this.isClippedHorizontally() ) {
9559 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
9560 this.toggleClipping( false );
9562 .removeClass( 'oo-ui-popupToolGroup-left' )
9563 .addClass( 'oo-ui-popupToolGroup-right' );
9564 this.toggleClipping( true );
9567 this.getElementDocument().removeEventListener( 'mouseup', this.onBlurHandler
, true );
9568 this.$element
.removeClass(
9569 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
9571 this.toggleClipping( false );
9577 * Drop down list layout of tools as labeled icon buttons.
9579 * This layout allows some tools to be collapsible, controlled by a "More" / "Fewer" option at the
9580 * bottom of the main list. These are not automatically positioned at the bottom of the list; you
9581 * may want to use the 'promote' and 'demote' configuration options to achieve this.
9584 * @extends OO.ui.PopupToolGroup
9587 * @param {OO.ui.Toolbar} toolbar
9588 * @param {Object} [config] Configuration options
9589 * @cfg {Array} [allowCollapse] List of tools that can be collapsed. Remaining tools will be always
9591 * @cfg {Array} [forceExpand] List of tools that *may not* be collapsed. All remaining tools will be
9592 * allowed to be collapsed.
9593 * @cfg {boolean} [expanded=false] Whether the collapsible tools are expanded by default
9595 OO
.ui
.ListToolGroup
= function OoUiListToolGroup( toolbar
, config
) {
9596 // Allow passing positional parameters inside the config object
9597 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
9599 toolbar
= config
.toolbar
;
9602 // Configuration initialization
9603 config
= config
|| {};
9605 // Properties (must be set before parent constructor, which calls #populate)
9606 this.allowCollapse
= config
.allowCollapse
;
9607 this.forceExpand
= config
.forceExpand
;
9608 this.expanded
= config
.expanded
!== undefined ? config
.expanded
: false;
9609 this.collapsibleTools
= [];
9611 // Parent constructor
9612 OO
.ui
.ListToolGroup
.super.call( this, toolbar
, config
);
9615 this.$element
.addClass( 'oo-ui-listToolGroup' );
9620 OO
.inheritClass( OO
.ui
.ListToolGroup
, OO
.ui
.PopupToolGroup
);
9622 /* Static Properties */
9624 OO
.ui
.ListToolGroup
.static.accelTooltips
= true;
9626 OO
.ui
.ListToolGroup
.static.name
= 'list';
9633 OO
.ui
.ListToolGroup
.prototype.populate = function () {
9634 var i
, len
, allowCollapse
= [];
9636 OO
.ui
.ListToolGroup
.super.prototype.populate
.call( this );
9638 // Update the list of collapsible tools
9639 if ( this.allowCollapse
!== undefined ) {
9640 allowCollapse
= this.allowCollapse
;
9641 } else if ( this.forceExpand
!== undefined ) {
9642 allowCollapse
= OO
.simpleArrayDifference( Object
.keys( this.tools
), this.forceExpand
);
9645 this.collapsibleTools
= [];
9646 for ( i
= 0, len
= allowCollapse
.length
; i
< len
; i
++ ) {
9647 if ( this.tools
[ allowCollapse
[ i
] ] !== undefined ) {
9648 this.collapsibleTools
.push( this.tools
[ allowCollapse
[ i
] ] );
9652 // Keep at the end, even when tools are added
9653 this.$group
.append( this.getExpandCollapseTool().$element
);
9655 this.getExpandCollapseTool().toggle( this.collapsibleTools
.length
!== 0 );
9656 this.updateCollapsibleState();
9659 OO
.ui
.ListToolGroup
.prototype.getExpandCollapseTool = function () {
9660 if ( this.expandCollapseTool
=== undefined ) {
9661 var ExpandCollapseTool = function () {
9662 ExpandCollapseTool
.super.apply( this, arguments
);
9665 OO
.inheritClass( ExpandCollapseTool
, OO
.ui
.Tool
);
9667 ExpandCollapseTool
.prototype.onSelect = function () {
9668 this.toolGroup
.expanded
= !this.toolGroup
.expanded
;
9669 this.toolGroup
.updateCollapsibleState();
9670 this.setActive( false );
9672 ExpandCollapseTool
.prototype.onUpdateState = function () {
9673 // Do nothing. Tool interface requires an implementation of this function.
9676 ExpandCollapseTool
.static.name
= 'more-fewer';
9678 this.expandCollapseTool
= new ExpandCollapseTool( this );
9680 return this.expandCollapseTool
;
9686 OO
.ui
.ListToolGroup
.prototype.onPointerUp = function ( e
) {
9687 var ret
= OO
.ui
.ListToolGroup
.super.prototype.onPointerUp
.call( this, e
);
9689 // Do not close the popup when the user wants to show more/fewer tools
9690 if ( $( e
.target
).closest( '.oo-ui-tool-name-more-fewer' ).length
) {
9691 // Prevent the popup list from being hidden
9692 this.setActive( true );
9698 OO
.ui
.ListToolGroup
.prototype.updateCollapsibleState = function () {
9701 this.getExpandCollapseTool()
9702 .setIcon( this.expanded
? 'collapse' : 'expand' )
9703 .setTitle( OO
.ui
.msg( this.expanded
? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
9705 for ( i
= 0, len
= this.collapsibleTools
.length
; i
< len
; i
++ ) {
9706 this.collapsibleTools
[ i
].toggle( this.expanded
);
9711 * Drop down menu layout of tools as selectable menu items.
9714 * @extends OO.ui.PopupToolGroup
9717 * @param {OO.ui.Toolbar} toolbar
9718 * @param {Object} [config] Configuration options
9720 OO
.ui
.MenuToolGroup
= function OoUiMenuToolGroup( toolbar
, config
) {
9721 // Allow passing positional parameters inside the config object
9722 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
9724 toolbar
= config
.toolbar
;
9727 // Configuration initialization
9728 config
= config
|| {};
9730 // Parent constructor
9731 OO
.ui
.MenuToolGroup
.super.call( this, toolbar
, config
);
9734 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
9737 this.$element
.addClass( 'oo-ui-menuToolGroup' );
9742 OO
.inheritClass( OO
.ui
.MenuToolGroup
, OO
.ui
.PopupToolGroup
);
9744 /* Static Properties */
9746 OO
.ui
.MenuToolGroup
.static.accelTooltips
= true;
9748 OO
.ui
.MenuToolGroup
.static.name
= 'menu';
9753 * Handle the toolbar state being updated.
9755 * When the state changes, the title of each active item in the menu will be joined together and
9756 * used as a label for the group. The label will be empty if none of the items are active.
9758 OO
.ui
.MenuToolGroup
.prototype.onUpdateState = function () {
9762 for ( name
in this.tools
) {
9763 if ( this.tools
[ name
].isActive() ) {
9764 labelTexts
.push( this.tools
[ name
].getTitle() );
9768 this.setLabel( labelTexts
.join( ', ' ) || ' ' );
9772 * Tool that shows a popup when selected.
9776 * @extends OO.ui.Tool
9777 * @mixins OO.ui.PopupElement
9780 * @param {OO.ui.ToolGroup} toolGroup
9781 * @param {Object} [config] Configuration options
9783 OO
.ui
.PopupTool
= function OoUiPopupTool( toolGroup
, config
) {
9784 // Allow passing positional parameters inside the config object
9785 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
9787 toolGroup
= config
.toolGroup
;
9790 // Parent constructor
9791 OO
.ui
.PopupTool
.super.call( this, toolGroup
, config
);
9793 // Mixin constructors
9794 OO
.ui
.PopupElement
.call( this, config
);
9798 .addClass( 'oo-ui-popupTool' )
9799 .append( this.popup
.$element
);
9804 OO
.inheritClass( OO
.ui
.PopupTool
, OO
.ui
.Tool
);
9805 OO
.mixinClass( OO
.ui
.PopupTool
, OO
.ui
.PopupElement
);
9810 * Handle the tool being selected.
9814 OO
.ui
.PopupTool
.prototype.onSelect = function () {
9815 if ( !this.isDisabled() ) {
9816 this.popup
.toggle();
9818 this.setActive( false );
9823 * Handle the toolbar state being updated.
9827 OO
.ui
.PopupTool
.prototype.onUpdateState = function () {
9828 this.setActive( false );
9832 * Tool that has a tool group inside. This is a bad workaround for the lack of proper hierarchical
9833 * menus in toolbars (T74159).
9837 * @extends OO.ui.Tool
9840 * @param {OO.ui.ToolGroup} toolGroup
9841 * @param {Object} [config] Configuration options
9843 OO
.ui
.ToolGroupTool
= function OoUiToolGroupTool( toolGroup
, config
) {
9844 // Allow passing positional parameters inside the config object
9845 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
9847 toolGroup
= config
.toolGroup
;
9850 // Parent constructor
9851 OO
.ui
.ToolGroupTool
.super.call( this, toolGroup
, config
);
9854 this.innerToolGroup
= this.createGroup( this.constructor.static.groupConfig
);
9857 this.$link
.remove();
9859 .addClass( 'oo-ui-toolGroupTool' )
9860 .append( this.innerToolGroup
.$element
);
9865 OO
.inheritClass( OO
.ui
.ToolGroupTool
, OO
.ui
.Tool
);
9867 /* Static Properties */
9870 * Tool group configuration. See OO.ui.Toolbar#setup for the accepted values.
9872 * @property {Object.<string,Array>}
9874 OO
.ui
.ToolGroupTool
.static.groupConfig
= {};
9879 * Handle the tool being selected.
9883 OO
.ui
.ToolGroupTool
.prototype.onSelect = function () {
9884 this.innerToolGroup
.setActive( !this.innerToolGroup
.active
);
9889 * Handle the toolbar state being updated.
9893 OO
.ui
.ToolGroupTool
.prototype.onUpdateState = function () {
9894 this.setActive( false );
9898 * Build a OO.ui.ToolGroup from the configuration.
9900 * @param {Object.<string,Array>} group Tool group configuration. See OO.ui.Toolbar#setup for the
9902 * @return {OO.ui.ListToolGroup}
9904 OO
.ui
.ToolGroupTool
.prototype.createGroup = function ( group
) {
9905 if ( group
.include
=== '*' ) {
9906 // Apply defaults to catch-all groups
9907 if ( group
.label
=== undefined ) {
9908 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
9912 return this.toolbar
.getToolGroupFactory().create( 'list', this.toolbar
, group
);
9916 * Mixin for OO.ui.Widget subclasses to provide OO.ui.GroupElement.
9918 * Use together with OO.ui.ItemWidget to make disabled state inheritable.
9923 * @extends OO.ui.GroupElement
9926 * @param {Object} [config] Configuration options
9928 OO
.ui
.GroupWidget
= function OoUiGroupWidget( config
) {
9929 // Parent constructor
9930 OO
.ui
.GroupWidget
.super.call( this, config
);
9935 OO
.inheritClass( OO
.ui
.GroupWidget
, OO
.ui
.GroupElement
);
9940 * Set the disabled state of the widget.
9942 * This will also update the disabled state of child widgets.
9944 * @param {boolean} disabled Disable widget
9947 OO
.ui
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
9951 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
9952 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
9954 // During construction, #setDisabled is called before the OO.ui.GroupElement constructor
9956 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
9957 this.items
[ i
].updateDisabled();
9965 * Mixin for widgets used as items in widgets that inherit OO.ui.GroupWidget.
9967 * Item widgets have a reference to a OO.ui.GroupWidget while they are attached to the group. This
9968 * allows bidirectional communication.
9970 * Use together with OO.ui.GroupWidget to make disabled state inheritable.
9978 OO
.ui
.ItemWidget
= function OoUiItemWidget() {
9985 * Check if widget is disabled.
9987 * Checks parent if present, making disabled state inheritable.
9989 * @return {boolean} Widget is disabled
9991 OO
.ui
.ItemWidget
.prototype.isDisabled = function () {
9992 return this.disabled
||
9993 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
9997 * Set group element is in.
9999 * @param {OO.ui.GroupElement|null} group Group element, null if none
10002 OO
.ui
.ItemWidget
.prototype.setElementGroup = function ( group
) {
10004 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
10005 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
10007 // Initialize item disabled states
10008 this.updateDisabled();
10014 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
10015 * Controls include moving items up and down, removing items, and adding different kinds of items.
10016 * ####Currently, this class is only used by {@link OO.ui.BookletLayout BookletLayouts}.####
10019 * @extends OO.ui.Widget
10020 * @mixins OO.ui.GroupElement
10021 * @mixins OO.ui.IconElement
10024 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
10025 * @param {Object} [config] Configuration options
10026 * @cfg {Object} [abilities] List of abilties
10027 * @cfg {boolean} [abilities.move=true] Allow moving movable items
10028 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
10030 OO
.ui
.OutlineControlsWidget
= function OoUiOutlineControlsWidget( outline
, config
) {
10031 // Allow passing positional parameters inside the config object
10032 if ( OO
.isPlainObject( outline
) && config
=== undefined ) {
10034 outline
= config
.outline
;
10037 // Configuration initialization
10038 config
= $.extend( { icon
: 'add' }, config
);
10040 // Parent constructor
10041 OO
.ui
.OutlineControlsWidget
.super.call( this, config
);
10043 // Mixin constructors
10044 OO
.ui
.GroupElement
.call( this, config
);
10045 OO
.ui
.IconElement
.call( this, config
);
10048 this.outline
= outline
;
10049 this.$movers
= $( '<div>' );
10050 this.upButton
= new OO
.ui
.ButtonWidget( {
10053 title
: OO
.ui
.msg( 'ooui-outline-control-move-up' )
10055 this.downButton
= new OO
.ui
.ButtonWidget( {
10058 title
: OO
.ui
.msg( 'ooui-outline-control-move-down' )
10060 this.removeButton
= new OO
.ui
.ButtonWidget( {
10063 title
: OO
.ui
.msg( 'ooui-outline-control-remove' )
10065 this.abilities
= { move: true, remove
: true };
10068 outline
.connect( this, {
10069 select
: 'onOutlineChange',
10070 add
: 'onOutlineChange',
10071 remove
: 'onOutlineChange'
10073 this.upButton
.connect( this, { click
: [ 'emit', 'move', -1 ] } );
10074 this.downButton
.connect( this, { click
: [ 'emit', 'move', 1 ] } );
10075 this.removeButton
.connect( this, { click
: [ 'emit', 'remove' ] } );
10078 this.$element
.addClass( 'oo-ui-outlineControlsWidget' );
10079 this.$group
.addClass( 'oo-ui-outlineControlsWidget-items' );
10081 .addClass( 'oo-ui-outlineControlsWidget-movers' )
10082 .append( this.removeButton
.$element
, this.upButton
.$element
, this.downButton
.$element
);
10083 this.$element
.append( this.$icon
, this.$group
, this.$movers
);
10084 this.setAbilities( config
.abilities
|| {} );
10089 OO
.inheritClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.Widget
);
10090 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.GroupElement
);
10091 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.IconElement
);
10097 * @param {number} places Number of places to move
10109 * @param {Object} abilities List of abilties
10110 * @param {boolean} [abilities.move] Allow moving movable items
10111 * @param {boolean} [abilities.remove] Allow removing removable items
10113 OO
.ui
.OutlineControlsWidget
.prototype.setAbilities = function ( abilities
) {
10116 for ( ability
in this.abilities
) {
10117 if ( abilities
[ability
] !== undefined ) {
10118 this.abilities
[ability
] = !!abilities
[ability
];
10122 this.onOutlineChange();
10128 * Handle outline change events.
10130 OO
.ui
.OutlineControlsWidget
.prototype.onOutlineChange = function () {
10131 var i
, len
, firstMovable
, lastMovable
,
10132 items
= this.outline
.getItems(),
10133 selectedItem
= this.outline
.getSelectedItem(),
10134 movable
= this.abilities
.move && selectedItem
&& selectedItem
.isMovable(),
10135 removable
= this.abilities
.remove
&& selectedItem
&& selectedItem
.isRemovable();
10139 len
= items
.length
;
10140 while ( ++i
< len
) {
10141 if ( items
[ i
].isMovable() ) {
10142 firstMovable
= items
[ i
];
10148 if ( items
[ i
].isMovable() ) {
10149 lastMovable
= items
[ i
];
10154 this.upButton
.setDisabled( !movable
|| selectedItem
=== firstMovable
);
10155 this.downButton
.setDisabled( !movable
|| selectedItem
=== lastMovable
);
10156 this.removeButton
.setDisabled( !removable
);
10160 * ToggleWidget is mixed into other classes to create widgets with an on/off state.
10161 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
10167 * @param {Object} [config] Configuration options
10168 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
10169 * By default, the toggle is in the 'off' state.
10171 OO
.ui
.ToggleWidget
= function OoUiToggleWidget( config
) {
10172 // Configuration initialization
10173 config
= config
|| {};
10179 this.$element
.addClass( 'oo-ui-toggleWidget' );
10180 this.setValue( !!config
.value
);
10188 * A change event is emitted when the on/off state of the toggle changes.
10190 * @param {boolean} value Value representing the new state of the toggle
10196 * Get the value representing the toggle’s state.
10198 * @return {boolean} The on/off state of the toggle
10200 OO
.ui
.ToggleWidget
.prototype.getValue = function () {
10205 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
10207 * @param {boolean} value The state of the toggle
10211 OO
.ui
.ToggleWidget
.prototype.setValue = function ( value
) {
10213 if ( this.value
!== value
) {
10214 this.value
= value
;
10215 this.emit( 'change', value
);
10216 this.$element
.toggleClass( 'oo-ui-toggleWidget-on', value
);
10217 this.$element
.toggleClass( 'oo-ui-toggleWidget-off', !value
);
10218 this.$element
.attr( 'aria-checked', value
.toString() );
10224 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
10225 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
10226 * removed, and cleared from the group.
10229 * // Example: A ButtonGroupWidget with two buttons
10230 * var button1 = new OO.ui.PopupButtonWidget( {
10231 * label: 'Select a category',
10234 * $content: $( '<p>List of categories...</p>' ),
10239 * var button2 = new OO.ui.ButtonWidget( {
10240 * label: 'Add item'
10242 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
10243 * items: [button1, button2]
10245 * $( 'body' ).append( buttonGroup.$element );
10248 * @extends OO.ui.Widget
10249 * @mixins OO.ui.GroupElement
10252 * @param {Object} [config] Configuration options
10253 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
10255 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
10256 // Configuration initialization
10257 config
= config
|| {};
10259 // Parent constructor
10260 OO
.ui
.ButtonGroupWidget
.super.call( this, config
);
10262 // Mixin constructors
10263 OO
.ui
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
10266 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
10267 if ( Array
.isArray( config
.items
) ) {
10268 this.addItems( config
.items
);
10274 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
10275 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.GroupElement
);
10278 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
10279 * feels, and functionality can be customized via the class’s configuration options
10280 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
10283 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
10286 * // A button widget
10287 * var button = new OO.ui.ButtonWidget( {
10288 * label: 'Button with Icon',
10290 * iconTitle: 'Remove'
10292 * $( 'body' ).append( button.$element );
10294 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
10297 * @extends OO.ui.Widget
10298 * @mixins OO.ui.ButtonElement
10299 * @mixins OO.ui.IconElement
10300 * @mixins OO.ui.IndicatorElement
10301 * @mixins OO.ui.LabelElement
10302 * @mixins OO.ui.TitledElement
10303 * @mixins OO.ui.FlaggedElement
10304 * @mixins OO.ui.TabIndexedElement
10307 * @param {Object} [config] Configuration options
10308 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
10309 * @cfg {string} [target] The frame or window in which to open the hyperlink.
10310 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
10312 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
10313 // Configuration initialization
10314 // FIXME: The `nofollow` alias is deprecated and will be removed (T89767)
10315 config
= $.extend( { noFollow
: config
&& config
.nofollow
}, config
);
10317 // Parent constructor
10318 OO
.ui
.ButtonWidget
.super.call( this, config
);
10320 // Mixin constructors
10321 OO
.ui
.ButtonElement
.call( this, config
);
10322 OO
.ui
.IconElement
.call( this, config
);
10323 OO
.ui
.IndicatorElement
.call( this, config
);
10324 OO
.ui
.LabelElement
.call( this, config
);
10325 OO
.ui
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
10326 OO
.ui
.FlaggedElement
.call( this, config
);
10327 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
10331 this.target
= null;
10332 this.noFollow
= false;
10333 this.isHyperlink
= false;
10336 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
10338 .addClass( 'oo-ui-buttonWidget' )
10339 .append( this.$button
);
10340 this.setHref( config
.href
);
10341 this.setTarget( config
.target
);
10342 this.setNoFollow( config
.noFollow
);
10347 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
10348 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.ButtonElement
);
10349 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.IconElement
);
10350 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.IndicatorElement
);
10351 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.LabelElement
);
10352 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.TitledElement
);
10353 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.FlaggedElement
);
10354 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.TabIndexedElement
);
10361 OO
.ui
.ButtonWidget
.prototype.onMouseDown = function ( e
) {
10362 if ( !this.isDisabled() ) {
10363 // Remove the tab-index while the button is down to prevent the button from stealing focus
10364 this.$button
.removeAttr( 'tabindex' );
10367 return OO
.ui
.ButtonElement
.prototype.onMouseDown
.call( this, e
);
10373 OO
.ui
.ButtonWidget
.prototype.onMouseUp = function ( e
) {
10374 if ( !this.isDisabled() ) {
10375 // Restore the tab-index after the button is up to restore the button's accessibility
10376 this.$button
.attr( 'tabindex', this.tabIndex
);
10379 return OO
.ui
.ButtonElement
.prototype.onMouseUp
.call( this, e
);
10385 OO
.ui
.ButtonWidget
.prototype.onClick = function ( e
) {
10386 var ret
= OO
.ui
.ButtonElement
.prototype.onClick
.call( this, e
);
10387 if ( this.isHyperlink
) {
10396 OO
.ui
.ButtonWidget
.prototype.onKeyPress = function ( e
) {
10397 var ret
= OO
.ui
.ButtonElement
.prototype.onKeyPress
.call( this, e
);
10398 if ( this.isHyperlink
) {
10405 * Get hyperlink location.
10407 * @return {string} Hyperlink location
10409 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
10414 * Get hyperlink target.
10416 * @return {string} Hyperlink target
10418 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
10419 return this.target
;
10423 * Get search engine traversal hint.
10425 * @return {boolean} Whether search engines should avoid traversing this hyperlink
10427 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
10428 return this.noFollow
;
10432 * Set hyperlink location.
10434 * @param {string|null} href Hyperlink location, null to remove
10436 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
10437 href
= typeof href
=== 'string' ? href
: null;
10439 if ( href
!== this.href
) {
10441 if ( href
!== null ) {
10442 this.$button
.attr( 'href', href
);
10443 this.isHyperlink
= true;
10445 this.$button
.removeAttr( 'href' );
10446 this.isHyperlink
= false;
10454 * Set hyperlink target.
10456 * @param {string|null} target Hyperlink target, null to remove
10458 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
10459 target
= typeof target
=== 'string' ? target
: null;
10461 if ( target
!== this.target
) {
10462 this.target
= target
;
10463 if ( target
!== null ) {
10464 this.$button
.attr( 'target', target
);
10466 this.$button
.removeAttr( 'target' );
10474 * Set search engine traversal hint.
10476 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
10478 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
10479 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
10481 if ( noFollow
!== this.noFollow
) {
10482 this.noFollow
= noFollow
;
10484 this.$button
.attr( 'rel', 'nofollow' );
10486 this.$button
.removeAttr( 'rel' );
10494 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
10495 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
10498 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
10499 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
10502 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
10505 * @extends OO.ui.ButtonWidget
10506 * @mixins OO.ui.PendingElement
10509 * @param {Object} [config] Configuration options
10510 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
10511 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
10512 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
10513 * for more information about setting modes.
10514 * @cfg {boolean} [framed=false] Render the action button with a frame
10516 OO
.ui
.ActionWidget
= function OoUiActionWidget( config
) {
10517 // Configuration initialization
10518 config
= $.extend( { framed
: false }, config
);
10520 // Parent constructor
10521 OO
.ui
.ActionWidget
.super.call( this, config
);
10523 // Mixin constructors
10524 OO
.ui
.PendingElement
.call( this, config
);
10527 this.action
= config
.action
|| '';
10528 this.modes
= config
.modes
|| [];
10533 this.$element
.addClass( 'oo-ui-actionWidget' );
10538 OO
.inheritClass( OO
.ui
.ActionWidget
, OO
.ui
.ButtonWidget
);
10539 OO
.mixinClass( OO
.ui
.ActionWidget
, OO
.ui
.PendingElement
);
10544 * A resize event is emitted when the size of the widget changes.
10552 * Check if the action is configured to be available in the specified `mode`.
10554 * @param {string} mode Name of mode
10555 * @return {boolean} The action is configured with the mode
10557 OO
.ui
.ActionWidget
.prototype.hasMode = function ( mode
) {
10558 return this.modes
.indexOf( mode
) !== -1;
10562 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
10566 OO
.ui
.ActionWidget
.prototype.getAction = function () {
10567 return this.action
;
10571 * Get the symbolic name of the mode or modes for which the action is configured to be available.
10573 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
10574 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
10577 * @return {string[]}
10579 OO
.ui
.ActionWidget
.prototype.getModes = function () {
10580 return this.modes
.slice();
10584 * Emit a resize event if the size has changed.
10589 OO
.ui
.ActionWidget
.prototype.propagateResize = function () {
10592 if ( this.isElementAttached() ) {
10593 width
= this.$element
.width();
10594 height
= this.$element
.height();
10596 if ( width
!== this.width
|| height
!== this.height
) {
10597 this.width
= width
;
10598 this.height
= height
;
10599 this.emit( 'resize' );
10609 OO
.ui
.ActionWidget
.prototype.setIcon = function () {
10611 OO
.ui
.IconElement
.prototype.setIcon
.apply( this, arguments
);
10612 this.propagateResize();
10620 OO
.ui
.ActionWidget
.prototype.setLabel = function () {
10622 OO
.ui
.LabelElement
.prototype.setLabel
.apply( this, arguments
);
10623 this.propagateResize();
10631 OO
.ui
.ActionWidget
.prototype.setFlags = function () {
10633 OO
.ui
.FlaggedElement
.prototype.setFlags
.apply( this, arguments
);
10634 this.propagateResize();
10642 OO
.ui
.ActionWidget
.prototype.clearFlags = function () {
10644 OO
.ui
.FlaggedElement
.prototype.clearFlags
.apply( this, arguments
);
10645 this.propagateResize();
10651 * Toggle the visibility of the action button.
10653 * @param {boolean} [show] Show button, omit to toggle visibility
10656 OO
.ui
.ActionWidget
.prototype.toggle = function () {
10658 OO
.ui
.ActionWidget
.super.prototype.toggle
.apply( this, arguments
);
10659 this.propagateResize();
10665 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
10666 * which is used to display additional information or options.
10669 * // Example of a popup button.
10670 * var popupButton = new OO.ui.PopupButtonWidget( {
10671 * label: 'Popup button with options',
10674 * $content: $( '<p>Additional options here.</p>' ),
10679 * // Append the button to the DOM.
10680 * $( 'body' ).append( popupButton.$element );
10683 * @extends OO.ui.ButtonWidget
10684 * @mixins OO.ui.PopupElement
10687 * @param {Object} [config] Configuration options
10689 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
10690 // Parent constructor
10691 OO
.ui
.PopupButtonWidget
.super.call( this, config
);
10693 // Mixin constructors
10694 OO
.ui
.PopupElement
.call( this, config
);
10697 this.connect( this, { click
: 'onAction' } );
10701 .addClass( 'oo-ui-popupButtonWidget' )
10702 .attr( 'aria-haspopup', 'true' )
10703 .append( this.popup
.$element
);
10708 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
10709 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.PopupElement
);
10714 * Handle the button action being triggered.
10718 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
10719 this.popup
.toggle();
10723 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
10724 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
10725 * configured with {@link OO.ui.IconElement icons}, {@link OO.ui.IndicatorElement indicators},
10726 * {@link OO.ui.TitledElement titles}, {@link OO.ui.FlaggedElement styling flags},
10727 * and {@link OO.ui.LabelElement labels}. Please see
10728 * the [OOjs UI documentation][1] on MediaWiki for more information.
10731 * // Toggle buttons in the 'off' and 'on' state.
10732 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
10733 * label: 'Toggle Button off'
10735 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
10736 * label: 'Toggle Button on',
10739 * // Append the buttons to the DOM.
10740 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
10742 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
10745 * @extends OO.ui.ButtonWidget
10746 * @mixins OO.ui.ToggleWidget
10749 * @param {Object} [config] Configuration options
10750 * @cfg {boolean} [value=false] The toggle button’s initial on/off
10751 * state. By default, the button is in the 'off' state.
10753 OO
.ui
.ToggleButtonWidget
= function OoUiToggleButtonWidget( config
) {
10754 // Configuration initialization
10755 config
= config
|| {};
10757 // Parent constructor
10758 OO
.ui
.ToggleButtonWidget
.super.call( this, config
);
10760 // Mixin constructors
10761 OO
.ui
.ToggleWidget
.call( this, config
);
10764 this.connect( this, { click
: 'onAction' } );
10767 this.$element
.addClass( 'oo-ui-toggleButtonWidget' );
10772 OO
.inheritClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.ButtonWidget
);
10773 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.ToggleWidget
);
10780 * Handle the button action being triggered.
10782 OO
.ui
.ToggleButtonWidget
.prototype.onAction = function () {
10783 this.setValue( !this.value
);
10789 OO
.ui
.ToggleButtonWidget
.prototype.setValue = function ( value
) {
10791 if ( value
!== this.value
) {
10792 this.$button
.attr( 'aria-pressed', value
.toString() );
10793 this.setActive( value
);
10796 // Parent method (from mixin)
10797 OO
.ui
.ToggleWidget
.prototype.setValue
.call( this, value
);
10803 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
10804 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
10805 * users can interact with it.
10808 * // Example: A DropdownWidget with a menu that contains three options
10809 * var dropDown = new OO.ui.DropdownWidget( {
10810 * label: 'Dropdown menu: Select a menu option',
10813 * new OO.ui.MenuOptionWidget( {
10817 * new OO.ui.MenuOptionWidget( {
10821 * new OO.ui.MenuOptionWidget( {
10829 * $( 'body' ).append( dropDown.$element );
10831 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
10833 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
10836 * @extends OO.ui.Widget
10837 * @mixins OO.ui.IconElement
10838 * @mixins OO.ui.IndicatorElement
10839 * @mixins OO.ui.LabelElement
10840 * @mixins OO.ui.TitledElement
10841 * @mixins OO.ui.TabIndexedElement
10844 * @param {Object} [config] Configuration options
10845 * @cfg {Object} [menu] Configuration options to pass to menu widget
10847 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
10848 // Configuration initialization
10849 config
= $.extend( { indicator
: 'down' }, config
);
10851 // Parent constructor
10852 OO
.ui
.DropdownWidget
.super.call( this, config
);
10854 // Properties (must be set before TabIndexedElement constructor call)
10855 this.$handle
= this.$( '<span>' );
10857 // Mixin constructors
10858 OO
.ui
.IconElement
.call( this, config
);
10859 OO
.ui
.IndicatorElement
.call( this, config
);
10860 OO
.ui
.LabelElement
.call( this, config
);
10861 OO
.ui
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
10862 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
10865 this.menu
= new OO
.ui
.MenuSelectWidget( $.extend( { widget
: this }, config
.menu
) );
10869 click
: this.onClick
.bind( this ),
10870 keypress
: this.onKeyPress
.bind( this )
10872 this.menu
.connect( this, { select
: 'onMenuSelect' } );
10876 .addClass( 'oo-ui-dropdownWidget-handle' )
10877 .append( this.$icon
, this.$label
, this.$indicator
);
10879 .addClass( 'oo-ui-dropdownWidget' )
10880 .append( this.$handle
, this.menu
.$element
);
10885 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
10886 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.IconElement
);
10887 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.IndicatorElement
);
10888 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.LabelElement
);
10889 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.TitledElement
);
10890 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.TabIndexedElement
);
10897 * @return {OO.ui.MenuSelectWidget} Menu of widget
10899 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
10904 * Handles menu select events.
10907 * @param {OO.ui.MenuOptionWidget} item Selected menu item
10909 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
10916 selectedLabel
= item
.getLabel();
10918 // If the label is a DOM element, clone it, because setLabel will append() it
10919 if ( selectedLabel
instanceof jQuery
) {
10920 selectedLabel
= selectedLabel
.clone();
10923 this.setLabel( selectedLabel
);
10927 * Handle mouse click events.
10930 * @param {jQuery.Event} e Mouse click event
10932 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
10933 if ( !this.isDisabled() && e
.which
=== 1 ) {
10934 this.menu
.toggle();
10940 * Handle key press events.
10943 * @param {jQuery.Event} e Key press event
10945 OO
.ui
.DropdownWidget
.prototype.onKeyPress = function ( e
) {
10946 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
10947 this.menu
.toggle();
10953 * IconWidget is a generic widget for {@link OO.ui.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
10954 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
10955 * for a list of icons included in the library.
10958 * // An icon widget with a label
10959 * var myIcon = new OO.ui.IconWidget( {
10961 * iconTitle: 'Help'
10963 * // Create a label.
10964 * var iconLabel = new OO.ui.LabelWidget( {
10967 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
10969 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
10972 * @extends OO.ui.Widget
10973 * @mixins OO.ui.IconElement
10974 * @mixins OO.ui.TitledElement
10975 * @mixins OO.ui.FlaggedElement
10978 * @param {Object} [config] Configuration options
10980 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
10981 // Configuration initialization
10982 config
= config
|| {};
10984 // Parent constructor
10985 OO
.ui
.IconWidget
.super.call( this, config
);
10987 // Mixin constructors
10988 OO
.ui
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
10989 OO
.ui
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
10990 OO
.ui
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
10993 this.$element
.addClass( 'oo-ui-iconWidget' );
10998 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
10999 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.IconElement
);
11000 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.TitledElement
);
11001 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.FlaggedElement
);
11003 /* Static Properties */
11005 OO
.ui
.IconWidget
.static.tagName
= 'span';
11008 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
11009 * attention to the status of an item or to clarify the function of a control. For a list of
11010 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
11013 * // Example of an indicator widget
11014 * var indicator1 = new OO.ui.IndicatorWidget( {
11015 * indicator: 'alert'
11018 * // Create a fieldset layout to add a label
11019 * var fieldset = new OO.ui.FieldsetLayout();
11020 * fieldset.addItems( [
11021 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
11023 * $( 'body' ).append( fieldset.$element );
11025 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
11028 * @extends OO.ui.Widget
11029 * @mixins OO.ui.IndicatorElement
11030 * @mixins OO.ui.TitledElement
11033 * @param {Object} [config] Configuration options
11035 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
11036 // Configuration initialization
11037 config
= config
|| {};
11039 // Parent constructor
11040 OO
.ui
.IndicatorWidget
.super.call( this, config
);
11042 // Mixin constructors
11043 OO
.ui
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
11044 OO
.ui
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
11047 this.$element
.addClass( 'oo-ui-indicatorWidget' );
11052 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
11053 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.IndicatorElement
);
11054 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.TitledElement
);
11056 /* Static Properties */
11058 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
11061 * InputWidget is the base class for all input widgets, which
11062 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
11063 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
11064 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
11066 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11070 * @extends OO.ui.Widget
11071 * @mixins OO.ui.FlaggedElement
11072 * @mixins OO.ui.TabIndexedElement
11075 * @param {Object} [config] Configuration options
11076 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
11077 * @cfg {string} [value=''] The value of the input.
11078 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
11079 * before it is accepted.
11081 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
11082 // Configuration initialization
11083 config
= config
|| {};
11085 // Parent constructor
11086 OO
.ui
.InputWidget
.super.call( this, config
);
11089 this.$input
= this.getInputElement( config
);
11091 this.inputFilter
= config
.inputFilter
;
11093 // Mixin constructors
11094 OO
.ui
.FlaggedElement
.call( this, config
);
11095 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
11098 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
11102 .attr( 'name', config
.name
)
11103 .prop( 'disabled', this.isDisabled() );
11104 this.$element
.addClass( 'oo-ui-inputWidget' ).append( this.$input
, $( '<span>' ) );
11105 this.setValue( config
.value
);
11110 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
11111 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.FlaggedElement
);
11112 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.TabIndexedElement
);
11119 * A change event is emitted when the value of the input changes.
11121 * @param {string} value
11127 * Get input element.
11129 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
11130 * different circumstances. The element must have a `value` property (like form elements).
11133 * @param {Object} config Configuration options
11134 * @return {jQuery} Input element
11136 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
11137 return $( '<input>' );
11141 * Handle potentially value-changing events.
11144 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
11146 OO
.ui
.InputWidget
.prototype.onEdit = function () {
11148 if ( !this.isDisabled() ) {
11149 // Allow the stack to clear so the value will be updated
11150 setTimeout( function () {
11151 widget
.setValue( widget
.$input
.val() );
11157 * Get the value of the input.
11159 * @return {string} Input value
11161 OO
.ui
.InputWidget
.prototype.getValue = function () {
11162 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
11163 // it, and we won't know unless they're kind enough to trigger a 'change' event.
11164 var value
= this.$input
.val();
11165 if ( this.value
!== value
) {
11166 this.setValue( value
);
11172 * Set the direction of the input, either RTL (right-to-left) or LTR (left-to-right).
11174 * @param {boolean} isRTL
11175 * Direction is right-to-left
11177 OO
.ui
.InputWidget
.prototype.setRTL = function ( isRTL
) {
11178 this.$input
.prop( 'dir', isRTL
? 'rtl' : 'ltr' );
11182 * Set the value of the input.
11184 * @param {string} value New value
11188 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
11189 value
= this.cleanUpValue( value
);
11190 // Update the DOM if it has changed. Note that with cleanUpValue, it
11191 // is possible for the DOM value to change without this.value changing.
11192 if ( this.$input
.val() !== value
) {
11193 this.$input
.val( value
);
11195 if ( this.value
!== value
) {
11196 this.value
= value
;
11197 this.emit( 'change', this.value
);
11203 * Clean up incoming value.
11205 * Ensures value is a string, and converts undefined and null to empty string.
11208 * @param {string} value Original value
11209 * @return {string} Cleaned up value
11211 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
11212 if ( value
=== undefined || value
=== null ) {
11214 } else if ( this.inputFilter
) {
11215 return this.inputFilter( String( value
) );
11217 return String( value
);
11222 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
11223 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
11226 OO
.ui
.InputWidget
.prototype.simulateLabelClick = function () {
11227 if ( !this.isDisabled() ) {
11228 if ( this.$input
.is( ':checkbox, :radio' ) ) {
11229 this.$input
.click();
11231 if ( this.$input
.is( ':input' ) ) {
11232 this.$input
[ 0 ].focus();
11240 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
11241 OO
.ui
.InputWidget
.super.prototype.setDisabled
.call( this, state
);
11242 if ( this.$input
) {
11243 this.$input
.prop( 'disabled', this.isDisabled() );
11253 OO
.ui
.InputWidget
.prototype.focus = function () {
11254 this.$input
[ 0 ].focus();
11263 OO
.ui
.InputWidget
.prototype.blur = function () {
11264 this.$input
[ 0 ].blur();
11269 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
11270 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
11271 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
11272 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
11273 * [OOjs UI documentation on MediaWiki] [1] for more information.
11276 * // A ButtonInputWidget rendered as an HTML button, the default.
11277 * var button = new OO.ui.ButtonInputWidget( {
11278 * label: 'Input button',
11282 * $( 'body' ).append( button.$element );
11284 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
11287 * @extends OO.ui.InputWidget
11288 * @mixins OO.ui.ButtonElement
11289 * @mixins OO.ui.IconElement
11290 * @mixins OO.ui.IndicatorElement
11291 * @mixins OO.ui.LabelElement
11292 * @mixins OO.ui.TitledElement
11293 * @mixins OO.ui.FlaggedElement
11296 * @param {Object} [config] Configuration options
11297 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
11298 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
11299 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
11300 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
11301 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
11303 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
11304 // Configuration initialization
11305 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
11307 // Properties (must be set before parent constructor, which calls #setValue)
11308 this.useInputTag
= config
.useInputTag
;
11310 // Parent constructor
11311 OO
.ui
.ButtonInputWidget
.super.call( this, config
);
11313 // Mixin constructors
11314 OO
.ui
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
11315 OO
.ui
.IconElement
.call( this, config
);
11316 OO
.ui
.IndicatorElement
.call( this, config
);
11317 OO
.ui
.LabelElement
.call( this, config
);
11318 OO
.ui
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
11319 OO
.ui
.FlaggedElement
.call( this, config
);
11322 if ( !config
.useInputTag
) {
11323 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
11325 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
11330 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
11331 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.ButtonElement
);
11332 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.IconElement
);
11333 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.IndicatorElement
);
11334 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.LabelElement
);
11335 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.TitledElement
);
11336 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.FlaggedElement
);
11344 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
11345 var html
= '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + config
.type
+ '">';
11352 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
11354 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
11355 * text, or `null` for no label
11358 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
11359 OO
.ui
.LabelElement
.prototype.setLabel
.call( this, label
);
11361 if ( this.useInputTag
) {
11362 if ( typeof label
=== 'function' ) {
11363 label
= OO
.ui
.resolveMsg( label
);
11365 if ( label
instanceof jQuery
) {
11366 label
= label
.text();
11371 this.$input
.val( label
);
11378 * Set the value of the input.
11380 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
11381 * they do not support {@link #value values}.
11383 * @param {string} value New value
11386 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
11387 if ( !this.useInputTag
) {
11388 OO
.ui
.ButtonInputWidget
.super.prototype.setValue
.call( this, value
);
11394 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
11395 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
11396 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
11397 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
11400 * // An example of selected, unselected, and disabled checkbox inputs
11401 * var checkbox1=new OO.ui.CheckboxInputWidget( {
11405 * var checkbox2=new OO.ui.CheckboxInputWidget( {
11408 * var checkbox3=new OO.ui.CheckboxInputWidget( {
11412 * // Create a fieldset layout with fields for each checkbox.
11413 * var fieldset = new OO.ui.FieldsetLayout( {
11414 * label: 'Checkboxes'
11416 * fieldset.addItems( [
11417 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
11418 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
11419 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
11421 * $( 'body' ).append( fieldset.$element );
11423 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11426 * @extends OO.ui.InputWidget
11429 * @param {Object} [config] Configuration options
11430 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
11432 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
11433 // Configuration initialization
11434 config
= config
|| {};
11436 // Parent constructor
11437 OO
.ui
.CheckboxInputWidget
.super.call( this, config
);
11440 this.$element
.addClass( 'oo-ui-checkboxInputWidget' );
11441 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
11446 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
11454 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
11455 return $( '<input type="checkbox" />' );
11461 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
11463 if ( !this.isDisabled() ) {
11464 // Allow the stack to clear so the value will be updated
11465 setTimeout( function () {
11466 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
11472 * Set selection state of this checkbox.
11474 * @param {boolean} state `true` for selected
11477 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
11479 if ( this.selected
!== state
) {
11480 this.selected
= state
;
11481 this.$input
.prop( 'checked', this.selected
);
11482 this.emit( 'change', this.selected
);
11488 * Check if this checkbox is selected.
11490 * @return {boolean} Checkbox is selected
11492 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
11493 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
11494 // it, and we won't know unless they're kind enough to trigger a 'change' event.
11495 var selected
= this.$input
.prop( 'checked' );
11496 if ( this.selected
!== selected
) {
11497 this.setSelected( selected
);
11499 return this.selected
;
11503 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
11504 * within a {@link OO.ui.FormLayout form}. The selected value is synchronized with the value
11505 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
11506 * more information about input widgets.
11509 * // Example: A DropdownInputWidget with three options
11510 * var dropDown = new OO.ui.DropdownInputWidget( {
11511 * label: 'Dropdown menu: Select a menu option',
11513 * { data: 'a', label: 'First' } ,
11514 * { data: 'b', label: 'Second'} ,
11515 * { data: 'c', label: 'Third' }
11518 * $( 'body' ).append( dropDown.$element );
11520 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11523 * @extends OO.ui.InputWidget
11526 * @param {Object} [config] Configuration options
11527 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
11529 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
11530 // Configuration initialization
11531 config
= config
|| {};
11533 // Properties (must be done before parent constructor which calls #setDisabled)
11534 this.dropdownWidget
= new OO
.ui
.DropdownWidget();
11536 // Parent constructor
11537 OO
.ui
.DropdownInputWidget
.super.call( this, config
);
11540 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
11543 this.setOptions( config
.options
|| [] );
11545 .addClass( 'oo-ui-dropdownInputWidget' )
11546 .append( this.dropdownWidget
.$element
);
11551 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
11559 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
11560 return $( '<input type="hidden">' );
11564 * Handles menu select events.
11567 * @param {OO.ui.MenuOptionWidget} item Selected menu item
11569 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
11570 this.setValue( item
.getData() );
11576 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
11577 var item
= this.dropdownWidget
.getMenu().getItemFromData( value
);
11579 this.dropdownWidget
.getMenu().selectItem( item
);
11581 OO
.ui
.DropdownInputWidget
.super.prototype.setValue
.call( this, value
);
11588 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
11589 this.dropdownWidget
.setDisabled( state
);
11590 OO
.ui
.DropdownInputWidget
.super.prototype.setDisabled
.call( this, state
);
11595 * Set the options available for this input.
11597 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
11600 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
11601 var value
= this.getValue();
11603 // Rebuild the dropdown menu
11604 this.dropdownWidget
.getMenu()
11606 .addItems( options
.map( function ( opt
) {
11607 return new OO
.ui
.MenuOptionWidget( {
11609 label
: opt
.label
!== undefined ? opt
.label
: opt
.data
11613 // Restore the previous value, or reset to something sensible
11614 if ( this.dropdownWidget
.getMenu().getItemFromData( value
) ) {
11615 // Previous value is still available, ensure consistency with the dropdown
11616 this.setValue( value
);
11618 // No longer valid, reset
11619 if ( options
.length
) {
11620 this.setValue( options
[ 0 ].data
);
11630 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
11631 this.dropdownWidget
.getMenu().toggle( true );
11638 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
11639 this.dropdownWidget
.getMenu().toggle( false );
11644 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
11645 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
11646 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
11647 * please see the [OOjs UI documentation on MediaWiki][1].
11650 * // An example of selected, unselected, and disabled radio inputs
11651 * var radio1 = new OO.ui.RadioInputWidget( {
11655 * var radio2 = new OO.ui.RadioInputWidget( {
11658 * var radio3 = new OO.ui.RadioInputWidget( {
11662 * // Create a fieldset layout with fields for each radio button.
11663 * var fieldset = new OO.ui.FieldsetLayout( {
11664 * label: 'Radio inputs'
11666 * fieldset.addItems( [
11667 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
11668 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
11669 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
11671 * $( 'body' ).append( fieldset.$element );
11673 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11676 * @extends OO.ui.InputWidget
11679 * @param {Object} [config] Configuration options
11680 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
11682 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
11683 // Configuration initialization
11684 config
= config
|| {};
11686 // Parent constructor
11687 OO
.ui
.RadioInputWidget
.super.call( this, config
);
11690 this.$element
.addClass( 'oo-ui-radioInputWidget' );
11691 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
11696 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
11704 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
11705 return $( '<input type="radio" />' );
11711 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
11712 // RadioInputWidget doesn't track its state.
11716 * Set selection state of this radio button.
11718 * @param {boolean} state `true` for selected
11721 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
11722 // RadioInputWidget doesn't track its state.
11723 this.$input
.prop( 'checked', state
);
11728 * Check if this radio button is selected.
11730 * @return {boolean} Radio is selected
11732 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
11733 return this.$input
.prop( 'checked' );
11737 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
11738 * size of the field as well as its presentation. In addition, these widgets can be configured
11739 * with {@link OO.ui.IconElement icons}, {@link OO.ui.IndicatorElement indicators}, an optional
11740 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
11741 * which modifies incoming values rather than validating them.
11742 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
11745 * // Example of a text input widget
11746 * var textInput = new OO.ui.TextInputWidget( {
11747 * value: 'Text input'
11749 * $( 'body' ).append( textInput.$element );
11751 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11754 * @extends OO.ui.InputWidget
11755 * @mixins OO.ui.IconElement
11756 * @mixins OO.ui.IndicatorElement
11757 * @mixins OO.ui.PendingElement
11758 * @mixins OO.ui.LabelElement
11761 * @param {Object} [config] Configuration options
11762 * @cfg {string} [type='text'] The value of the HTML `type` attribute
11763 * @cfg {string} [placeholder] Placeholder text
11764 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
11765 * instruct the browser to focus this widget.
11766 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
11767 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
11768 * @cfg {boolean} [multiline=false] Allow multiple lines of text
11769 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
11770 * Use the #maxRows config to specify a maximum number of displayed rows.
11771 * @cfg {boolean} [maxRows=10] Maximum number of rows to display when #autosize is set to true.
11772 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
11773 * the value or placeholder text: `'before'` or `'after'`
11774 * @cfg {boolean} [required=false] Mark the field as required
11775 * @cfg {RegExp|string} [validate] Validation pattern, either a regular expression or the
11776 * symbolic name of a pattern defined by the class: 'non-empty' (the value cannot be an empty string)
11777 * or 'integer' (the value must contain only numbers).
11779 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
11780 // Configuration initialization
11781 config
= $.extend( {
11783 labelPosition
: 'after',
11787 // Parent constructor
11788 OO
.ui
.TextInputWidget
.super.call( this, config
);
11790 // Mixin constructors
11791 OO
.ui
.IconElement
.call( this, config
);
11792 OO
.ui
.IndicatorElement
.call( this, config
);
11793 OO
.ui
.PendingElement
.call( this, config
);
11794 OO
.ui
.LabelElement
.call( this, config
);
11797 this.readOnly
= false;
11798 this.multiline
= !!config
.multiline
;
11799 this.autosize
= !!config
.autosize
;
11800 this.maxRows
= config
.maxRows
;
11801 this.validate
= null;
11803 // Clone for resizing
11804 if ( this.autosize
) {
11805 this.$clone
= this.$input
11807 .insertAfter( this.$input
)
11808 .attr( 'aria-hidden', 'true' )
11809 .addClass( 'oo-ui-element-hidden' );
11812 this.setValidation( config
.validate
);
11813 this.setLabelPosition( config
.labelPosition
);
11817 keypress
: this.onKeyPress
.bind( this ),
11818 blur
: this.setValidityFlag
.bind( this )
11821 focus
: this.onElementAttach
.bind( this )
11823 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
11824 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
11825 this.on( 'labelChange', this.updatePosition
.bind( this ) );
11829 .addClass( 'oo-ui-textInputWidget' )
11830 .append( this.$icon
, this.$indicator
);
11831 this.setReadOnly( !!config
.readOnly
);
11832 if ( config
.placeholder
) {
11833 this.$input
.attr( 'placeholder', config
.placeholder
);
11835 if ( config
.maxLength
!== undefined ) {
11836 this.$input
.attr( 'maxlength', config
.maxLength
);
11838 if ( config
.autofocus
) {
11839 this.$input
.attr( 'autofocus', 'autofocus' );
11841 if ( config
.required
) {
11842 this.$input
.attr( 'required', 'true' );
11844 if ( this.label
|| config
.autosize
) {
11845 this.installParentChangeDetector();
11851 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
11852 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.IconElement
);
11853 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.IndicatorElement
);
11854 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.PendingElement
);
11855 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.LabelElement
);
11857 /* Static properties */
11859 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
11867 * An `enter` event is emitted when the user presses 'enter' inside the text box.
11869 * Not emitted if the input is multiline.
11877 * Handle icon mouse down events.
11880 * @param {jQuery.Event} e Mouse down event
11883 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
11884 if ( e
.which
=== 1 ) {
11885 this.$input
[ 0 ].focus();
11891 * Handle indicator mouse down events.
11894 * @param {jQuery.Event} e Mouse down event
11897 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
11898 if ( e
.which
=== 1 ) {
11899 this.$input
[ 0 ].focus();
11905 * Handle key press events.
11908 * @param {jQuery.Event} e Key press event
11909 * @fires enter If enter key is pressed and input is not multiline
11911 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
11912 if ( e
.which
=== OO
.ui
.Keys
.ENTER
&& !this.multiline
) {
11913 this.emit( 'enter', e
);
11918 * Handle element attach events.
11921 * @param {jQuery.Event} e Element attach event
11923 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
11924 // Any previously calculated size is now probably invalid if we reattached elsewhere
11925 this.valCache
= null;
11927 this.positionLabel();
11933 OO
.ui
.TextInputWidget
.prototype.onEdit = function () {
11937 return OO
.ui
.TextInputWidget
.super.prototype.onEdit
.call( this );
11943 OO
.ui
.TextInputWidget
.prototype.setValue = function ( value
) {
11945 OO
.ui
.TextInputWidget
.super.prototype.setValue
.call( this, value
);
11947 this.setValidityFlag();
11953 * Check if the input is {@link #readOnly read-only}.
11955 * @return {boolean}
11957 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
11958 return this.readOnly
;
11962 * Set the {@link #readOnly read-only} state of the input.
11964 * @param {boolean} state Make input read-only
11967 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
11968 this.readOnly
= !!state
;
11969 this.$input
.prop( 'readOnly', this.readOnly
);
11974 * Support function for making #onElementAttach work across browsers.
11976 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
11977 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
11979 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
11980 * first time that the element gets attached to the documented.
11982 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
11983 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
11984 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
11987 if ( MutationObserver
) {
11988 // The new way. If only it wasn't so ugly.
11990 if ( this.$element
.closest( 'html' ).length
) {
11991 // Widget is attached already, do nothing. This breaks the functionality of this function when
11992 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
11993 // would require observation of the whole document, which would hurt performance of other,
11994 // more important code.
11998 // Find topmost node in the tree
11999 topmostNode
= this.$element
[0];
12000 while ( topmostNode
.parentNode
) {
12001 topmostNode
= topmostNode
.parentNode
;
12004 // We have no way to detect the $element being attached somewhere without observing the entire
12005 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
12006 // parent node of $element, and instead detect when $element is removed from it (and thus
12007 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
12008 // doesn't get attached, we end up back here and create the parent.
12010 mutationObserver
= new MutationObserver( function ( mutations
) {
12011 var i
, j
, removedNodes
;
12012 for ( i
= 0; i
< mutations
.length
; i
++ ) {
12013 removedNodes
= mutations
[ i
].removedNodes
;
12014 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
12015 if ( removedNodes
[ j
] === topmostNode
) {
12016 setTimeout( onRemove
, 0 );
12023 onRemove = function () {
12024 // If the node was attached somewhere else, report it
12025 if ( widget
.$element
.closest( 'html' ).length
) {
12026 widget
.onElementAttach();
12028 mutationObserver
.disconnect();
12029 widget
.installParentChangeDetector();
12032 // Create a fake parent and observe it
12033 fakeParentNode
= $( '<div>' ).append( this.$element
)[0];
12034 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
12036 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
12037 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
12038 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
12043 * Automatically adjust the size of the text input.
12045 * This only affects #multiline inputs that are {@link #autosize autosized}.
12049 OO
.ui
.TextInputWidget
.prototype.adjustSize = function () {
12050 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
, idealHeight
;
12052 if ( this.multiline
&& this.autosize
&& this.$input
.val() !== this.valCache
) {
12054 .val( this.$input
.val() )
12055 .attr( 'rows', '' )
12056 // Set inline height property to 0 to measure scroll height
12057 .css( 'height', 0 );
12059 this.$clone
.removeClass( 'oo-ui-element-hidden' );
12061 this.valCache
= this.$input
.val();
12063 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
12065 // Remove inline height property to measure natural heights
12066 this.$clone
.css( 'height', '' );
12067 innerHeight
= this.$clone
.innerHeight();
12068 outerHeight
= this.$clone
.outerHeight();
12070 // Measure max rows height
12072 .attr( 'rows', this.maxRows
)
12073 .css( 'height', 'auto' )
12075 maxInnerHeight
= this.$clone
.innerHeight();
12077 // Difference between reported innerHeight and scrollHeight with no scrollbars present
12078 // Equals 1 on Blink-based browsers and 0 everywhere else
12079 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
12080 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
12082 this.$clone
.addClass( 'oo-ui-element-hidden' );
12084 // Only apply inline height when expansion beyond natural height is needed
12085 if ( idealHeight
> innerHeight
) {
12086 // Use the difference between the inner and outer height as a buffer
12087 this.$input
.css( 'height', idealHeight
+ ( outerHeight
- innerHeight
) );
12089 this.$input
.css( 'height', '' );
12099 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
12100 return config
.multiline
? $( '<textarea>' ) : $( '<input type="' + config
.type
+ '" />' );
12104 * Check if the input supports multiple lines.
12106 * @return {boolean}
12108 OO
.ui
.TextInputWidget
.prototype.isMultiline = function () {
12109 return !!this.multiline
;
12113 * Check if the input automatically adjusts its size.
12115 * @return {boolean}
12117 OO
.ui
.TextInputWidget
.prototype.isAutosizing = function () {
12118 return !!this.autosize
;
12122 * Select the entire text of the input.
12126 OO
.ui
.TextInputWidget
.prototype.select = function () {
12127 this.$input
.select();
12132 * Set the validation pattern.
12134 * The validation pattern is either a regular expression or the symbolic name of a pattern
12135 * defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
12136 * value must contain only numbers).
12138 * @param {RegExp|string|null} validate Regular expression or the symbolic name of a
12139 * pattern (either ‘integer’ or ‘non-empty’) defined by the class.
12141 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
12142 if ( validate
instanceof RegExp
) {
12143 this.validate
= validate
;
12145 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
12150 * Sets the 'invalid' flag appropriately.
12152 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function () {
12154 this.isValid().done( function ( valid
) {
12155 widget
.setFlags( { invalid
: !valid
} );
12160 * Check if a value is valid.
12162 * This method returns a promise that resolves with a boolean `true` if the current value is
12163 * considered valid according to the supplied {@link #validate validation pattern}.
12165 * @return {jQuery.Deferred} A promise that resolves to a boolean `true` if the value is valid.
12167 OO
.ui
.TextInputWidget
.prototype.isValid = function () {
12168 return $.Deferred().resolve( !!this.getValue().match( this.validate
) ).promise();
12172 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
12174 * @param {string} labelPosition Label position, 'before' or 'after'
12177 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
12178 this.labelPosition
= labelPosition
;
12179 this.updatePosition();
12184 * Deprecated alias of #setLabelPosition
12186 * @deprecated Use setLabelPosition instead.
12188 OO
.ui
.TextInputWidget
.prototype.setPosition
=
12189 OO
.ui
.TextInputWidget
.prototype.setLabelPosition
;
12192 * Update the position of the inline label.
12194 * This method is called by #setLabelPosition, and can also be called on its own if
12195 * something causes the label to be mispositioned.
12200 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
12201 var after
= this.labelPosition
=== 'after';
12204 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
12205 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
12207 if ( this.label
) {
12208 this.positionLabel();
12215 * Position the label by setting the correct padding on the input.
12220 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
12221 // Clear old values
12223 // Clear old values if present
12225 'padding-right': '',
12229 if ( this.label
) {
12230 this.$element
.append( this.$label
);
12232 this.$label
.detach();
12236 var after
= this.labelPosition
=== 'after',
12237 rtl
= this.$element
.css( 'direction' ) === 'rtl',
12238 property
= after
=== rtl
? 'padding-left' : 'padding-right';
12240 this.$input
.css( property
, this.$label
.outerWidth( true ) );
12246 * ComboBoxWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
12247 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
12248 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
12250 * - by typing a value in the text input field. If the value exactly matches the value of a menu
12251 * option, that option will appear to be selected.
12252 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
12255 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
12258 * // Example: A ComboBoxWidget.
12259 * var comboBox = new OO.ui.ComboBoxWidget( {
12260 * label: 'ComboBoxWidget',
12261 * input: { value: 'Option One' },
12264 * new OO.ui.MenuOptionWidget( {
12265 * data: 'Option 1',
12266 * label: 'Option One'
12268 * new OO.ui.MenuOptionWidget( {
12269 * data: 'Option 2',
12270 * label: 'Option Two'
12272 * new OO.ui.MenuOptionWidget( {
12273 * data: 'Option 3',
12274 * label: 'Option Three'
12276 * new OO.ui.MenuOptionWidget( {
12277 * data: 'Option 4',
12278 * label: 'Option Four'
12280 * new OO.ui.MenuOptionWidget( {
12281 * data: 'Option 5',
12282 * label: 'Option Five'
12287 * $( 'body' ).append( comboBox.$element );
12289 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
12292 * @extends OO.ui.Widget
12293 * @mixins OO.ui.TabIndexedElement
12296 * @param {Object} [config] Configuration options
12297 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
12298 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
12299 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
12300 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
12301 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
12303 OO
.ui
.ComboBoxWidget
= function OoUiComboBoxWidget( config
) {
12304 // Configuration initialization
12305 config
= config
|| {};
12307 // Parent constructor
12308 OO
.ui
.ComboBoxWidget
.super.call( this, config
);
12310 // Properties (must be set before TabIndexedElement constructor call)
12311 this.$indicator
= this.$( '<span>' );
12313 // Mixin constructors
12314 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$indicator
} ) );
12317 this.$overlay
= config
.$overlay
|| this.$element
;
12318 this.input
= new OO
.ui
.TextInputWidget( $.extend(
12321 $indicator
: this.$indicator
,
12322 disabled
: this.isDisabled()
12326 this.input
.$input
.eq( 0 ).attr( {
12328 'aria-autocomplete': 'list'
12330 this.menu
= new OO
.ui
.TextInputMenuSelectWidget( this.input
, $.extend(
12334 disabled
: this.isDisabled()
12340 this.$indicator
.on( {
12341 click
: this.onClick
.bind( this ),
12342 keypress
: this.onKeyPress
.bind( this )
12344 this.input
.connect( this, {
12345 change
: 'onInputChange',
12346 enter
: 'onInputEnter'
12348 this.menu
.connect( this, {
12349 choose
: 'onMenuChoose',
12350 add
: 'onMenuItemsChange',
12351 remove
: 'onMenuItemsChange'
12355 this.$element
.addClass( 'oo-ui-comboBoxWidget' ).append( this.input
.$element
);
12356 this.$overlay
.append( this.menu
.$element
);
12357 this.onMenuItemsChange();
12362 OO
.inheritClass( OO
.ui
.ComboBoxWidget
, OO
.ui
.Widget
);
12363 OO
.mixinClass( OO
.ui
.ComboBoxWidget
, OO
.ui
.TabIndexedElement
);
12368 * Get the combobox's menu.
12369 * @return {OO.ui.TextInputMenuSelectWidget} Menu widget
12371 OO
.ui
.ComboBoxWidget
.prototype.getMenu = function () {
12376 * Handle input change events.
12379 * @param {string} value New value
12381 OO
.ui
.ComboBoxWidget
.prototype.onInputChange = function ( value
) {
12382 var match
= this.menu
.getItemFromData( value
);
12384 this.menu
.selectItem( match
);
12385 if ( this.menu
.getHighlightedItem() ) {
12386 this.menu
.highlightItem( match
);
12389 if ( !this.isDisabled() ) {
12390 this.menu
.toggle( true );
12395 * Handle mouse click events.
12399 * @param {jQuery.Event} e Mouse click event
12401 OO
.ui
.ComboBoxWidget
.prototype.onClick = function ( e
) {
12402 if ( !this.isDisabled() && e
.which
=== 1 ) {
12403 this.menu
.toggle();
12404 this.input
.$input
[ 0 ].focus();
12410 * Handle key press events.
12414 * @param {jQuery.Event} e Key press event
12416 OO
.ui
.ComboBoxWidget
.prototype.onKeyPress = function ( e
) {
12417 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
12418 this.menu
.toggle();
12419 this.input
.$input
[ 0 ].focus();
12425 * Handle input enter events.
12429 OO
.ui
.ComboBoxWidget
.prototype.onInputEnter = function () {
12430 if ( !this.isDisabled() ) {
12431 this.menu
.toggle( false );
12436 * Handle menu choose events.
12439 * @param {OO.ui.OptionWidget} item Chosen item
12441 OO
.ui
.ComboBoxWidget
.prototype.onMenuChoose = function ( item
) {
12442 this.input
.setValue( item
.getData() );
12446 * Handle menu item change events.
12450 OO
.ui
.ComboBoxWidget
.prototype.onMenuItemsChange = function () {
12451 var match
= this.menu
.getItemFromData( this.input
.getValue() );
12452 this.menu
.selectItem( match
);
12453 if ( this.menu
.getHighlightedItem() ) {
12454 this.menu
.highlightItem( match
);
12456 this.$element
.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu
.isEmpty() );
12462 OO
.ui
.ComboBoxWidget
.prototype.setDisabled = function ( disabled
) {
12464 OO
.ui
.ComboBoxWidget
.super.prototype.setDisabled
.call( this, disabled
);
12466 if ( this.input
) {
12467 this.input
.setDisabled( this.isDisabled() );
12470 this.menu
.setDisabled( this.isDisabled() );
12477 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
12478 * be configured with a `label` option that is set to a string, a label node, or a function:
12480 * - String: a plaintext string
12481 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
12482 * label that includes a link or special styling, such as a gray color or additional graphical elements.
12483 * - Function: a function that will produce a string in the future. Functions are used
12484 * in cases where the value of the label is not currently defined.
12486 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
12487 * will come into focus when the label is clicked.
12490 * // Examples of LabelWidgets
12491 * var label1 = new OO.ui.LabelWidget( {
12492 * label: 'plaintext label'
12494 * var label2 = new OO.ui.LabelWidget( {
12495 * label: $( '<a href="default.html">jQuery label</a>' )
12497 * // Create a fieldset layout with fields for each example
12498 * var fieldset = new OO.ui.FieldsetLayout();
12499 * fieldset.addItems( [
12500 * new OO.ui.FieldLayout( label1 ),
12501 * new OO.ui.FieldLayout( label2 )
12503 * $( 'body' ).append( fieldset.$element );
12507 * @extends OO.ui.Widget
12508 * @mixins OO.ui.LabelElement
12511 * @param {Object} [config] Configuration options
12512 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
12513 * Clicking the label will focus the specified input field.
12515 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
12516 // Configuration initialization
12517 config
= config
|| {};
12519 // Parent constructor
12520 OO
.ui
.LabelWidget
.super.call( this, config
);
12522 // Mixin constructors
12523 OO
.ui
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
12524 OO
.ui
.TitledElement
.call( this, config
);
12527 this.input
= config
.input
;
12530 if ( this.input
instanceof OO
.ui
.InputWidget
) {
12531 this.$element
.on( 'click', this.onClick
.bind( this ) );
12535 this.$element
.addClass( 'oo-ui-labelWidget' );
12540 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
12541 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.LabelElement
);
12542 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.TitledElement
);
12544 /* Static Properties */
12546 OO
.ui
.LabelWidget
.static.tagName
= 'span';
12551 * Handles label mouse click events.
12554 * @param {jQuery.Event} e Mouse click event
12556 OO
.ui
.LabelWidget
.prototype.onClick = function () {
12557 this.input
.simulateLabelClick();
12562 * OptionWidgets are special elements that can be selected and configured with data. The
12563 * data is often unique for each option, but it does not have to be. OptionWidgets are used
12564 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
12565 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
12567 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
12570 * @extends OO.ui.Widget
12571 * @mixins OO.ui.LabelElement
12572 * @mixins OO.ui.FlaggedElement
12575 * @param {Object} [config] Configuration options
12577 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
12578 // Configuration initialization
12579 config
= config
|| {};
12581 // Parent constructor
12582 OO
.ui
.OptionWidget
.super.call( this, config
);
12584 // Mixin constructors
12585 OO
.ui
.ItemWidget
.call( this );
12586 OO
.ui
.LabelElement
.call( this, config
);
12587 OO
.ui
.FlaggedElement
.call( this, config
);
12590 this.selected
= false;
12591 this.highlighted
= false;
12592 this.pressed
= false;
12596 .data( 'oo-ui-optionWidget', this )
12597 .attr( 'role', 'option' )
12598 .addClass( 'oo-ui-optionWidget' )
12599 .append( this.$label
);
12604 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
12605 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.ItemWidget
);
12606 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.LabelElement
);
12607 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.FlaggedElement
);
12609 /* Static Properties */
12611 OO
.ui
.OptionWidget
.static.selectable
= true;
12613 OO
.ui
.OptionWidget
.static.highlightable
= true;
12615 OO
.ui
.OptionWidget
.static.pressable
= true;
12617 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
12622 * Check if the option can be selected.
12624 * @return {boolean} Item is selectable
12626 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
12627 return this.constructor.static.selectable
&& !this.isDisabled();
12631 * Check if the option can be highlighted. A highlight indicates that the option
12632 * may be selected when a user presses enter or clicks. Disabled items cannot
12635 * @return {boolean} Item is highlightable
12637 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
12638 return this.constructor.static.highlightable
&& !this.isDisabled();
12642 * Check if the option can be pressed. The pressed state occurs when a user mouses
12643 * down on an item, but has not yet let go of the mouse.
12645 * @return {boolean} Item is pressable
12647 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
12648 return this.constructor.static.pressable
&& !this.isDisabled();
12652 * Check if the option is selected.
12654 * @return {boolean} Item is selected
12656 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
12657 return this.selected
;
12661 * Check if the option is highlighted. A highlight indicates that the
12662 * item may be selected when a user presses enter or clicks.
12664 * @return {boolean} Item is highlighted
12666 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
12667 return this.highlighted
;
12671 * Check if the option is pressed. The pressed state occurs when a user mouses
12672 * down on an item, but has not yet let go of the mouse. The item may appear
12673 * selected, but it will not be selected until the user releases the mouse.
12675 * @return {boolean} Item is pressed
12677 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
12678 return this.pressed
;
12682 * Set the option’s selected state. In general, all modifications to the selection
12683 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
12684 * method instead of this method.
12686 * @param {boolean} [state=false] Select option
12689 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
12690 if ( this.constructor.static.selectable
) {
12691 this.selected
= !!state
;
12693 .toggleClass( 'oo-ui-optionWidget-selected', state
)
12694 .attr( 'aria-selected', state
.toString() );
12695 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
12696 this.scrollElementIntoView();
12698 this.updateThemeClasses();
12704 * Set the option’s highlighted state. In general, all programmatic
12705 * modifications to the highlight should be handled by the
12706 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
12707 * method instead of this method.
12709 * @param {boolean} [state=false] Highlight option
12712 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
12713 if ( this.constructor.static.highlightable
) {
12714 this.highlighted
= !!state
;
12715 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
12716 this.updateThemeClasses();
12722 * Set the option’s pressed state. In general, all
12723 * programmatic modifications to the pressed state should be handled by the
12724 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
12725 * method instead of this method.
12727 * @param {boolean} [state=false] Press option
12730 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
12731 if ( this.constructor.static.pressable
) {
12732 this.pressed
= !!state
;
12733 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
12734 this.updateThemeClasses();
12740 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
12741 * with an {@link OO.ui.IconElement icon} and/or {@link OO.ui.IndicatorElement indicator}.
12742 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
12743 * options. For more information about options and selects, please see the
12744 * [OOjs UI documentation on MediaWiki][1].
12747 * // Decorated options in a select widget
12748 * var select = new OO.ui.SelectWidget( {
12750 * new OO.ui.DecoratedOptionWidget( {
12752 * label: 'Option with icon',
12755 * new OO.ui.DecoratedOptionWidget( {
12757 * label: 'Option with indicator',
12758 * indicator: 'next'
12762 * $( 'body' ).append( select.$element );
12764 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
12767 * @extends OO.ui.OptionWidget
12768 * @mixins OO.ui.IconElement
12769 * @mixins OO.ui.IndicatorElement
12772 * @param {Object} [config] Configuration options
12774 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
12775 // Parent constructor
12776 OO
.ui
.DecoratedOptionWidget
.super.call( this, config
);
12778 // Mixin constructors
12779 OO
.ui
.IconElement
.call( this, config
);
12780 OO
.ui
.IndicatorElement
.call( this, config
);
12784 .addClass( 'oo-ui-decoratedOptionWidget' )
12785 .prepend( this.$icon
)
12786 .append( this.$indicator
);
12791 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
12792 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.IconElement
);
12793 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.IndicatorElement
);
12796 * ButtonOptionWidget is a special type of {@link OO.ui.ButtonElement button element} that
12797 * can be selected and configured with data. The class is
12798 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
12799 * [OOjs UI documentation on MediaWiki] [1] for more information.
12801 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
12804 * @extends OO.ui.DecoratedOptionWidget
12805 * @mixins OO.ui.ButtonElement
12806 * @mixins OO.ui.TabIndexedElement
12809 * @param {Object} [config] Configuration options
12811 OO
.ui
.ButtonOptionWidget
= function OoUiButtonOptionWidget( config
) {
12812 // Configuration initialization
12813 config
= $.extend( { tabIndex
: -1 }, config
);
12815 // Parent constructor
12816 OO
.ui
.ButtonOptionWidget
.super.call( this, config
);
12818 // Mixin constructors
12819 OO
.ui
.ButtonElement
.call( this, config
);
12820 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
12823 this.$element
.addClass( 'oo-ui-buttonOptionWidget' );
12824 this.$button
.append( this.$element
.contents() );
12825 this.$element
.append( this.$button
);
12830 OO
.inheritClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
12831 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.ButtonElement
);
12832 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.TabIndexedElement
);
12834 /* Static Properties */
12836 // Allow button mouse down events to pass through so they can be handled by the parent select widget
12837 OO
.ui
.ButtonOptionWidget
.static.cancelButtonMouseDownEvents
= false;
12839 OO
.ui
.ButtonOptionWidget
.static.highlightable
= false;
12846 OO
.ui
.ButtonOptionWidget
.prototype.setSelected = function ( state
) {
12847 OO
.ui
.ButtonOptionWidget
.super.prototype.setSelected
.call( this, state
);
12849 if ( this.constructor.static.selectable
) {
12850 this.setActive( state
);
12857 * RadioOptionWidget is an option widget that looks like a radio button.
12858 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
12859 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
12861 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
12864 * @extends OO.ui.OptionWidget
12867 * @param {Object} [config] Configuration options
12869 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
12870 // Configuration initialization
12871 config
= config
|| {};
12873 // Properties (must be done before parent constructor which calls #setDisabled)
12874 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
12876 // Parent constructor
12877 OO
.ui
.RadioOptionWidget
.super.call( this, config
);
12881 .addClass( 'oo-ui-radioOptionWidget' )
12882 .prepend( this.radio
.$element
);
12887 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
12889 /* Static Properties */
12891 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
12893 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
12895 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
12897 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
12904 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
12905 OO
.ui
.RadioOptionWidget
.super.prototype.setSelected
.call( this, state
);
12907 this.radio
.setSelected( state
);
12915 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
12916 OO
.ui
.RadioOptionWidget
.super.prototype.setDisabled
.call( this, disabled
);
12918 this.radio
.setDisabled( this.isDisabled() );
12924 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
12925 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
12926 * the [OOjs UI documentation on MediaWiki] [1] for more information.
12928 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
12931 * @extends OO.ui.DecoratedOptionWidget
12934 * @param {Object} [config] Configuration options
12936 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
12937 // Configuration initialization
12938 config
= $.extend( { icon
: 'check' }, config
);
12940 // Parent constructor
12941 OO
.ui
.MenuOptionWidget
.super.call( this, config
);
12945 .attr( 'role', 'menuitem' )
12946 .addClass( 'oo-ui-menuOptionWidget' );
12951 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
12953 /* Static Properties */
12955 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
12958 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
12959 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
12962 * var myDropdown = new OO.ui.DropdownWidget( {
12965 * new OO.ui.MenuSectionOptionWidget( {
12968 * new OO.ui.MenuOptionWidget( {
12970 * label: 'Welsh Corgi'
12972 * new OO.ui.MenuOptionWidget( {
12974 * label: 'Standard Poodle'
12976 * new OO.ui.MenuSectionOptionWidget( {
12979 * new OO.ui.MenuOptionWidget( {
12986 * $( 'body' ).append( myDropdown.$element );
12990 * @extends OO.ui.DecoratedOptionWidget
12993 * @param {Object} [config] Configuration options
12995 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
12996 // Parent constructor
12997 OO
.ui
.MenuSectionOptionWidget
.super.call( this, config
);
13000 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' );
13005 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
13007 /* Static Properties */
13009 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
13011 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
13014 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
13016 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
13017 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
13021 * @extends OO.ui.DecoratedOptionWidget
13024 * @param {Object} [config] Configuration options
13025 * @cfg {number} [level] Indentation level
13026 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
13028 OO
.ui
.OutlineOptionWidget
= function OoUiOutlineOptionWidget( config
) {
13029 // Configuration initialization
13030 config
= config
|| {};
13032 // Parent constructor
13033 OO
.ui
.OutlineOptionWidget
.super.call( this, config
);
13037 this.movable
= !!config
.movable
;
13038 this.removable
= !!config
.removable
;
13041 this.$element
.addClass( 'oo-ui-outlineOptionWidget' );
13042 this.setLevel( config
.level
);
13047 OO
.inheritClass( OO
.ui
.OutlineOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
13049 /* Static Properties */
13051 OO
.ui
.OutlineOptionWidget
.static.highlightable
= false;
13053 OO
.ui
.OutlineOptionWidget
.static.scrollIntoViewOnSelect
= true;
13055 OO
.ui
.OutlineOptionWidget
.static.levelClass
= 'oo-ui-outlineOptionWidget-level-';
13057 OO
.ui
.OutlineOptionWidget
.static.levels
= 3;
13062 * Check if item is movable.
13064 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
13066 * @return {boolean} Item is movable
13068 OO
.ui
.OutlineOptionWidget
.prototype.isMovable = function () {
13069 return this.movable
;
13073 * Check if item is removable.
13075 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
13077 * @return {boolean} Item is removable
13079 OO
.ui
.OutlineOptionWidget
.prototype.isRemovable = function () {
13080 return this.removable
;
13084 * Get indentation level.
13086 * @return {number} Indentation level
13088 OO
.ui
.OutlineOptionWidget
.prototype.getLevel = function () {
13095 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
13097 * @param {boolean} movable Item is movable
13100 OO
.ui
.OutlineOptionWidget
.prototype.setMovable = function ( movable
) {
13101 this.movable
= !!movable
;
13102 this.updateThemeClasses();
13107 * Set removability.
13109 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
13111 * @param {boolean} movable Item is removable
13114 OO
.ui
.OutlineOptionWidget
.prototype.setRemovable = function ( removable
) {
13115 this.removable
= !!removable
;
13116 this.updateThemeClasses();
13121 * Set indentation level.
13123 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
13126 OO
.ui
.OutlineOptionWidget
.prototype.setLevel = function ( level
) {
13127 var levels
= this.constructor.static.levels
,
13128 levelClass
= this.constructor.static.levelClass
,
13131 this.level
= level
? Math
.max( 0, Math
.min( levels
- 1, level
) ) : 0;
13133 if ( this.level
=== i
) {
13134 this.$element
.addClass( levelClass
+ i
);
13136 this.$element
.removeClass( levelClass
+ i
);
13139 this.updateThemeClasses();
13145 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
13146 * By default, each popup has an anchor that points toward its origin.
13147 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
13150 * // A popup widget.
13151 * var popup = new OO.ui.PopupWidget( {
13152 * $content: $( '<p>Hi there!</p>' ),
13157 * $( 'body' ).append( popup.$element );
13158 * // To display the popup, toggle the visibility to 'true'.
13159 * popup.toggle( true );
13161 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
13164 * @extends OO.ui.Widget
13165 * @mixins OO.ui.LabelElement
13168 * @param {Object} [config] Configuration options
13169 * @cfg {number} [width=320] Width of popup in pixels
13170 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
13171 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
13172 * @cfg {string} [align='center'] Alignment of the popup: `center`, `left`, or `right`.
13173 * If the popup is right-aligned, the right edge of the popup is aligned to the anchor.
13174 * For left-aligned popups, the left edge is aligned to the anchor.
13175 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
13176 * See the [OOjs UI docs on MediaWiki][3] for an example.
13177 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
13178 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
13179 * @cfg {jQuery} [$content] Content to append to the popup's body
13180 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
13181 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
13182 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
13184 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
13185 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
13187 * @cfg {boolean} [padded] Add padding to the popup's body
13189 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
13190 // Configuration initialization
13191 config
= config
|| {};
13193 // Parent constructor
13194 OO
.ui
.PopupWidget
.super.call( this, config
);
13196 // Properties (must be set before ClippableElement constructor call)
13197 this.$body
= $( '<div>' );
13199 // Mixin constructors
13200 OO
.ui
.LabelElement
.call( this, config
);
13201 OO
.ui
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$body
} ) );
13204 this.$popup
= $( '<div>' );
13205 this.$head
= $( '<div>' );
13206 this.$anchor
= $( '<div>' );
13207 // If undefined, will be computed lazily in updateDimensions()
13208 this.$container
= config
.$container
;
13209 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
13210 this.autoClose
= !!config
.autoClose
;
13211 this.$autoCloseIgnore
= config
.$autoCloseIgnore
;
13212 this.transitionTimeout
= null;
13213 this.anchor
= null;
13214 this.width
= config
.width
!== undefined ? config
.width
: 320;
13215 this.height
= config
.height
!== undefined ? config
.height
: null;
13216 this.align
= config
.align
|| 'center';
13217 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
13218 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
13219 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
13222 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
13225 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
13226 this.$body
.addClass( 'oo-ui-popupWidget-body' );
13227 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
13229 .addClass( 'oo-ui-popupWidget-head' )
13230 .append( this.$label
, this.closeButton
.$element
);
13231 if ( !config
.head
) {
13232 this.$head
.addClass( 'oo-ui-element-hidden' );
13235 .addClass( 'oo-ui-popupWidget-popup' )
13236 .append( this.$head
, this.$body
);
13238 .addClass( 'oo-ui-popupWidget' )
13239 .append( this.$popup
, this.$anchor
);
13240 // Move content, which was added to #$element by OO.ui.Widget, to the body
13241 if ( config
.$content
instanceof jQuery
) {
13242 this.$body
.append( config
.$content
);
13244 if ( config
.padded
) {
13245 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
13248 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
13249 // that reference properties not initialized at that time of parent class construction
13250 // TODO: Find a better way to handle post-constructor setup
13251 this.visible
= false;
13252 this.$element
.addClass( 'oo-ui-element-hidden' );
13257 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
13258 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.LabelElement
);
13259 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.ClippableElement
);
13264 * Handles mouse down events.
13267 * @param {MouseEvent} e Mouse down event
13269 OO
.ui
.PopupWidget
.prototype.onMouseDown = function ( e
) {
13271 this.isVisible() &&
13272 !$.contains( this.$element
[ 0 ], e
.target
) &&
13273 ( !this.$autoCloseIgnore
|| !this.$autoCloseIgnore
.has( e
.target
).length
)
13275 this.toggle( false );
13280 * Bind mouse down listener.
13284 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
13285 // Capture clicks outside popup
13286 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler
, true );
13290 * Handles close button click events.
13294 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
13295 if ( this.isVisible() ) {
13296 this.toggle( false );
13301 * Unbind mouse down listener.
13305 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
13306 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler
, true );
13310 * Handles key down events.
13313 * @param {KeyboardEvent} e Key down event
13315 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
13317 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
13320 this.toggle( false );
13321 e
.preventDefault();
13322 e
.stopPropagation();
13327 * Bind key down listener.
13331 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
13332 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
13336 * Unbind key down listener.
13340 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
13341 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
13345 * Show, hide, or toggle the visibility of the anchor.
13347 * @param {boolean} [show] Show anchor, omit to toggle
13349 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
13350 show
= show
=== undefined ? !this.anchored
: !!show
;
13352 if ( this.anchored
!== show
) {
13354 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
13356 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
13358 this.anchored
= show
;
13363 * Check if the anchor is visible.
13365 * @return {boolean} Anchor is visible
13367 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
13368 return this.anchor
;
13374 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
13375 show
= show
=== undefined ? !this.isVisible() : !!show
;
13377 var change
= show
!== this.isVisible();
13380 OO
.ui
.PopupWidget
.super.prototype.toggle
.call( this, show
);
13384 if ( this.autoClose
) {
13385 this.bindMouseDownListener();
13386 this.bindKeyDownListener();
13388 this.updateDimensions();
13389 this.toggleClipping( true );
13391 this.toggleClipping( false );
13392 if ( this.autoClose
) {
13393 this.unbindMouseDownListener();
13394 this.unbindKeyDownListener();
13403 * Set the size of the popup.
13405 * Changing the size may also change the popup's position depending on the alignment.
13407 * @param {number} width Width in pixels
13408 * @param {number} height Height in pixels
13409 * @param {boolean} [transition=false] Use a smooth transition
13412 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
13413 this.width
= width
;
13414 this.height
= height
!== undefined ? height
: null;
13415 if ( this.isVisible() ) {
13416 this.updateDimensions( transition
);
13421 * Update the size and position.
13423 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
13424 * be called automatically.
13426 * @param {boolean} [transition=false] Use a smooth transition
13429 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
13430 var popupOffset
, originOffset
, containerLeft
, containerWidth
, containerRight
,
13431 popupLeft
, popupRight
, overlapLeft
, overlapRight
, anchorWidth
,
13434 if ( !this.$container
) {
13435 // Lazy-initialize $container if not specified in constructor
13436 this.$container
= $( this.getClosestScrollableElementContainer() );
13439 // Set height and width before measuring things, since it might cause our measurements
13440 // to change (e.g. due to scrollbars appearing or disappearing)
13443 height
: this.height
!== null ? this.height
: 'auto'
13446 // Compute initial popupOffset based on alignment
13447 popupOffset
= this.width
* ( { left
: 0, center
: -0.5, right
: -1 } )[ this.align
];
13449 // Figure out if this will cause the popup to go beyond the edge of the container
13450 originOffset
= this.$element
.offset().left
;
13451 containerLeft
= this.$container
.offset().left
;
13452 containerWidth
= this.$container
.innerWidth();
13453 containerRight
= containerLeft
+ containerWidth
;
13454 popupLeft
= popupOffset
- this.containerPadding
;
13455 popupRight
= popupOffset
+ this.containerPadding
+ this.width
+ this.containerPadding
;
13456 overlapLeft
= ( originOffset
+ popupLeft
) - containerLeft
;
13457 overlapRight
= containerRight
- ( originOffset
+ popupRight
);
13459 // Adjust offset to make the popup not go beyond the edge, if needed
13460 if ( overlapRight
< 0 ) {
13461 popupOffset
+= overlapRight
;
13462 } else if ( overlapLeft
< 0 ) {
13463 popupOffset
-= overlapLeft
;
13466 // Adjust offset to avoid anchor being rendered too close to the edge
13467 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
13468 // TODO: Find a measurement that works for CSS anchors and image anchors
13469 anchorWidth
= this.$anchor
[ 0 ].scrollWidth
* 2;
13470 if ( popupOffset
+ this.width
< anchorWidth
) {
13471 popupOffset
= anchorWidth
- this.width
;
13472 } else if ( -popupOffset
< anchorWidth
) {
13473 popupOffset
= -anchorWidth
;
13476 // Prevent transition from being interrupted
13477 clearTimeout( this.transitionTimeout
);
13478 if ( transition
) {
13479 // Enable transition
13480 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
13483 // Position body relative to anchor
13484 this.$popup
.css( 'margin-left', popupOffset
);
13486 if ( transition
) {
13487 // Prevent transitioning after transition is complete
13488 this.transitionTimeout
= setTimeout( function () {
13489 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
13492 // Prevent transitioning immediately
13493 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
13496 // Reevaluate clipping state since we've relocated and resized the popup
13503 * Progress bars visually display the status of an operation, such as a download,
13504 * and can be either determinate or indeterminate:
13506 * - **determinate** process bars show the percent of an operation that is complete.
13508 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
13509 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
13510 * not use percentages.
13512 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
13515 * // Examples of determinate and indeterminate progress bars.
13516 * var progressBar1 = new OO.ui.ProgressBarWidget( {
13519 * var progressBar2 = new OO.ui.ProgressBarWidget();
13521 * // Create a FieldsetLayout to layout progress bars
13522 * var fieldset = new OO.ui.FieldsetLayout;
13523 * fieldset.addItems( [
13524 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
13525 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
13527 * $( 'body' ).append( fieldset.$element );
13530 * @extends OO.ui.Widget
13533 * @param {Object} [config] Configuration options
13534 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
13535 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
13536 * By default, the progress bar is indeterminate.
13538 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
13539 // Configuration initialization
13540 config
= config
|| {};
13542 // Parent constructor
13543 OO
.ui
.ProgressBarWidget
.super.call( this, config
);
13546 this.$bar
= $( '<div>' );
13547 this.progress
= null;
13550 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
13551 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
13554 role
: 'progressbar',
13555 'aria-valuemin': 0,
13556 'aria-valuemax': 100
13558 .addClass( 'oo-ui-progressBarWidget' )
13559 .append( this.$bar
);
13564 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
13566 /* Static Properties */
13568 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
13573 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
13575 * @return {number|boolean} Progress percent
13577 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
13578 return this.progress
;
13582 * Set the percent of the process completed or `false` for an indeterminate process.
13584 * @param {number|boolean} progress Progress percent or `false` for indeterminate
13586 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
13587 this.progress
= progress
;
13589 if ( progress
!== false ) {
13590 this.$bar
.css( 'width', this.progress
+ '%' );
13591 this.$element
.attr( 'aria-valuenow', this.progress
);
13593 this.$bar
.css( 'width', '' );
13594 this.$element
.removeAttr( 'aria-valuenow' );
13596 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress
);
13600 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
13601 * and a {@link OO.ui.TextInputMenuSelectWidget menu} of search results, which is displayed beneath the query
13602 * field. Unlike {@link OO.ui.LookupElement lookup menus}, search result menus are always visible to the user.
13603 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
13604 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
13606 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
13607 * the [OOjs UI demos][1] for an example.
13609 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
13612 * @extends OO.ui.Widget
13615 * @param {Object} [config] Configuration options
13616 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
13617 * @cfg {string} [value] Initial query value
13619 OO
.ui
.SearchWidget
= function OoUiSearchWidget( config
) {
13620 // Configuration initialization
13621 config
= config
|| {};
13623 // Parent constructor
13624 OO
.ui
.SearchWidget
.super.call( this, config
);
13627 this.query
= new OO
.ui
.TextInputWidget( {
13629 placeholder
: config
.placeholder
,
13630 value
: config
.value
13632 this.results
= new OO
.ui
.SelectWidget();
13633 this.$query
= $( '<div>' );
13634 this.$results
= $( '<div>' );
13637 this.query
.connect( this, {
13638 change
: 'onQueryChange',
13639 enter
: 'onQueryEnter'
13641 this.results
.connect( this, {
13642 highlight
: 'onResultsHighlight',
13643 select
: 'onResultsSelect'
13645 this.query
.$input
.on( 'keydown', this.onQueryKeydown
.bind( this ) );
13649 .addClass( 'oo-ui-searchWidget-query' )
13650 .append( this.query
.$element
);
13652 .addClass( 'oo-ui-searchWidget-results' )
13653 .append( this.results
.$element
);
13655 .addClass( 'oo-ui-searchWidget' )
13656 .append( this.$results
, this.$query
);
13661 OO
.inheritClass( OO
.ui
.SearchWidget
, OO
.ui
.Widget
);
13666 * A 'highlight' event is emitted when an item is highlighted. The highlight indicates which
13667 * item will be selected. When a user mouses over a menu item, it is highlighted. If a search
13668 * string is typed into the query field instead, the first menu item that matches the query
13669 * will be highlighted.
13672 * @deprecated Connect straight to getResults() events instead
13673 * @param {Object|null} item Item data or null if no item is highlighted
13677 * A 'select' event is emitted when an item is selected. A menu item is selected when it is clicked,
13678 * or when a user types a search query, a menu result is highlighted, and the user presses enter.
13681 * @deprecated Connect straight to getResults() events instead
13682 * @param {Object|null} item Item data or null if no item is selected
13688 * Handle query key down events.
13691 * @param {jQuery.Event} e Key down event
13693 OO
.ui
.SearchWidget
.prototype.onQueryKeydown = function ( e
) {
13694 var highlightedItem
, nextItem
,
13695 dir
= e
.which
=== OO
.ui
.Keys
.DOWN
? 1 : ( e
.which
=== OO
.ui
.Keys
.UP
? -1 : 0 );
13698 highlightedItem
= this.results
.getHighlightedItem();
13699 if ( !highlightedItem
) {
13700 highlightedItem
= this.results
.getSelectedItem();
13702 nextItem
= this.results
.getRelativeSelectableItem( highlightedItem
, dir
);
13703 this.results
.highlightItem( nextItem
);
13704 nextItem
.scrollElementIntoView();
13709 * Handle select widget select events.
13711 * Clears existing results. Subclasses should repopulate items according to new query.
13714 * @param {string} value New value
13716 OO
.ui
.SearchWidget
.prototype.onQueryChange = function () {
13718 this.results
.clearItems();
13722 * Handle select widget enter key events.
13724 * Selects highlighted item.
13727 * @param {string} value New value
13729 OO
.ui
.SearchWidget
.prototype.onQueryEnter = function () {
13731 this.results
.selectItem( this.results
.getHighlightedItem() );
13735 * Handle select widget highlight events.
13738 * @deprecated Connect straight to getResults() events instead
13739 * @param {OO.ui.OptionWidget} item Highlighted item
13742 OO
.ui
.SearchWidget
.prototype.onResultsHighlight = function ( item
) {
13743 this.emit( 'highlight', item
? item
.getData() : null );
13747 * Handle select widget select events.
13750 * @deprecated Connect straight to getResults() events instead
13751 * @param {OO.ui.OptionWidget} item Selected item
13754 OO
.ui
.SearchWidget
.prototype.onResultsSelect = function ( item
) {
13755 this.emit( 'select', item
? item
.getData() : null );
13759 * Get the query input.
13761 * @return {OO.ui.TextInputWidget} Query input
13763 OO
.ui
.SearchWidget
.prototype.getQuery = function () {
13768 * Get the search results menu.
13770 * @return {OO.ui.SelectWidget} Menu of search results
13772 OO
.ui
.SearchWidget
.prototype.getResults = function () {
13773 return this.results
;
13777 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
13778 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
13779 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
13782 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
13783 * information, please see the [OOjs UI documentation on MediaWiki][1].
13786 * // Example of a select widget with three options
13787 * var select = new OO.ui.SelectWidget( {
13789 * new OO.ui.OptionWidget( {
13791 * label: 'Option One',
13793 * new OO.ui.OptionWidget( {
13795 * label: 'Option Two',
13797 * new OO.ui.OptionWidget( {
13799 * label: 'Option Three',
13803 * $( 'body' ).append( select.$element );
13805 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
13808 * @extends OO.ui.Widget
13809 * @mixins OO.ui.GroupElement
13812 * @param {Object} [config] Configuration options
13813 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
13814 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
13815 * the [OOjs UI documentation on MediaWiki] [2] for examples.
13816 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
13818 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
13819 // Configuration initialization
13820 config
= config
|| {};
13822 // Parent constructor
13823 OO
.ui
.SelectWidget
.super.call( this, config
);
13825 // Mixin constructors
13826 OO
.ui
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
13829 this.pressed
= false;
13830 this.selecting
= null;
13831 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
13832 this.onMouseMoveHandler
= this.onMouseMove
.bind( this );
13833 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
13836 this.$element
.on( {
13837 mousedown
: this.onMouseDown
.bind( this ),
13838 mouseover
: this.onMouseOver
.bind( this ),
13839 mouseleave
: this.onMouseLeave
.bind( this )
13844 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
13845 .attr( 'role', 'listbox' );
13846 if ( Array
.isArray( config
.items
) ) {
13847 this.addItems( config
.items
);
13853 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
13855 // Need to mixin base class as well
13856 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.GroupElement
);
13857 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.GroupWidget
);
13864 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
13866 * @param {OO.ui.OptionWidget|null} item Highlighted item
13872 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
13873 * pressed state of an option.
13875 * @param {OO.ui.OptionWidget|null} item Pressed item
13881 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
13883 * @param {OO.ui.OptionWidget|null} item Selected item
13888 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
13889 * @param {OO.ui.OptionWidget} item Chosen item
13895 * An `add` event is emitted when options are added to the select with the #addItems method.
13897 * @param {OO.ui.OptionWidget[]} items Added items
13898 * @param {number} index Index of insertion point
13904 * A `remove` event is emitted when options are removed from the select with the #clearItems
13905 * or #removeItems methods.
13907 * @param {OO.ui.OptionWidget[]} items Removed items
13913 * Handle mouse down events.
13916 * @param {jQuery.Event} e Mouse down event
13918 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
13921 if ( !this.isDisabled() && e
.which
=== 1 ) {
13922 this.togglePressed( true );
13923 item
= this.getTargetItem( e
);
13924 if ( item
&& item
.isSelectable() ) {
13925 this.pressItem( item
);
13926 this.selecting
= item
;
13927 this.getElementDocument().addEventListener(
13929 this.onMouseUpHandler
,
13932 this.getElementDocument().addEventListener(
13934 this.onMouseMoveHandler
,
13943 * Handle mouse up events.
13946 * @param {jQuery.Event} e Mouse up event
13948 OO
.ui
.SelectWidget
.prototype.onMouseUp = function ( e
) {
13951 this.togglePressed( false );
13952 if ( !this.selecting
) {
13953 item
= this.getTargetItem( e
);
13954 if ( item
&& item
.isSelectable() ) {
13955 this.selecting
= item
;
13958 if ( !this.isDisabled() && e
.which
=== 1 && this.selecting
) {
13959 this.pressItem( null );
13960 this.chooseItem( this.selecting
);
13961 this.selecting
= null;
13964 this.getElementDocument().removeEventListener(
13966 this.onMouseUpHandler
,
13969 this.getElementDocument().removeEventListener(
13971 this.onMouseMoveHandler
,
13979 * Handle mouse move events.
13982 * @param {jQuery.Event} e Mouse move event
13984 OO
.ui
.SelectWidget
.prototype.onMouseMove = function ( e
) {
13987 if ( !this.isDisabled() && this.pressed
) {
13988 item
= this.getTargetItem( e
);
13989 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
13990 this.pressItem( item
);
13991 this.selecting
= item
;
13998 * Handle mouse over events.
14001 * @param {jQuery.Event} e Mouse over event
14003 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
14006 if ( !this.isDisabled() ) {
14007 item
= this.getTargetItem( e
);
14008 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
14014 * Handle mouse leave events.
14017 * @param {jQuery.Event} e Mouse over event
14019 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
14020 if ( !this.isDisabled() ) {
14021 this.highlightItem( null );
14027 * Handle key down events.
14030 * @param {jQuery.Event} e Key down event
14032 OO
.ui
.SelectWidget
.prototype.onKeyDown = function ( e
) {
14035 currentItem
= this.getHighlightedItem() || this.getSelectedItem();
14037 if ( !this.isDisabled() && this.isVisible() ) {
14038 switch ( e
.keyCode
) {
14039 case OO
.ui
.Keys
.ENTER
:
14040 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
14041 // Was only highlighted, now let's select it. No-op if already selected.
14042 this.chooseItem( currentItem
);
14046 case OO
.ui
.Keys
.UP
:
14047 case OO
.ui
.Keys
.LEFT
:
14048 nextItem
= this.getRelativeSelectableItem( currentItem
, -1 );
14051 case OO
.ui
.Keys
.DOWN
:
14052 case OO
.ui
.Keys
.RIGHT
:
14053 nextItem
= this.getRelativeSelectableItem( currentItem
, 1 );
14056 case OO
.ui
.Keys
.ESCAPE
:
14057 case OO
.ui
.Keys
.TAB
:
14058 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
14059 currentItem
.setHighlighted( false );
14061 this.unbindKeyDownListener();
14062 // Don't prevent tabbing away / defocusing
14068 if ( nextItem
.constructor.static.highlightable
) {
14069 this.highlightItem( nextItem
);
14071 this.chooseItem( nextItem
);
14073 nextItem
.scrollElementIntoView();
14077 // Can't just return false, because e is not always a jQuery event
14078 e
.preventDefault();
14079 e
.stopPropagation();
14085 * Bind key down listener.
14089 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
14090 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler
, true );
14094 * Unbind key down listener.
14098 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
14099 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler
, true );
14103 * Get the closest item to a jQuery.Event.
14106 * @param {jQuery.Event} e
14107 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
14109 OO
.ui
.SelectWidget
.prototype.getTargetItem = function ( e
) {
14110 var $item
= $( e
.target
).closest( '.oo-ui-optionWidget' );
14111 if ( $item
.length
) {
14112 return $item
.data( 'oo-ui-optionWidget' );
14118 * Get selected item.
14120 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
14122 OO
.ui
.SelectWidget
.prototype.getSelectedItem = function () {
14125 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
14126 if ( this.items
[ i
].isSelected() ) {
14127 return this.items
[ i
];
14134 * Get highlighted item.
14136 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
14138 OO
.ui
.SelectWidget
.prototype.getHighlightedItem = function () {
14141 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
14142 if ( this.items
[ i
].isHighlighted() ) {
14143 return this.items
[ i
];
14150 * Toggle pressed state.
14152 * Press is a state that occurs when a user mouses down on an item, but
14153 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
14154 * until the user releases the mouse.
14156 * @param {boolean} pressed An option is being pressed
14158 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
14159 if ( pressed
=== undefined ) {
14160 pressed
= !this.pressed
;
14162 if ( pressed
!== this.pressed
) {
14164 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
14165 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
14166 this.pressed
= pressed
;
14171 * Highlight an option. If the `item` param is omitted, no options will be highlighted
14172 * and any existing highlight will be removed. The highlight is mutually exclusive.
14174 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
14178 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
14179 var i
, len
, highlighted
,
14182 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
14183 highlighted
= this.items
[ i
] === item
;
14184 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
14185 this.items
[ i
].setHighlighted( highlighted
);
14190 this.emit( 'highlight', item
);
14197 * Programmatically select an option by its reference. If the `item` parameter is omitted,
14198 * all options will be deselected.
14200 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
14204 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
14205 var i
, len
, selected
,
14208 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
14209 selected
= this.items
[ i
] === item
;
14210 if ( this.items
[ i
].isSelected() !== selected
) {
14211 this.items
[ i
].setSelected( selected
);
14216 this.emit( 'select', item
);
14225 * Press is a state that occurs when a user mouses down on an item, but has not
14226 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
14227 * releases the mouse.
14229 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
14233 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
14234 var i
, len
, pressed
,
14237 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
14238 pressed
= this.items
[ i
] === item
;
14239 if ( this.items
[ i
].isPressed() !== pressed
) {
14240 this.items
[ i
].setPressed( pressed
);
14245 this.emit( 'press', item
);
14254 * Note that ‘choose’ should never be modified programmatically. A user can choose
14255 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
14256 * use the #selectItem method.
14258 * This method is identical to #selectItem, but may vary in subclasses that take additional action
14259 * when users choose an item with the keyboard or mouse.
14261 * @param {OO.ui.OptionWidget} item Item to choose
14265 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
14266 this.selectItem( item
);
14267 this.emit( 'choose', item
);
14273 * Get an option by its position relative to the specified item (or to the start of the option array,
14274 * if item is `null`). The direction in which to search through the option array is specified with a
14275 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
14276 * `null` if there are no options in the array.
14278 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
14279 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
14280 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
14282 OO
.ui
.SelectWidget
.prototype.getRelativeSelectableItem = function ( item
, direction
) {
14283 var currentIndex
, nextIndex
, i
,
14284 increase
= direction
> 0 ? 1 : -1,
14285 len
= this.items
.length
;
14287 if ( item
instanceof OO
.ui
.OptionWidget
) {
14288 currentIndex
= $.inArray( item
, this.items
);
14289 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
14291 // If no item is selected and moving forward, start at the beginning.
14292 // If moving backward, start at the end.
14293 nextIndex
= direction
> 0 ? 0 : len
- 1;
14296 for ( i
= 0; i
< len
; i
++ ) {
14297 item
= this.items
[ nextIndex
];
14298 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() ) {
14301 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
14307 * Get the next selectable item or `null` if there are no selectable items.
14308 * Disabled options and menu-section markers and breaks are not selectable.
14310 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
14312 OO
.ui
.SelectWidget
.prototype.getFirstSelectableItem = function () {
14315 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
14316 item
= this.items
[ i
];
14317 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() ) {
14326 * Add an array of options to the select. Optionally, an index number can be used to
14327 * specify an insertion point.
14329 * @param {OO.ui.OptionWidget[]} items Items to add
14330 * @param {number} [index] Index to insert items after
14334 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
14336 OO
.ui
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
14338 // Always provide an index, even if it was omitted
14339 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
14345 * Remove the specified array of options from the select. Options will be detached
14346 * from the DOM, not removed, so they can be reused later. To remove all options from
14347 * the select, you may wish to use the #clearItems method instead.
14349 * @param {OO.ui.OptionWidget[]} items Items to remove
14353 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
14356 // Deselect items being removed
14357 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
14359 if ( item
.isSelected() ) {
14360 this.selectItem( null );
14365 OO
.ui
.GroupWidget
.prototype.removeItems
.call( this, items
);
14367 this.emit( 'remove', items
);
14373 * Clear all options from the select. Options will be detached from the DOM, not removed,
14374 * so that they can be reused later. To remove a subset of options from the select, use
14375 * the #removeItems method.
14380 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
14381 var items
= this.items
.slice();
14384 OO
.ui
.GroupWidget
.prototype.clearItems
.call( this );
14387 this.selectItem( null );
14389 this.emit( 'remove', items
);
14395 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
14396 * button options and is used together with
14397 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
14398 * highlighting, choosing, and selecting mutually exclusive options. Please see
14399 * the [OOjs UI documentation on MediaWiki] [1] for more information.
14402 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
14403 * var option1 = new OO.ui.ButtonOptionWidget( {
14405 * label: 'Option 1',
14406 * title: 'Button option 1'
14409 * var option2 = new OO.ui.ButtonOptionWidget( {
14411 * label: 'Option 2',
14412 * title: 'Button option 2'
14415 * var option3 = new OO.ui.ButtonOptionWidget( {
14417 * label: 'Option 3',
14418 * title: 'Button option 3'
14421 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
14422 * items: [ option1, option2, option3 ]
14424 * $( 'body' ).append( buttonSelect.$element );
14426 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14429 * @extends OO.ui.SelectWidget
14430 * @mixins OO.ui.TabIndexedElement
14433 * @param {Object} [config] Configuration options
14435 OO
.ui
.ButtonSelectWidget
= function OoUiButtonSelectWidget( config
) {
14436 // Parent constructor
14437 OO
.ui
.ButtonSelectWidget
.super.call( this, config
);
14439 // Mixin constructors
14440 OO
.ui
.TabIndexedElement
.call( this, config
);
14443 this.$element
.on( {
14444 focus
: this.bindKeyDownListener
.bind( this ),
14445 blur
: this.unbindKeyDownListener
.bind( this )
14449 this.$element
.addClass( 'oo-ui-buttonSelectWidget' );
14454 OO
.inheritClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.SelectWidget
);
14455 OO
.mixinClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.TabIndexedElement
);
14458 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
14459 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
14460 * an interface for adding, removing and selecting options.
14461 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
14464 * // A RadioSelectWidget with RadioOptions.
14465 * var option1 = new OO.ui.RadioOptionWidget( {
14467 * label: 'Selected radio option'
14470 * var option2 = new OO.ui.RadioOptionWidget( {
14472 * label: 'Unselected radio option'
14475 * var radioSelect=new OO.ui.RadioSelectWidget( {
14476 * items: [ option1, option2 ]
14479 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
14480 * radioSelect.selectItem( option1 );
14482 * $( 'body' ).append( radioSelect.$element );
14484 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14488 * @extends OO.ui.SelectWidget
14489 * @mixins OO.ui.TabIndexedElement
14492 * @param {Object} [config] Configuration options
14494 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
14495 // Parent constructor
14496 OO
.ui
.RadioSelectWidget
.super.call( this, config
);
14498 // Mixin constructors
14499 OO
.ui
.TabIndexedElement
.call( this, config
);
14502 this.$element
.on( {
14503 focus
: this.bindKeyDownListener
.bind( this ),
14504 blur
: this.unbindKeyDownListener
.bind( this )
14508 this.$element
.addClass( 'oo-ui-radioSelectWidget' );
14513 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
14514 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.TabIndexedElement
);
14517 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
14518 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
14519 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxWidget ComboBoxWidget},
14520 * and {@link OO.ui.LookupElement LookupElement} for examples of widgets that contain menus.
14521 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
14522 * and customized to be opened, closed, and displayed as needed.
14524 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
14525 * mouse outside the menu.
14527 * Menus also have support for keyboard interaction:
14529 * - Enter/Return key: choose and select a menu option
14530 * - Up-arrow key: highlight the previous menu option
14531 * - Down-arrow key: highlight the next menu option
14532 * - Esc key: hide the menu
14534 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
14535 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14538 * @extends OO.ui.SelectWidget
14539 * @mixins OO.ui.ClippableElement
14542 * @param {Object} [config] Configuration options
14543 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
14544 * the text the user types. This config is used by {@link OO.ui.ComboBoxWidget ComboBoxWidget}
14545 * and {@link OO.ui.LookupElement LookupElement}
14546 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu’s active state. If the user clicks the mouse
14547 * anywhere on the page outside of this widget, the menu is hidden.
14548 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
14550 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
14551 // Configuration initialization
14552 config
= config
|| {};
14554 // Parent constructor
14555 OO
.ui
.MenuSelectWidget
.super.call( this, config
);
14557 // Mixin constructors
14558 OO
.ui
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
14561 this.newItems
= null;
14562 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
14563 this.$input
= config
.input
? config
.input
.$input
: null;
14564 this.$widget
= config
.widget
? config
.widget
.$element
: null;
14565 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
14569 .addClass( 'oo-ui-menuSelectWidget' )
14570 .attr( 'role', 'menu' );
14572 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
14573 // that reference properties not initialized at that time of parent class construction
14574 // TODO: Find a better way to handle post-constructor setup
14575 this.visible
= false;
14576 this.$element
.addClass( 'oo-ui-element-hidden' );
14581 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
14582 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.ClippableElement
);
14587 * Handles document mouse down events.
14590 * @param {jQuery.Event} e Key down event
14592 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
14594 !OO
.ui
.contains( this.$element
[ 0 ], e
.target
, true ) &&
14595 ( !this.$widget
|| !OO
.ui
.contains( this.$widget
[ 0 ], e
.target
, true ) )
14597 this.toggle( false );
14604 OO
.ui
.MenuSelectWidget
.prototype.onKeyDown = function ( e
) {
14605 var currentItem
= this.getHighlightedItem() || this.getSelectedItem();
14607 if ( !this.isDisabled() && this.isVisible() ) {
14608 switch ( e
.keyCode
) {
14609 case OO
.ui
.Keys
.LEFT
:
14610 case OO
.ui
.Keys
.RIGHT
:
14611 // Do nothing if a text field is associated, arrow keys will be handled natively
14612 if ( !this.$input
) {
14613 OO
.ui
.MenuSelectWidget
.super.prototype.onKeyDown
.call( this, e
);
14616 case OO
.ui
.Keys
.ESCAPE
:
14617 case OO
.ui
.Keys
.TAB
:
14618 if ( currentItem
) {
14619 currentItem
.setHighlighted( false );
14621 this.toggle( false );
14622 // Don't prevent tabbing away, prevent defocusing
14623 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
14624 e
.preventDefault();
14625 e
.stopPropagation();
14629 OO
.ui
.MenuSelectWidget
.super.prototype.onKeyDown
.call( this, e
);
14638 OO
.ui
.MenuSelectWidget
.prototype.bindKeyDownListener = function () {
14639 if ( this.$input
) {
14640 this.$input
.on( 'keydown', this.onKeyDownHandler
);
14642 OO
.ui
.MenuSelectWidget
.super.prototype.bindKeyDownListener
.call( this );
14649 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyDownListener = function () {
14650 if ( this.$input
) {
14651 this.$input
.off( 'keydown', this.onKeyDownHandler
);
14653 OO
.ui
.MenuSelectWidget
.super.prototype.unbindKeyDownListener
.call( this );
14660 * When a user chooses an item, the menu is closed.
14662 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
14663 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
14664 * @param {OO.ui.OptionWidget} item Item to choose
14667 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
14668 OO
.ui
.MenuSelectWidget
.super.prototype.chooseItem
.call( this, item
);
14669 this.toggle( false );
14676 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
14680 OO
.ui
.MenuSelectWidget
.super.prototype.addItems
.call( this, items
, index
);
14683 if ( !this.newItems
) {
14684 this.newItems
= [];
14687 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
14689 if ( this.isVisible() ) {
14690 // Defer fitting label until item has been attached
14693 this.newItems
.push( item
);
14697 // Reevaluate clipping
14706 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
14708 OO
.ui
.MenuSelectWidget
.super.prototype.removeItems
.call( this, items
);
14710 // Reevaluate clipping
14719 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
14721 OO
.ui
.MenuSelectWidget
.super.prototype.clearItems
.call( this );
14723 // Reevaluate clipping
14732 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
14733 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
14736 change
= visible
!== this.isVisible();
14739 OO
.ui
.MenuSelectWidget
.super.prototype.toggle
.call( this, visible
);
14743 this.bindKeyDownListener();
14745 if ( this.newItems
&& this.newItems
.length
) {
14746 for ( i
= 0, len
= this.newItems
.length
; i
< len
; i
++ ) {
14747 this.newItems
[ i
].fitLabel();
14749 this.newItems
= null;
14751 this.toggleClipping( true );
14754 if ( this.autoHide
) {
14755 this.getElementDocument().addEventListener(
14756 'mousedown', this.onDocumentMouseDownHandler
, true
14760 this.unbindKeyDownListener();
14761 this.getElementDocument().removeEventListener(
14762 'mousedown', this.onDocumentMouseDownHandler
, true
14764 this.toggleClipping( false );
14772 * TextInputMenuSelectWidget is a menu that is specially designed to be positioned beneath
14773 * a {@link OO.ui.TextInputWidget text input} field. The menu's position is automatically
14774 * calculated and maintained when the menu is toggled or the window is resized.
14775 * See OO.ui.ComboBoxWidget for an example of a widget that uses this class.
14778 * @extends OO.ui.MenuSelectWidget
14781 * @param {OO.ui.TextInputWidget} inputWidget Text input widget to provide menu for
14782 * @param {Object} [config] Configuration options
14783 * @cfg {jQuery} [$container=input.$element] Element to render menu under
14785 OO
.ui
.TextInputMenuSelectWidget
= function OoUiTextInputMenuSelectWidget( inputWidget
, config
) {
14786 // Allow passing positional parameters inside the config object
14787 if ( OO
.isPlainObject( inputWidget
) && config
=== undefined ) {
14788 config
= inputWidget
;
14789 inputWidget
= config
.inputWidget
;
14792 // Configuration initialization
14793 config
= config
|| {};
14795 // Parent constructor
14796 OO
.ui
.TextInputMenuSelectWidget
.super.call( this, config
);
14799 this.inputWidget
= inputWidget
;
14800 this.$container
= config
.$container
|| this.inputWidget
.$element
;
14801 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
14804 this.$element
.addClass( 'oo-ui-textInputMenuSelectWidget' );
14809 OO
.inheritClass( OO
.ui
.TextInputMenuSelectWidget
, OO
.ui
.MenuSelectWidget
);
14814 * Handle window resize event.
14817 * @param {jQuery.Event} e Window resize event
14819 OO
.ui
.TextInputMenuSelectWidget
.prototype.onWindowResize = function () {
14826 OO
.ui
.TextInputMenuSelectWidget
.prototype.toggle = function ( visible
) {
14827 visible
= visible
=== undefined ? !this.isVisible() : !!visible
;
14829 var change
= visible
!== this.isVisible();
14831 if ( change
&& visible
) {
14832 // Make sure the width is set before the parent method runs.
14833 // After this we have to call this.position(); again to actually
14834 // position ourselves correctly.
14839 OO
.ui
.TextInputMenuSelectWidget
.super.prototype.toggle
.call( this, visible
);
14842 if ( this.isVisible() ) {
14844 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler
);
14846 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler
);
14854 * Position the menu.
14859 OO
.ui
.TextInputMenuSelectWidget
.prototype.position = function () {
14860 var $container
= this.$container
,
14861 pos
= OO
.ui
.Element
.static.getRelativePosition( $container
, this.$element
.offsetParent() );
14863 // Position under input
14864 pos
.top
+= $container
.height();
14865 this.$element
.css( pos
);
14868 this.setIdealSize( $container
.width() );
14869 // We updated the position, so re-evaluate the clipping state
14876 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
14877 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
14879 * ####Currently, this class is only used by {@link OO.ui.BookletLayout BookletLayouts}.####
14882 * @extends OO.ui.SelectWidget
14883 * @mixins OO.ui.TabIndexedElement
14886 * @param {Object} [config] Configuration options
14888 OO
.ui
.OutlineSelectWidget
= function OoUiOutlineSelectWidget( config
) {
14889 // Parent constructor
14890 OO
.ui
.OutlineSelectWidget
.super.call( this, config
);
14892 // Mixin constructors
14893 OO
.ui
.TabIndexedElement
.call( this, config
);
14896 this.$element
.on( {
14897 focus
: this.bindKeyDownListener
.bind( this ),
14898 blur
: this.unbindKeyDownListener
.bind( this )
14902 this.$element
.addClass( 'oo-ui-outlineSelectWidget' );
14907 OO
.inheritClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.SelectWidget
);
14908 OO
.mixinClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.TabIndexedElement
);
14911 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
14912 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
14913 * visually by a slider in the leftmost position.
14916 * // Toggle switches in the 'off' and 'on' position.
14917 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
14918 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
14922 * // Create a FieldsetLayout to layout and label switches
14923 * var fieldset = new OO.ui.FieldsetLayout( {
14924 * label: 'Toggle switches'
14926 * fieldset.addItems( [
14927 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
14928 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
14930 * $( 'body' ).append( fieldset.$element );
14933 * @extends OO.ui.Widget
14934 * @mixins OO.ui.ToggleWidget
14935 * @mixins OO.ui.TabIndexedElement
14938 * @param {Object} [config] Configuration options
14939 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
14940 * By default, the toggle switch is in the 'off' position.
14942 OO
.ui
.ToggleSwitchWidget
= function OoUiToggleSwitchWidget( config
) {
14943 // Parent constructor
14944 OO
.ui
.ToggleSwitchWidget
.super.call( this, config
);
14946 // Mixin constructors
14947 OO
.ui
.ToggleWidget
.call( this, config
);
14948 OO
.ui
.TabIndexedElement
.call( this, config
);
14951 this.dragging
= false;
14952 this.dragStart
= null;
14953 this.sliding
= false;
14954 this.$glow
= $( '<span>' );
14955 this.$grip
= $( '<span>' );
14958 this.$element
.on( {
14959 click
: this.onClick
.bind( this ),
14960 keypress
: this.onKeyPress
.bind( this )
14964 this.$glow
.addClass( 'oo-ui-toggleSwitchWidget-glow' );
14965 this.$grip
.addClass( 'oo-ui-toggleSwitchWidget-grip' );
14967 .addClass( 'oo-ui-toggleSwitchWidget' )
14968 .attr( 'role', 'checkbox' )
14969 .append( this.$glow
, this.$grip
);
14974 OO
.inheritClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.Widget
);
14975 OO
.mixinClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.ToggleWidget
);
14976 OO
.mixinClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.TabIndexedElement
);
14981 * Handle mouse click events.
14984 * @param {jQuery.Event} e Mouse click event
14986 OO
.ui
.ToggleSwitchWidget
.prototype.onClick = function ( e
) {
14987 if ( !this.isDisabled() && e
.which
=== 1 ) {
14988 this.setValue( !this.value
);
14994 * Handle key press events.
14997 * @param {jQuery.Event} e Key press event
14999 OO
.ui
.ToggleSwitchWidget
.prototype.onKeyPress = function ( e
) {
15000 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
15001 this.setValue( !this.value
);