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-03-19T23:18:59Z
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 * Container for elements.
1581 * @extends OO.ui.Element
1582 * @mixins OO.EventEmitter
1585 * @param {Object} [config] Configuration options
1587 OO
.ui
.Layout
= function OoUiLayout( config
) {
1588 // Configuration initialization
1589 config
= config
|| {};
1591 // Parent constructor
1592 OO
.ui
.Layout
.super.call( this, config
);
1594 // Mixin constructors
1595 OO
.EventEmitter
.call( this );
1598 this.$element
.addClass( 'oo-ui-layout' );
1603 OO
.inheritClass( OO
.ui
.Layout
, OO
.ui
.Element
);
1604 OO
.mixinClass( OO
.ui
.Layout
, OO
.EventEmitter
);
1607 * Widgets are compositions of one or more OOjs UI elements that users can both view
1608 * and interact with. All widgets can be configured and modified via a standard API,
1609 * and their state can change dynamically according to a model.
1613 * @extends OO.ui.Element
1614 * @mixins OO.EventEmitter
1617 * @param {Object} [config] Configuration options
1618 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1619 * appearance reflects this state.
1621 OO
.ui
.Widget
= function OoUiWidget( config
) {
1622 // Initialize config
1623 config
= $.extend( { disabled
: false }, config
);
1625 // Parent constructor
1626 OO
.ui
.Widget
.super.call( this, config
);
1628 // Mixin constructors
1629 OO
.EventEmitter
.call( this );
1632 this.disabled
= null;
1633 this.wasDisabled
= null;
1636 this.$element
.addClass( 'oo-ui-widget' );
1637 this.setDisabled( !!config
.disabled
);
1642 OO
.inheritClass( OO
.ui
.Widget
, OO
.ui
.Element
);
1643 OO
.mixinClass( OO
.ui
.Widget
, OO
.EventEmitter
);
1650 * A 'disable' event is emitted when a widget is disabled.
1652 * @param {boolean} disabled Widget is disabled
1658 * A 'toggle' event is emitted when the visibility of the widget changes.
1660 * @param {boolean} visible Widget is visible
1666 * Check if the widget is disabled.
1668 * @return {boolean} Widget is disabled
1670 OO
.ui
.Widget
.prototype.isDisabled = function () {
1671 return this.disabled
;
1675 * Set the 'disabled' state of the widget.
1677 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1679 * @param {boolean} disabled Disable widget
1682 OO
.ui
.Widget
.prototype.setDisabled = function ( disabled
) {
1685 this.disabled
= !!disabled
;
1686 isDisabled
= this.isDisabled();
1687 if ( isDisabled
!== this.wasDisabled
) {
1688 this.$element
.toggleClass( 'oo-ui-widget-disabled', isDisabled
);
1689 this.$element
.toggleClass( 'oo-ui-widget-enabled', !isDisabled
);
1690 this.$element
.attr( 'aria-disabled', isDisabled
.toString() );
1691 this.emit( 'disable', isDisabled
);
1692 this.updateThemeClasses();
1694 this.wasDisabled
= isDisabled
;
1700 * Update the disabled state, in case of changes in parent widget.
1704 OO
.ui
.Widget
.prototype.updateDisabled = function () {
1705 this.setDisabled( this.disabled
);
1710 * A window is a container for elements that are in a child frame. They are used with
1711 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
1712 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
1713 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
1714 * the window manager will choose a sensible fallback.
1716 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
1717 * different processes are executed:
1719 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
1720 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
1723 * - {@link #getSetupProcess} method is called and its result executed
1724 * - {@link #getReadyProcess} method is called and its result executed
1726 * **opened**: The window is now open
1728 * **closing**: The closing stage begins when the window manager's
1729 * {@link OO.ui.WindowManager#closeWindow closeWindow}
1730 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
1732 * - {@link #getHoldProcess} method is called and its result executed
1733 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
1735 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
1736 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
1737 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
1738 * processing can complete. Always assume window processes are executed asynchronously.
1740 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
1742 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
1746 * @extends OO.ui.Element
1747 * @mixins OO.EventEmitter
1750 * @param {Object} [config] Configuration options
1751 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
1752 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
1754 OO
.ui
.Window
= function OoUiWindow( config
) {
1755 // Configuration initialization
1756 config
= config
|| {};
1758 // Parent constructor
1759 OO
.ui
.Window
.super.call( this, config
);
1761 // Mixin constructors
1762 OO
.EventEmitter
.call( this );
1765 this.manager
= null;
1766 this.size
= config
.size
|| this.constructor.static.size
;
1767 this.$frame
= $( '<div>' );
1768 this.$overlay
= $( '<div>' );
1769 this.$content
= $( '<div>' );
1772 this.$overlay
.addClass( 'oo-ui-window-overlay' );
1774 .addClass( 'oo-ui-window-content' )
1775 .attr( 'tabIndex', 0 );
1777 .addClass( 'oo-ui-window-frame' )
1778 .append( this.$content
);
1781 .addClass( 'oo-ui-window' )
1782 .append( this.$frame
, this.$overlay
);
1784 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
1785 // that reference properties not initialized at that time of parent class construction
1786 // TODO: Find a better way to handle post-constructor setup
1787 this.visible
= false;
1788 this.$element
.addClass( 'oo-ui-element-hidden' );
1793 OO
.inheritClass( OO
.ui
.Window
, OO
.ui
.Element
);
1794 OO
.mixinClass( OO
.ui
.Window
, OO
.EventEmitter
);
1796 /* Static Properties */
1799 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
1801 * The static size is used if no #size is configured during construction.
1805 * @property {string}
1807 OO
.ui
.Window
.static.size
= 'medium';
1812 * Handle mouse down events.
1815 * @param {jQuery.Event} e Mouse down event
1817 OO
.ui
.Window
.prototype.onMouseDown = function ( e
) {
1818 // Prevent clicking on the click-block from stealing focus
1819 if ( e
.target
=== this.$element
[ 0 ] ) {
1825 * Check if the window has been initialized.
1827 * Initialization occurs when a window is added to a manager.
1829 * @return {boolean} Window has been initialized
1831 OO
.ui
.Window
.prototype.isInitialized = function () {
1832 return !!this.manager
;
1836 * Check if the window is visible.
1838 * @return {boolean} Window is visible
1840 OO
.ui
.Window
.prototype.isVisible = function () {
1841 return this.visible
;
1845 * Check if the window is opening.
1847 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
1850 * @return {boolean} Window is opening
1852 OO
.ui
.Window
.prototype.isOpening = function () {
1853 return this.manager
.isOpening( this );
1857 * Check if the window is closing.
1859 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
1861 * @return {boolean} Window is closing
1863 OO
.ui
.Window
.prototype.isClosing = function () {
1864 return this.manager
.isClosing( this );
1868 * Check if the window is opened.
1870 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
1872 * @return {boolean} Window is opened
1874 OO
.ui
.Window
.prototype.isOpened = function () {
1875 return this.manager
.isOpened( this );
1879 * Get the window manager.
1881 * All windows must be attached to a window manager, which is used to open
1882 * and close the window and control its presentation.
1884 * @return {OO.ui.WindowManager} Manager of window
1886 OO
.ui
.Window
.prototype.getManager = function () {
1887 return this.manager
;
1891 * Get the symbolic name of the window size (e.g., `small` or `medium`).
1893 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
1895 OO
.ui
.Window
.prototype.getSize = function () {
1900 * Disable transitions on window's frame for the duration of the callback function, then enable them
1904 * @param {Function} callback Function to call while transitions are disabled
1906 OO
.ui
.Window
.prototype.withoutSizeTransitions = function ( callback
) {
1907 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
1908 // Disable transitions first, otherwise we'll get values from when the window was animating.
1910 styleObj
= this.$frame
[ 0 ].style
;
1911 oldTransition
= styleObj
.transition
|| styleObj
.OTransition
|| styleObj
.MsTransition
||
1912 styleObj
.MozTransition
|| styleObj
.WebkitTransition
;
1913 styleObj
.transition
= styleObj
.OTransition
= styleObj
.MsTransition
=
1914 styleObj
.MozTransition
= styleObj
.WebkitTransition
= 'none';
1916 // Force reflow to make sure the style changes done inside callback really are not transitioned
1917 this.$frame
.height();
1918 styleObj
.transition
= styleObj
.OTransition
= styleObj
.MsTransition
=
1919 styleObj
.MozTransition
= styleObj
.WebkitTransition
= oldTransition
;
1923 * Get the height of the full window contents (i.e., the window head, body and foot together).
1925 * What consistitutes the head, body, and foot varies depending on the window type.
1926 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
1927 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
1928 * and special actions in the head, and dialog content in the body.
1930 * To get just the height of the dialog body, use the #getBodyHeight method.
1932 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
1934 OO
.ui
.Window
.prototype.getContentHeight = function () {
1937 bodyStyleObj
= this.$body
[ 0 ].style
,
1938 frameStyleObj
= this.$frame
[ 0 ].style
;
1940 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
1941 // Disable transitions first, otherwise we'll get values from when the window was animating.
1942 this.withoutSizeTransitions( function () {
1943 var oldHeight
= frameStyleObj
.height
,
1944 oldPosition
= bodyStyleObj
.position
;
1945 frameStyleObj
.height
= '1px';
1946 // Force body to resize to new width
1947 bodyStyleObj
.position
= 'relative';
1948 bodyHeight
= win
.getBodyHeight();
1949 frameStyleObj
.height
= oldHeight
;
1950 bodyStyleObj
.position
= oldPosition
;
1954 // Add buffer for border
1955 ( this.$frame
.outerHeight() - this.$frame
.innerHeight() ) +
1956 // Use combined heights of children
1957 ( this.$head
.outerHeight( true ) + bodyHeight
+ this.$foot
.outerHeight( true ) )
1962 * Get the height of the window body.
1964 * To get the height of the full window contents (the window body, head, and foot together),
1965 * use #getContentHeight.
1967 * When this function is called, the window will temporarily have been resized
1968 * to height=1px, so .scrollHeight measurements can be taken accurately.
1970 * @return {number} Height of the window body in pixels
1972 OO
.ui
.Window
.prototype.getBodyHeight = function () {
1973 return this.$body
[ 0 ].scrollHeight
;
1977 * Get the directionality of the frame (right-to-left or left-to-right).
1979 * @return {string} Directionality: `'ltr'` or `'rtl'`
1981 OO
.ui
.Window
.prototype.getDir = function () {
1986 * Get the 'setup' process.
1988 * The setup process is used to set up a window for use in a particular context,
1989 * based on the `data` argument. This method is called during the opening phase of the window’s
1992 * Override this method to add additional steps to the ‘setup’ process the parent method provides
1993 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
1996 * To add window content that persists between openings, you may wish to use the #initialize method
2000 * @param {Object} [data] Window opening data
2001 * @return {OO.ui.Process} Setup process
2003 OO
.ui
.Window
.prototype.getSetupProcess = function () {
2004 return new OO
.ui
.Process();
2008 * Get the ‘ready’ process.
2010 * The ready process is used to ready a window for use in a particular
2011 * context, based on the `data` argument. This method is called during the opening phase of
2012 * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
2014 * Override this method to add additional steps to the ‘ready’ process the parent method
2015 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
2016 * methods of OO.ui.Process.
2019 * @param {Object} [data] Window opening data
2020 * @return {OO.ui.Process} Ready process
2022 OO
.ui
.Window
.prototype.getReadyProcess = function () {
2023 return new OO
.ui
.Process();
2027 * Get the 'hold' process.
2029 * The hold proccess is used to keep a window from being used in a particular context,
2030 * based on the `data` argument. This method is called during the closing phase of the window’s
2033 * Override this method to add additional steps to the 'hold' process the parent method provides
2034 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2038 * @param {Object} [data] Window closing data
2039 * @return {OO.ui.Process} Hold process
2041 OO
.ui
.Window
.prototype.getHoldProcess = function () {
2042 return new OO
.ui
.Process();
2046 * Get the ‘teardown’ process.
2048 * The teardown process is used to teardown a window after use. During teardown,
2049 * user interactions within the window are conveyed and the window is closed, based on the `data`
2050 * argument. This method is called during the closing phase of the window’s lifecycle.
2052 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
2053 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2057 * @param {Object} [data] Window closing data
2058 * @return {OO.ui.Process} Teardown process
2060 OO
.ui
.Window
.prototype.getTeardownProcess = function () {
2061 return new OO
.ui
.Process();
2065 * Set the window manager.
2067 * This will cause the window to initialize. Calling it more than once will cause an error.
2069 * @param {OO.ui.WindowManager} manager Manager for this window
2070 * @throws {Error} An error is thrown if the method is called more than once
2073 OO
.ui
.Window
.prototype.setManager = function ( manager
) {
2074 if ( this.manager
) {
2075 throw new Error( 'Cannot set window manager, window already has a manager' );
2078 this.manager
= manager
;
2085 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2087 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2091 OO
.ui
.Window
.prototype.setSize = function ( size
) {
2098 * Update the window size.
2100 * @throws {Error} An error is thrown if the window is not attached to a window manager
2103 OO
.ui
.Window
.prototype.updateSize = function () {
2104 if ( !this.manager
) {
2105 throw new Error( 'Cannot update window size, must be attached to a manager' );
2108 this.manager
.updateWindowSize( this );
2114 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2115 * when the window is opening. In general, setDimensions should not be called directly.
2117 * To set the size of the window, use the #setSize method.
2119 * @param {Object} dim CSS dimension properties
2120 * @param {string|number} [dim.width] Width
2121 * @param {string|number} [dim.minWidth] Minimum width
2122 * @param {string|number} [dim.maxWidth] Maximum width
2123 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2124 * @param {string|number} [dim.minWidth] Minimum height
2125 * @param {string|number} [dim.maxWidth] Maximum height
2128 OO
.ui
.Window
.prototype.setDimensions = function ( dim
) {
2131 styleObj
= this.$frame
[ 0 ].style
;
2133 // Calculate the height we need to set using the correct width
2134 if ( dim
.height
=== undefined ) {
2135 this.withoutSizeTransitions( function () {
2136 var oldWidth
= styleObj
.width
;
2137 win
.$frame
.css( 'width', dim
.width
|| '' );
2138 height
= win
.getContentHeight();
2139 styleObj
.width
= oldWidth
;
2142 height
= dim
.height
;
2146 width
: dim
.width
|| '',
2147 minWidth
: dim
.minWidth
|| '',
2148 maxWidth
: dim
.maxWidth
|| '',
2149 height
: height
|| '',
2150 minHeight
: dim
.minHeight
|| '',
2151 maxHeight
: dim
.maxHeight
|| ''
2158 * Initialize window contents.
2160 * Before the window is opened for the first time, #initialize is called so that content that
2161 * persists between openings can be added to the window.
2163 * To set up a window with new content each time the window opens, use #getSetupProcess.
2165 * @throws {Error} An error is thrown if the window is not attached to a window manager
2168 OO
.ui
.Window
.prototype.initialize = function () {
2169 if ( !this.manager
) {
2170 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2174 this.$head
= $( '<div>' );
2175 this.$body
= $( '<div>' );
2176 this.$foot
= $( '<div>' );
2177 this.dir
= OO
.ui
.Element
.static.getDir( this.$content
) || 'ltr';
2178 this.$document
= $( this.getElementDocument() );
2181 this.$element
.on( 'mousedown', this.onMouseDown
.bind( this ) );
2184 this.$head
.addClass( 'oo-ui-window-head' );
2185 this.$body
.addClass( 'oo-ui-window-body' );
2186 this.$foot
.addClass( 'oo-ui-window-foot' );
2187 this.$content
.append( this.$head
, this.$body
, this.$foot
);
2195 * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
2196 * method, which returns a promise resolved when the window is done opening.
2198 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2200 * @param {Object} [data] Window opening data
2201 * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
2202 * if the window fails to open. When the promise is resolved successfully, the first argument of the
2203 * value is a new promise, which is resolved when the window begins closing.
2204 * @throws {Error} An error is thrown if the window is not attached to a window manager
2206 OO
.ui
.Window
.prototype.open = function ( data
) {
2207 if ( !this.manager
) {
2208 throw new Error( 'Cannot open window, must be attached to a manager' );
2211 return this.manager
.openWindow( this, data
);
2217 * This method is a wrapper around a call to the window
2218 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
2219 * which returns a closing promise resolved when the window is done closing.
2221 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2222 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2223 * the window closes.
2225 * @param {Object} [data] Window closing data
2226 * @return {jQuery.Promise} Promise resolved when window is closed
2227 * @throws {Error} An error is thrown if the window is not attached to a window manager
2229 OO
.ui
.Window
.prototype.close = function ( data
) {
2230 if ( !this.manager
) {
2231 throw new Error( 'Cannot close window, must be attached to a manager' );
2234 return this.manager
.closeWindow( this, data
);
2240 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2243 * @param {Object} [data] Window opening data
2244 * @return {jQuery.Promise} Promise resolved when window is setup
2246 OO
.ui
.Window
.prototype.setup = function ( data
) {
2248 deferred
= $.Deferred();
2250 this.toggle( true );
2252 this.getSetupProcess( data
).execute().done( function () {
2253 // Force redraw by asking the browser to measure the elements' widths
2254 win
.$element
.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2255 win
.$content
.addClass( 'oo-ui-window-content-setup' ).width();
2259 return deferred
.promise();
2265 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2268 * @param {Object} [data] Window opening data
2269 * @return {jQuery.Promise} Promise resolved when window is ready
2271 OO
.ui
.Window
.prototype.ready = function ( data
) {
2273 deferred
= $.Deferred();
2275 this.$content
.focus();
2276 this.getReadyProcess( data
).execute().done( function () {
2277 // Force redraw by asking the browser to measure the elements' widths
2278 win
.$element
.addClass( 'oo-ui-window-ready' ).width();
2279 win
.$content
.addClass( 'oo-ui-window-content-ready' ).width();
2283 return deferred
.promise();
2289 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2292 * @param {Object} [data] Window closing data
2293 * @return {jQuery.Promise} Promise resolved when window is held
2295 OO
.ui
.Window
.prototype.hold = function ( data
) {
2297 deferred
= $.Deferred();
2299 this.getHoldProcess( data
).execute().done( function () {
2300 // Get the focused element within the window's content
2301 var $focus
= win
.$content
.find( OO
.ui
.Element
.static.getDocument( win
.$content
).activeElement
);
2303 // Blur the focused element
2304 if ( $focus
.length
) {
2308 // Force redraw by asking the browser to measure the elements' widths
2309 win
.$element
.removeClass( 'oo-ui-window-ready' ).width();
2310 win
.$content
.removeClass( 'oo-ui-window-content-ready' ).width();
2314 return deferred
.promise();
2320 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2323 * @param {Object} [data] Window closing data
2324 * @return {jQuery.Promise} Promise resolved when window is torn down
2326 OO
.ui
.Window
.prototype.teardown = function ( data
) {
2329 return this.getTeardownProcess( data
).execute()
2330 .done( function () {
2331 // Force redraw by asking the browser to measure the elements' widths
2332 win
.$element
.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2333 win
.$content
.removeClass( 'oo-ui-window-content-setup' ).width();
2334 win
.toggle( false );
2339 * The Dialog class serves as the base class for the other types of dialogs.
2340 * Unless extended to include controls, the rendered dialog box is a simple window
2341 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2342 * which opens, closes, and controls the presentation of the window. See the
2343 * [OOjs UI documentation on MediaWiki] [1] for more information.
2346 * // A simple dialog window.
2347 * function MyDialog( config ) {
2348 * MyDialog.super.call( this, config );
2350 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2351 * MyDialog.prototype.initialize = function () {
2352 * MyDialog.super.prototype.initialize.call( this );
2353 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2354 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2355 * this.$body.append( this.content.$element );
2357 * MyDialog.prototype.getBodyHeight = function () {
2358 * return this.content.$element.outerHeight( true );
2360 * var myDialog = new MyDialog( {
2363 * // Create and append a window manager, which opens and closes the window.
2364 * var windowManager = new OO.ui.WindowManager();
2365 * $( 'body' ).append( windowManager.$element );
2366 * windowManager.addWindows( [ myDialog ] );
2367 * // Open the window!
2368 * windowManager.openWindow( myDialog );
2370 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2374 * @extends OO.ui.Window
2375 * @mixins OO.ui.PendingElement
2378 * @param {Object} [config] Configuration options
2380 OO
.ui
.Dialog
= function OoUiDialog( config
) {
2381 // Parent constructor
2382 OO
.ui
.Dialog
.super.call( this, config
);
2384 // Mixin constructors
2385 OO
.ui
.PendingElement
.call( this );
2388 this.actions
= new OO
.ui
.ActionSet();
2389 this.attachedActions
= [];
2390 this.currentAction
= null;
2391 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
2394 this.actions
.connect( this, {
2395 click
: 'onActionClick',
2396 resize
: 'onActionResize',
2397 change
: 'onActionsChange'
2402 .addClass( 'oo-ui-dialog' )
2403 .attr( 'role', 'dialog' );
2408 OO
.inheritClass( OO
.ui
.Dialog
, OO
.ui
.Window
);
2409 OO
.mixinClass( OO
.ui
.Dialog
, OO
.ui
.PendingElement
);
2411 /* Static Properties */
2414 * Symbolic name of dialog.
2416 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2417 * Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
2419 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2424 * @property {string}
2426 OO
.ui
.Dialog
.static.name
= '';
2431 * The title can be specified as a plaintext string, a {@link OO.ui.LabelElement Label} node, or a function
2432 * that will produce a Label node or string. The title can also be specified with data passed to the
2433 * constructor (see #getSetupProcess). In this case, the static value will be overriden.
2438 * @property {jQuery|string|Function}
2440 OO
.ui
.Dialog
.static.title
= '';
2443 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2445 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2446 * value will be overriden.
2448 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
2452 * @property {Object[]}
2454 OO
.ui
.Dialog
.static.actions
= [];
2457 * Close the dialog when the 'Esc' key is pressed.
2462 * @property {boolean}
2464 OO
.ui
.Dialog
.static.escapable
= true;
2469 * Handle frame document key down events.
2472 * @param {jQuery.Event} e Key down event
2474 OO
.ui
.Dialog
.prototype.onDocumentKeyDown = function ( e
) {
2475 if ( e
.which
=== OO
.ui
.Keys
.ESCAPE
) {
2478 e
.stopPropagation();
2483 * Handle action resized events.
2486 * @param {OO.ui.ActionWidget} action Action that was resized
2488 OO
.ui
.Dialog
.prototype.onActionResize = function () {
2489 // Override in subclass
2493 * Handle action click events.
2496 * @param {OO.ui.ActionWidget} action Action that was clicked
2498 OO
.ui
.Dialog
.prototype.onActionClick = function ( action
) {
2499 if ( !this.isPending() ) {
2500 this.executeAction( action
.getAction() );
2505 * Handle actions change event.
2509 OO
.ui
.Dialog
.prototype.onActionsChange = function () {
2510 this.detachActions();
2511 if ( !this.isClosing() ) {
2512 this.attachActions();
2517 * Get the set of actions used by the dialog.
2519 * @return {OO.ui.ActionSet}
2521 OO
.ui
.Dialog
.prototype.getActions = function () {
2522 return this.actions
;
2526 * Get a process for taking action.
2528 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
2529 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
2530 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
2533 * @param {string} [action] Symbolic name of action
2534 * @return {OO.ui.Process} Action process
2536 OO
.ui
.Dialog
.prototype.getActionProcess = function ( action
) {
2537 return new OO
.ui
.Process()
2538 .next( function () {
2540 // An empty action always closes the dialog without data, which should always be
2541 // safe and make no changes
2550 * @param {Object} [data] Dialog opening data
2551 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
2552 * the {@link #static-title static title}
2553 * @param {Object[]} [data.actions] List of configuration options for each
2554 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
2556 OO
.ui
.Dialog
.prototype.getSetupProcess = function ( data
) {
2560 return OO
.ui
.Dialog
.super.prototype.getSetupProcess
.call( this, data
)
2561 .next( function () {
2562 var config
= this.constructor.static,
2563 actions
= data
.actions
!== undefined ? data
.actions
: config
.actions
;
2565 this.title
.setLabel(
2566 data
.title
!== undefined ? data
.title
: this.constructor.static.title
2568 this.actions
.add( this.getActionWidgets( actions
) );
2570 if ( this.constructor.static.escapable
) {
2571 this.$document
.on( 'keydown', this.onDocumentKeyDownHandler
);
2579 OO
.ui
.Dialog
.prototype.getTeardownProcess = function ( data
) {
2581 return OO
.ui
.Dialog
.super.prototype.getTeardownProcess
.call( this, data
)
2582 .first( function () {
2583 if ( this.constructor.static.escapable
) {
2584 this.$document
.off( 'keydown', this.onDocumentKeyDownHandler
);
2587 this.actions
.clear();
2588 this.currentAction
= null;
2595 OO
.ui
.Dialog
.prototype.initialize = function () {
2597 OO
.ui
.Dialog
.super.prototype.initialize
.call( this );
2600 this.title
= new OO
.ui
.LabelWidget();
2603 this.$content
.addClass( 'oo-ui-dialog-content' );
2604 this.setPendingElement( this.$head
);
2608 * Get action widgets from a list of configs
2610 * @param {Object[]} actions Action widget configs
2611 * @return {OO.ui.ActionWidget[]} Action widgets
2613 OO
.ui
.Dialog
.prototype.getActionWidgets = function ( actions
) {
2614 var i
, len
, widgets
= [];
2615 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
2617 new OO
.ui
.ActionWidget( actions
[ i
] )
2624 * Attach action actions.
2628 OO
.ui
.Dialog
.prototype.attachActions = function () {
2629 // Remember the list of potentially attached actions
2630 this.attachedActions
= this.actions
.get();
2634 * Detach action actions.
2639 OO
.ui
.Dialog
.prototype.detachActions = function () {
2642 // Detach all actions that may have been previously attached
2643 for ( i
= 0, len
= this.attachedActions
.length
; i
< len
; i
++ ) {
2644 this.attachedActions
[ i
].$element
.detach();
2646 this.attachedActions
= [];
2650 * Execute an action.
2652 * @param {string} action Symbolic name of action to execute
2653 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
2655 OO
.ui
.Dialog
.prototype.executeAction = function ( action
) {
2657 this.currentAction
= action
;
2658 return this.getActionProcess( action
).execute()
2659 .always( this.popPending
.bind( this ) );
2663 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
2664 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
2665 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
2666 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
2667 * pertinent data and reused.
2669 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
2670 * `opened`, and `closing`, which represent the primary stages of the cycle:
2672 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
2673 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
2675 * - an `opening` event is emitted with an `opening` promise
2676 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
2677 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
2678 * window and its result executed
2679 * - a `setup` progress notification is emitted from the `opening` promise
2680 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
2681 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
2682 * window and its result executed
2683 * - a `ready` progress notification is emitted from the `opening` promise
2684 * - the `opening` promise is resolved with an `opened` promise
2686 * **Opened**: the window is now open.
2688 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
2689 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
2690 * to close the window.
2692 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
2693 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
2694 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
2695 * window and its result executed
2696 * - a `hold` progress notification is emitted from the `closing` promise
2697 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
2698 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
2699 * window and its result executed
2700 * - a `teardown` progress notification is emitted from the `closing` promise
2701 * - the `closing` promise is resolved. The window is now closed
2703 * See the [OOjs UI documentation on MediaWiki][1] for more information.
2705 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2708 * @extends OO.ui.Element
2709 * @mixins OO.EventEmitter
2712 * @param {Object} [config] Configuration options
2713 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
2714 * Note that window classes that are instantiated with a factory must have
2715 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
2716 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
2718 OO
.ui
.WindowManager
= function OoUiWindowManager( config
) {
2719 // Configuration initialization
2720 config
= config
|| {};
2722 // Parent constructor
2723 OO
.ui
.WindowManager
.super.call( this, config
);
2725 // Mixin constructors
2726 OO
.EventEmitter
.call( this );
2729 this.factory
= config
.factory
;
2730 this.modal
= config
.modal
=== undefined || !!config
.modal
;
2732 this.opening
= null;
2734 this.closing
= null;
2735 this.preparingToOpen
= null;
2736 this.preparingToClose
= null;
2737 this.currentWindow
= null;
2738 this.globalEvents
= false;
2739 this.$ariaHidden
= null;
2740 this.onWindowResizeTimeout
= null;
2741 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
2742 this.afterWindowResizeHandler
= this.afterWindowResize
.bind( this );
2746 .addClass( 'oo-ui-windowManager' )
2747 .toggleClass( 'oo-ui-windowManager-modal', this.modal
);
2752 OO
.inheritClass( OO
.ui
.WindowManager
, OO
.ui
.Element
);
2753 OO
.mixinClass( OO
.ui
.WindowManager
, OO
.EventEmitter
);
2758 * An 'opening' event is emitted when the window begins to be opened.
2761 * @param {OO.ui.Window} win Window that's being opened
2762 * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
2763 * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
2764 * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
2765 * @param {Object} data Window opening data
2769 * A 'closing' event is emitted when the window begins to be closed.
2772 * @param {OO.ui.Window} win Window that's being closed
2773 * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
2774 * is closed successfully. The promise emits `hold` and `teardown` notifications when those
2775 * processes are complete. When the `closing` promise is resolved, the first argument of its value
2776 * is the closing data.
2777 * @param {Object} data Window closing data
2781 * A 'resize' event is emitted when a window is resized.
2784 * @param {OO.ui.Window} win Window that was resized
2787 /* Static Properties */
2790 * Map of the symbolic name of each window size and its CSS properties.
2794 * @property {Object}
2796 OO
.ui
.WindowManager
.static.sizes
= {
2810 // These can be non-numeric because they are never used in calculations
2817 * Symbolic name of the default window size.
2819 * The default size is used if the window's requested size is not recognized.
2823 * @property {string}
2825 OO
.ui
.WindowManager
.static.defaultSize
= 'medium';
2830 * Handle window resize events.
2833 * @param {jQuery.Event} e Window resize event
2835 OO
.ui
.WindowManager
.prototype.onWindowResize = function () {
2836 clearTimeout( this.onWindowResizeTimeout
);
2837 this.onWindowResizeTimeout
= setTimeout( this.afterWindowResizeHandler
, 200 );
2841 * Handle window resize events.
2844 * @param {jQuery.Event} e Window resize event
2846 OO
.ui
.WindowManager
.prototype.afterWindowResize = function () {
2847 if ( this.currentWindow
) {
2848 this.updateWindowSize( this.currentWindow
);
2853 * Check if window is opening.
2855 * @return {boolean} Window is opening
2857 OO
.ui
.WindowManager
.prototype.isOpening = function ( win
) {
2858 return win
=== this.currentWindow
&& !!this.opening
&& this.opening
.state() === 'pending';
2862 * Check if window is closing.
2864 * @return {boolean} Window is closing
2866 OO
.ui
.WindowManager
.prototype.isClosing = function ( win
) {
2867 return win
=== this.currentWindow
&& !!this.closing
&& this.closing
.state() === 'pending';
2871 * Check if window is opened.
2873 * @return {boolean} Window is opened
2875 OO
.ui
.WindowManager
.prototype.isOpened = function ( win
) {
2876 return win
=== this.currentWindow
&& !!this.opened
&& this.opened
.state() === 'pending';
2880 * Check if a window is being managed.
2882 * @param {OO.ui.Window} win Window to check
2883 * @return {boolean} Window is being managed
2885 OO
.ui
.WindowManager
.prototype.hasWindow = function ( win
) {
2888 for ( name
in this.windows
) {
2889 if ( this.windows
[ name
] === win
) {
2898 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
2900 * @param {OO.ui.Window} win Window being opened
2901 * @param {Object} [data] Window opening data
2902 * @return {number} Milliseconds to wait
2904 OO
.ui
.WindowManager
.prototype.getSetupDelay = function () {
2909 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
2911 * @param {OO.ui.Window} win Window being opened
2912 * @param {Object} [data] Window opening data
2913 * @return {number} Milliseconds to wait
2915 OO
.ui
.WindowManager
.prototype.getReadyDelay = function () {
2920 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
2922 * @param {OO.ui.Window} win Window being closed
2923 * @param {Object} [data] Window closing data
2924 * @return {number} Milliseconds to wait
2926 OO
.ui
.WindowManager
.prototype.getHoldDelay = function () {
2931 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
2932 * executing the ‘teardown’ process.
2934 * @param {OO.ui.Window} win Window being closed
2935 * @param {Object} [data] Window closing data
2936 * @return {number} Milliseconds to wait
2938 OO
.ui
.WindowManager
.prototype.getTeardownDelay = function () {
2939 return this.modal
? 250 : 0;
2943 * Get a window by its symbolic name.
2945 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
2946 * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
2947 * for more information about using factories.
2948 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2950 * @param {string} name Symbolic name of the window
2951 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
2952 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
2953 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
2955 OO
.ui
.WindowManager
.prototype.getWindow = function ( name
) {
2956 var deferred
= $.Deferred(),
2957 win
= this.windows
[ name
];
2959 if ( !( win
instanceof OO
.ui
.Window
) ) {
2960 if ( this.factory
) {
2961 if ( !this.factory
.lookup( name
) ) {
2962 deferred
.reject( new OO
.ui
.Error(
2963 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
2966 win
= this.factory
.create( name
);
2967 this.addWindows( [ win
] );
2968 deferred
.resolve( win
);
2971 deferred
.reject( new OO
.ui
.Error(
2972 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
2976 deferred
.resolve( win
);
2979 return deferred
.promise();
2983 * Get current window.
2985 * @return {OO.ui.Window|null} Currently opening/opened/closing window
2987 OO
.ui
.WindowManager
.prototype.getCurrentWindow = function () {
2988 return this.currentWindow
;
2994 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
2995 * @param {Object} [data] Window opening data
2996 * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
2997 * See {@link #event-opening 'opening' event} for more information about `opening` promises.
3000 OO
.ui
.WindowManager
.prototype.openWindow = function ( win
, data
) {
3002 opening
= $.Deferred();
3004 // Argument handling
3005 if ( typeof win
=== 'string' ) {
3006 return this.getWindow( win
).then( function ( win
) {
3007 return manager
.openWindow( win
, data
);
3012 if ( !this.hasWindow( win
) ) {
3013 opening
.reject( new OO
.ui
.Error(
3014 'Cannot open window: window is not attached to manager'
3016 } else if ( this.preparingToOpen
|| this.opening
|| this.opened
) {
3017 opening
.reject( new OO
.ui
.Error(
3018 'Cannot open window: another window is opening or open'
3023 if ( opening
.state() !== 'rejected' ) {
3024 // If a window is currently closing, wait for it to complete
3025 this.preparingToOpen
= $.when( this.closing
);
3026 // Ensure handlers get called after preparingToOpen is set
3027 this.preparingToOpen
.done( function () {
3028 if ( manager
.modal
) {
3029 manager
.toggleGlobalEvents( true );
3030 manager
.toggleAriaIsolation( true );
3032 manager
.currentWindow
= win
;
3033 manager
.opening
= opening
;
3034 manager
.preparingToOpen
= null;
3035 manager
.emit( 'opening', win
, opening
, data
);
3036 setTimeout( function () {
3037 win
.setup( data
).then( function () {
3038 manager
.updateWindowSize( win
);
3039 manager
.opening
.notify( { state
: 'setup' } );
3040 setTimeout( function () {
3041 win
.ready( data
).then( function () {
3042 manager
.opening
.notify( { state
: 'ready' } );
3043 manager
.opening
= null;
3044 manager
.opened
= $.Deferred();
3045 opening
.resolve( manager
.opened
.promise(), data
);
3047 }, manager
.getReadyDelay() );
3049 }, manager
.getSetupDelay() );
3053 return opening
.promise();
3059 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3060 * @param {Object} [data] Window closing data
3061 * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
3062 * See {@link #event-closing 'closing' event} for more information about closing promises.
3063 * @throws {Error} An error is thrown if the window is not managed by the window manager.
3066 OO
.ui
.WindowManager
.prototype.closeWindow = function ( win
, data
) {
3068 closing
= $.Deferred(),
3071 // Argument handling
3072 if ( typeof win
=== 'string' ) {
3073 win
= this.windows
[ win
];
3074 } else if ( !this.hasWindow( win
) ) {
3080 closing
.reject( new OO
.ui
.Error(
3081 'Cannot close window: window is not attached to manager'
3083 } else if ( win
!== this.currentWindow
) {
3084 closing
.reject( new OO
.ui
.Error(
3085 'Cannot close window: window already closed with different data'
3087 } else if ( this.preparingToClose
|| this.closing
) {
3088 closing
.reject( new OO
.ui
.Error(
3089 'Cannot close window: window already closing with different data'
3094 if ( closing
.state() !== 'rejected' ) {
3095 // If the window is currently opening, close it when it's done
3096 this.preparingToClose
= $.when( this.opening
);
3097 // Ensure handlers get called after preparingToClose is set
3098 this.preparingToClose
.done( function () {
3099 manager
.closing
= closing
;
3100 manager
.preparingToClose
= null;
3101 manager
.emit( 'closing', win
, closing
, data
);
3102 opened
= manager
.opened
;
3103 manager
.opened
= null;
3104 opened
.resolve( closing
.promise(), data
);
3105 setTimeout( function () {
3106 win
.hold( data
).then( function () {
3107 closing
.notify( { state
: 'hold' } );
3108 setTimeout( function () {
3109 win
.teardown( data
).then( function () {
3110 closing
.notify( { state
: 'teardown' } );
3111 if ( manager
.modal
) {
3112 manager
.toggleGlobalEvents( false );
3113 manager
.toggleAriaIsolation( false );
3115 manager
.closing
= null;
3116 manager
.currentWindow
= null;
3117 closing
.resolve( data
);
3119 }, manager
.getTeardownDelay() );
3121 }, manager
.getHoldDelay() );
3125 return closing
.promise();
3129 * Add windows to the window manager.
3131 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
3132 * See the [OOjs ui documentation on MediaWiki] [2] for examples.
3133 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3135 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
3136 * by reference, symbolic name, or explicitly defined symbolic names.
3137 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
3138 * explicit nor a statically configured symbolic name.
3140 OO
.ui
.WindowManager
.prototype.addWindows = function ( windows
) {
3141 var i
, len
, win
, name
, list
;
3143 if ( Array
.isArray( windows
) ) {
3144 // Convert to map of windows by looking up symbolic names from static configuration
3146 for ( i
= 0, len
= windows
.length
; i
< len
; i
++ ) {
3147 name
= windows
[ i
].constructor.static.name
;
3148 if ( typeof name
!== 'string' ) {
3149 throw new Error( 'Cannot add window' );
3151 list
[ name
] = windows
[ i
];
3153 } else if ( OO
.isPlainObject( windows
) ) {
3158 for ( name
in list
) {
3160 this.windows
[ name
] = win
.toggle( false );
3161 this.$element
.append( win
.$element
);
3162 win
.setManager( this );
3167 * Remove the specified windows from the windows manager.
3169 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
3170 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
3171 * longer listens to events, use the #destroy method.
3173 * @param {string[]} names Symbolic names of windows to remove
3174 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3175 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
3177 OO
.ui
.WindowManager
.prototype.removeWindows = function ( names
) {
3178 var i
, len
, win
, name
, cleanupWindow
,
3181 cleanup = function ( name
, win
) {
3182 delete manager
.windows
[ name
];
3183 win
.$element
.detach();
3186 for ( i
= 0, len
= names
.length
; i
< len
; i
++ ) {
3188 win
= this.windows
[ name
];
3190 throw new Error( 'Cannot remove window' );
3192 cleanupWindow
= cleanup
.bind( null, name
, win
);
3193 promises
.push( this.closeWindow( name
).then( cleanupWindow
, cleanupWindow
) );
3196 return $.when
.apply( $, promises
);
3200 * Remove all windows from the window manager.
3202 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
3203 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
3204 * To remove just a subset of windows, use the #removeWindows method.
3206 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3208 OO
.ui
.WindowManager
.prototype.clearWindows = function () {
3209 return this.removeWindows( Object
.keys( this.windows
) );
3213 * Set dialog size. In general, this method should not be called directly.
3215 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3219 OO
.ui
.WindowManager
.prototype.updateWindowSize = function ( win
) {
3220 // Bypass for non-current, and thus invisible, windows
3221 if ( win
!== this.currentWindow
) {
3225 var viewport
= OO
.ui
.Element
.static.getDimensions( win
.getElementWindow() ),
3226 sizes
= this.constructor.static.sizes
,
3227 size
= win
.getSize();
3229 if ( !sizes
[ size
] ) {
3230 size
= this.constructor.static.defaultSize
;
3232 if ( size
!== 'full' && viewport
.rect
.right
- viewport
.rect
.left
< sizes
[ size
].width
) {
3236 this.$element
.toggleClass( 'oo-ui-windowManager-fullscreen', size
=== 'full' );
3237 this.$element
.toggleClass( 'oo-ui-windowManager-floating', size
!== 'full' );
3238 win
.setDimensions( sizes
[ size
] );
3240 this.emit( 'resize', win
);
3246 * Bind or unbind global events for scrolling.
3249 * @param {boolean} [on] Bind global events
3252 OO
.ui
.WindowManager
.prototype.toggleGlobalEvents = function ( on
) {
3253 on
= on
=== undefined ? !!this.globalEvents
: !!on
;
3255 var $body
= $( this.getElementDocument().body
),
3256 // We could have multiple window managers open to only modify
3257 // the body class at the bottom of the stack
3258 stackDepth
= $body
.data( 'windowManagerGlobalEvents' ) || 0 ;
3261 if ( !this.globalEvents
) {
3262 $( this.getElementWindow() ).on( {
3263 // Start listening for top-level window dimension changes
3264 'orientationchange resize': this.onWindowResizeHandler
3266 if ( stackDepth
=== 0 ) {
3267 $body
.css( 'overflow', 'hidden' );
3270 this.globalEvents
= true;
3272 } else if ( this.globalEvents
) {
3273 $( this.getElementWindow() ).off( {
3274 // Stop listening for top-level window dimension changes
3275 'orientationchange resize': this.onWindowResizeHandler
3278 if ( stackDepth
=== 0 ) {
3279 $( this.getElementDocument().body
).css( 'overflow', '' );
3281 this.globalEvents
= false;
3283 $body
.data( 'windowManagerGlobalEvents', stackDepth
);
3289 * Toggle screen reader visibility of content other than the window manager.
3292 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3295 OO
.ui
.WindowManager
.prototype.toggleAriaIsolation = function ( isolate
) {
3296 isolate
= isolate
=== undefined ? !this.$ariaHidden
: !!isolate
;
3299 if ( !this.$ariaHidden
) {
3300 // Hide everything other than the window manager from screen readers
3301 this.$ariaHidden
= $( 'body' )
3303 .not( this.$element
.parentsUntil( 'body' ).last() )
3304 .attr( 'aria-hidden', '' );
3306 } else if ( this.$ariaHidden
) {
3307 // Restore screen reader visibility
3308 this.$ariaHidden
.removeAttr( 'aria-hidden' );
3309 this.$ariaHidden
= null;
3316 * Destroy the window manager.
3318 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
3319 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
3322 OO
.ui
.WindowManager
.prototype.destroy = function () {
3323 this.toggleGlobalEvents( false );
3324 this.toggleAriaIsolation( false );
3325 this.clearWindows();
3326 this.$element
.remove();
3333 * @param {string|jQuery} message Description of error
3334 * @param {Object} [config] Configuration options
3335 * @cfg {boolean} [recoverable=true] Error is recoverable
3336 * @cfg {boolean} [warning=false] Whether this error is a warning or not.
3338 OO
.ui
.Error
= function OoUiError( message
, config
) {
3339 // Allow passing positional parameters inside the config object
3340 if ( OO
.isPlainObject( message
) && config
=== undefined ) {
3342 message
= config
.message
;
3345 // Configuration initialization
3346 config
= config
|| {};
3349 this.message
= message
instanceof jQuery
? message
: String( message
);
3350 this.recoverable
= config
.recoverable
=== undefined || !!config
.recoverable
;
3351 this.warning
= !!config
.warning
;
3356 OO
.initClass( OO
.ui
.Error
);
3361 * Check if error can be recovered from.
3363 * @return {boolean} Error is recoverable
3365 OO
.ui
.Error
.prototype.isRecoverable = function () {
3366 return this.recoverable
;
3370 * Check if the error is a warning
3372 * @return {boolean} Error is warning
3374 OO
.ui
.Error
.prototype.isWarning = function () {
3375 return this.warning
;
3379 * Get error message as DOM nodes.
3381 * @return {jQuery} Error message in DOM nodes
3383 OO
.ui
.Error
.prototype.getMessage = function () {
3384 return this.message
instanceof jQuery
?
3385 this.message
.clone() :
3386 $( '<div>' ).text( this.message
).contents();
3390 * Get error message as text.
3392 * @return {string} Error message
3394 OO
.ui
.Error
.prototype.getMessageText = function () {
3395 return this.message
instanceof jQuery
? this.message
.text() : this.message
;
3399 * Wraps an HTML snippet for use with configuration values which default
3400 * to strings. This bypasses the default html-escaping done to string
3406 * @param {string} [content] HTML content
3408 OO
.ui
.HtmlSnippet
= function OoUiHtmlSnippet( content
) {
3410 this.content
= content
;
3415 OO
.initClass( OO
.ui
.HtmlSnippet
);
3422 * @return {string} Unchanged HTML snippet.
3424 OO
.ui
.HtmlSnippet
.prototype.toString = function () {
3425 return this.content
;
3429 * A list of functions, called in sequence.
3431 * If a function added to a process returns boolean false the process will stop; if it returns an
3432 * object with a `promise` method the process will use the promise to either continue to the next
3433 * step when the promise is resolved or stop when the promise is rejected.
3438 * @param {number|jQuery.Promise|Function} step Time to wait, promise to wait for or function to
3439 * call, see #createStep for more information
3440 * @param {Object} [context=null] Context to call the step function in, ignored if step is a number
3442 * @return {Object} Step object, with `callback` and `context` properties
3444 OO
.ui
.Process = function ( step
, context
) {
3449 if ( step
!== undefined ) {
3450 this.next( step
, context
);
3456 OO
.initClass( OO
.ui
.Process
);
3461 * Start the process.
3463 * @return {jQuery.Promise} Promise that is resolved when all steps have completed or rejected when
3464 * any of the steps return boolean false or a promise which gets rejected; upon stopping the
3465 * process, the remaining steps will not be taken
3467 OO
.ui
.Process
.prototype.execute = function () {
3468 var i
, len
, promise
;
3471 * Continue execution.
3474 * @param {Array} step A function and the context it should be called in
3475 * @return {Function} Function that continues the process
3477 function proceed( step
) {
3478 return function () {
3479 // Execute step in the correct context
3481 result
= step
.callback
.call( step
.context
);
3483 if ( result
=== false ) {
3484 // Use rejected promise for boolean false results
3485 return $.Deferred().reject( [] ).promise();
3487 if ( typeof result
=== 'number' ) {
3489 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3491 // Use a delayed promise for numbers, expecting them to be in milliseconds
3492 deferred
= $.Deferred();
3493 setTimeout( deferred
.resolve
, result
);
3494 return deferred
.promise();
3496 if ( result
instanceof OO
.ui
.Error
) {
3497 // Use rejected promise for error
3498 return $.Deferred().reject( [ result
] ).promise();
3500 if ( Array
.isArray( result
) && result
.length
&& result
[ 0 ] instanceof OO
.ui
.Error
) {
3501 // Use rejected promise for list of errors
3502 return $.Deferred().reject( result
).promise();
3504 // Duck-type the object to see if it can produce a promise
3505 if ( result
&& $.isFunction( result
.promise
) ) {
3506 // Use a promise generated from the result
3507 return result
.promise();
3509 // Use resolved promise for other results
3510 return $.Deferred().resolve().promise();
3514 if ( this.steps
.length
) {
3515 // Generate a chain reaction of promises
3516 promise
= proceed( this.steps
[ 0 ] )();
3517 for ( i
= 1, len
= this.steps
.length
; i
< len
; i
++ ) {
3518 promise
= promise
.then( proceed( this.steps
[ i
] ) );
3521 promise
= $.Deferred().resolve().promise();
3528 * Create a process step.
3531 * @param {number|jQuery.Promise|Function} step
3533 * - Number of milliseconds to wait; or
3534 * - Promise to wait to be resolved; or
3535 * - Function to execute
3536 * - If it returns boolean false the process will stop
3537 * - If it returns an object with a `promise` method the process will use the promise to either
3538 * continue to the next step when the promise is resolved or stop when the promise is rejected
3539 * - If it returns a number, the process will wait for that number of milliseconds before
3541 * @param {Object} [context=null] Context to call the step function in, ignored if step is a number
3543 * @return {Object} Step object, with `callback` and `context` properties
3545 OO
.ui
.Process
.prototype.createStep = function ( step
, context
) {
3546 if ( typeof step
=== 'number' || $.isFunction( step
.promise
) ) {
3548 callback: function () {
3554 if ( $.isFunction( step
) ) {
3560 throw new Error( 'Cannot create process step: number, promise or function expected' );
3564 * Add step to the beginning of the process.
3566 * @inheritdoc #createStep
3567 * @return {OO.ui.Process} this
3570 OO
.ui
.Process
.prototype.first = function ( step
, context
) {
3571 this.steps
.unshift( this.createStep( step
, context
) );
3576 * Add step to the end of the process.
3578 * @inheritdoc #createStep
3579 * @return {OO.ui.Process} this
3582 OO
.ui
.Process
.prototype.next = function ( step
, context
) {
3583 this.steps
.push( this.createStep( step
, context
) );
3588 * Factory for tools.
3591 * @extends OO.Factory
3594 OO
.ui
.ToolFactory
= function OoUiToolFactory() {
3595 // Parent constructor
3596 OO
.ui
.ToolFactory
.super.call( this );
3601 OO
.inheritClass( OO
.ui
.ToolFactory
, OO
.Factory
);
3606 * Get tools from the factory
3608 * @param {Array} include Included tools
3609 * @param {Array} exclude Excluded tools
3610 * @param {Array} promote Promoted tools
3611 * @param {Array} demote Demoted tools
3612 * @return {string[]} List of tools
3614 OO
.ui
.ToolFactory
.prototype.getTools = function ( include
, exclude
, promote
, demote
) {
3615 var i
, len
, included
, promoted
, demoted
,
3619 // Collect included and not excluded tools
3620 included
= OO
.simpleArrayDifference( this.extract( include
), this.extract( exclude
) );
3623 promoted
= this.extract( promote
, used
);
3624 demoted
= this.extract( demote
, used
);
3627 for ( i
= 0, len
= included
.length
; i
< len
; i
++ ) {
3628 if ( !used
[ included
[ i
] ] ) {
3629 auto
.push( included
[ i
] );
3633 return promoted
.concat( auto
).concat( demoted
);
3637 * Get a flat list of names from a list of names or groups.
3639 * Tools can be specified in the following ways:
3641 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
3642 * - All tools in a group: `{ group: 'group-name' }`
3643 * - All tools: `'*'`
3646 * @param {Array|string} collection List of tools
3647 * @param {Object} [used] Object with names that should be skipped as properties; extracted
3648 * names will be added as properties
3649 * @return {string[]} List of extracted names
3651 OO
.ui
.ToolFactory
.prototype.extract = function ( collection
, used
) {
3652 var i
, len
, item
, name
, tool
,
3655 if ( collection
=== '*' ) {
3656 for ( name
in this.registry
) {
3657 tool
= this.registry
[ name
];
3659 // Only add tools by group name when auto-add is enabled
3660 tool
.static.autoAddToCatchall
&&
3661 // Exclude already used tools
3662 ( !used
|| !used
[ name
] )
3666 used
[ name
] = true;
3670 } else if ( Array
.isArray( collection
) ) {
3671 for ( i
= 0, len
= collection
.length
; i
< len
; i
++ ) {
3672 item
= collection
[ i
];
3673 // Allow plain strings as shorthand for named tools
3674 if ( typeof item
=== 'string' ) {
3675 item
= { name
: item
};
3677 if ( OO
.isPlainObject( item
) ) {
3679 for ( name
in this.registry
) {
3680 tool
= this.registry
[ name
];
3682 // Include tools with matching group
3683 tool
.static.group
=== item
.group
&&
3684 // Only add tools by group name when auto-add is enabled
3685 tool
.static.autoAddToGroup
&&
3686 // Exclude already used tools
3687 ( !used
|| !used
[ name
] )
3691 used
[ name
] = true;
3695 // Include tools with matching name and exclude already used tools
3696 } else if ( item
.name
&& ( !used
|| !used
[ item
.name
] ) ) {
3697 names
.push( item
.name
);
3699 used
[ item
.name
] = true;
3709 * Factory for tool groups.
3712 * @extends OO.Factory
3715 OO
.ui
.ToolGroupFactory
= function OoUiToolGroupFactory() {
3716 // Parent constructor
3717 OO
.Factory
.call( this );
3720 defaultClasses
= this.constructor.static.getDefaultClasses();
3722 // Register default toolgroups
3723 for ( i
= 0, l
= defaultClasses
.length
; i
< l
; i
++ ) {
3724 this.register( defaultClasses
[ i
] );
3730 OO
.inheritClass( OO
.ui
.ToolGroupFactory
, OO
.Factory
);
3732 /* Static Methods */
3735 * Get a default set of classes to be registered on construction
3737 * @return {Function[]} Default classes
3739 OO
.ui
.ToolGroupFactory
.static.getDefaultClasses = function () {
3742 OO
.ui
.ListToolGroup
,
3754 * @param {Object} [config] Configuration options
3756 OO
.ui
.Theme
= function OoUiTheme( config
) {
3757 // Configuration initialization
3758 config
= config
|| {};
3763 OO
.initClass( OO
.ui
.Theme
);
3768 * Get a list of classes to be applied to a widget.
3770 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
3771 * otherwise state transitions will not work properly.
3773 * @param {OO.ui.Element} element Element for which to get classes
3774 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
3776 OO
.ui
.Theme
.prototype.getElementClasses = function ( /* element */ ) {
3777 return { on
: [], off
: [] };
3781 * Update CSS classes provided by the theme.
3783 * For elements with theme logic hooks, this should be called any time there's a state change.
3785 * @param {OO.ui.Element} element Element for which to update classes
3786 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
3788 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
3789 var classes
= this.getElementClasses( element
);
3792 .removeClass( classes
.off
.join( ' ' ) )
3793 .addClass( classes
.on
.join( ' ' ) );
3797 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
3798 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
3799 * order in which users will navigate through the focusable elements via the "tab" key.
3802 * // TabIndexedElement is mixed into the ButtonWidget class
3803 * // to provide a tabIndex property.
3804 * var button1 = new OO.ui.ButtonWidget( {
3808 * var button2 = new OO.ui.ButtonWidget( {
3812 * var button3 = new OO.ui.ButtonWidget( {
3816 * var button4 = new OO.ui.ButtonWidget( {
3820 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
3826 * @param {Object} [config] Configuration options
3827 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
3828 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
3829 * functionality will be applied to it instead.
3830 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
3831 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
3832 * to remove the element from the tab-navigation flow.
3834 OO
.ui
.TabIndexedElement
= function OoUiTabIndexedElement( config
) {
3835 // Configuration initialization
3836 config
= $.extend( { tabIndex
: 0 }, config
);
3839 this.$tabIndexed
= null;
3840 this.tabIndex
= null;
3843 this.connect( this, { disable
: 'onDisable' } );
3846 this.setTabIndex( config
.tabIndex
);
3847 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
3852 OO
.initClass( OO
.ui
.TabIndexedElement
);
3857 * Set the element that should use the tabindex functionality.
3859 * This method is used to retarget a tabindex mixin so that its functionality applies
3860 * to the specified element. If an element is currently using the functionality, the mixin’s
3861 * effect on that element is removed before the new element is set up.
3863 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
3866 OO
.ui
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
3867 var tabIndex
= this.tabIndex
;
3868 // Remove attributes from old $tabIndexed
3869 this.setTabIndex( null );
3870 // Force update of new $tabIndexed
3871 this.$tabIndexed
= $tabIndexed
;
3872 this.tabIndex
= tabIndex
;
3873 return this.updateTabIndex();
3877 * Set the value of the tabindex.
3879 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
3882 OO
.ui
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
3883 tabIndex
= typeof tabIndex
=== 'number' ? tabIndex
: null;
3885 if ( this.tabIndex
!== tabIndex
) {
3886 this.tabIndex
= tabIndex
;
3887 this.updateTabIndex();
3894 * Update the `tabindex` attribute, in case of changes to tab index or
3899 OO
.ui
.TabIndexedElement
.prototype.updateTabIndex = function () {
3900 if ( this.$tabIndexed
) {
3901 if ( this.tabIndex
!== null ) {
3902 // Do not index over disabled elements
3903 this.$tabIndexed
.attr( {
3904 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
3905 // ChromeVox and NVDA do not seem to inherit this from parent elements
3906 'aria-disabled': this.isDisabled().toString()
3909 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
3916 * Handle disable events.
3919 * @param {boolean} disabled Element is disabled
3921 OO
.ui
.TabIndexedElement
.prototype.onDisable = function () {
3922 this.updateTabIndex();
3926 * Get the value of the tabindex.
3928 * @return {number|null} Tabindex value
3930 OO
.ui
.TabIndexedElement
.prototype.getTabIndex = function () {
3931 return this.tabIndex
;
3935 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
3936 * interface element that can be configured with access keys for accessibility.
3937 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
3939 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
3944 * @param {Object} [config] Configuration options
3945 * @cfg {jQuery} [$button] Button node, assigned to #$button, omit to use a generated `<a>`
3946 * @cfg {boolean} [framed=true] Render button with a frame
3947 * @cfg {string} [accessKey] Button's access key
3949 OO
.ui
.ButtonElement
= function OoUiButtonElement( config
) {
3950 // Configuration initialization
3951 config
= config
|| {};
3954 this.$button
= null;
3956 this.accessKey
= null;
3957 this.active
= false;
3958 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
3959 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
3960 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
3961 this.onKeyUpHandler
= this.onKeyUp
.bind( this );
3962 this.onClickHandler
= this.onClick
.bind( this );
3963 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
3966 this.$element
.addClass( 'oo-ui-buttonElement' );
3967 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
3968 this.setAccessKey( config
.accessKey
);
3969 this.setButtonElement( config
.$button
|| $( '<a>' ) );
3974 OO
.initClass( OO
.ui
.ButtonElement
);
3976 /* Static Properties */
3979 * Cancel mouse down events.
3983 * @property {boolean}
3985 OO
.ui
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
3996 * Set the button element.
3998 * If an element is already set, it will be cleaned up before setting up the new element.
4000 * @param {jQuery} $button Element to use as button
4002 OO
.ui
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
4003 if ( this.$button
) {
4005 .removeClass( 'oo-ui-buttonElement-button' )
4006 .removeAttr( 'role accesskey' )
4008 mousedown
: this.onMouseDownHandler
,
4009 keydown
: this.onKeyDownHandler
,
4010 click
: this.onClickHandler
,
4011 keypress
: this.onKeyPressHandler
4015 this.$button
= $button
4016 .addClass( 'oo-ui-buttonElement-button' )
4017 .attr( { role
: 'button', accesskey
: this.accessKey
} )
4019 mousedown
: this.onMouseDownHandler
,
4020 keydown
: this.onKeyDownHandler
,
4021 click
: this.onClickHandler
,
4022 keypress
: this.onKeyPressHandler
4027 * Handles mouse down events.
4030 * @param {jQuery.Event} e Mouse down event
4032 OO
.ui
.ButtonElement
.prototype.onMouseDown = function ( e
) {
4033 if ( this.isDisabled() || e
.which
!== 1 ) {
4036 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
4037 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4038 // reliably remove the pressed class
4039 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
4040 // Prevent change of focus unless specifically configured otherwise
4041 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
4047 * Handles mouse up events.
4050 * @param {jQuery.Event} e Mouse up event
4052 OO
.ui
.ButtonElement
.prototype.onMouseUp = function ( e
) {
4053 if ( this.isDisabled() || e
.which
!== 1 ) {
4056 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
4057 // Stop listening for mouseup, since we only needed this once
4058 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
4062 * Handles mouse click events.
4065 * @param {jQuery.Event} e Mouse click event
4068 OO
.ui
.ButtonElement
.prototype.onClick = function ( e
) {
4069 if ( !this.isDisabled() && e
.which
=== 1 ) {
4070 this.emit( 'click' );
4076 * Handles key down events.
4079 * @param {jQuery.Event} e Key down event
4081 OO
.ui
.ButtonElement
.prototype.onKeyDown = function ( e
) {
4082 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
4085 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
4086 // Run the keyup handler no matter where the key is when the button is let go, so we can
4087 // reliably remove the pressed class
4088 this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler
, true );
4092 * Handles key up events.
4095 * @param {jQuery.Event} e Key up event
4097 OO
.ui
.ButtonElement
.prototype.onKeyUp = function ( e
) {
4098 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
4101 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
4102 // Stop listening for keyup, since we only needed this once
4103 this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler
, true );
4107 * Handles key press events.
4110 * @param {jQuery.Event} e Key press event
4113 OO
.ui
.ButtonElement
.prototype.onKeyPress = function ( e
) {
4114 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
4115 this.emit( 'click' );
4121 * Check if button has a frame.
4123 * @return {boolean} Button is framed
4125 OO
.ui
.ButtonElement
.prototype.isFramed = function () {
4132 * @param {boolean} [framed] Make button framed, omit to toggle
4135 OO
.ui
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
4136 framed
= framed
=== undefined ? !this.framed
: !!framed
;
4137 if ( framed
!== this.framed
) {
4138 this.framed
= framed
;
4140 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
4141 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
4142 this.updateThemeClasses();
4151 * @param {string} accessKey Button's access key, use empty string to remove
4154 OO
.ui
.ButtonElement
.prototype.setAccessKey = function ( accessKey
) {
4155 accessKey
= typeof accessKey
=== 'string' && accessKey
.length
? accessKey
: null;
4157 if ( this.accessKey
!== accessKey
) {
4158 if ( this.$button
) {
4159 if ( accessKey
!== null ) {
4160 this.$button
.attr( 'accesskey', accessKey
);
4162 this.$button
.removeAttr( 'accesskey' );
4165 this.accessKey
= accessKey
;
4174 * @param {boolean} [value] Make button active
4177 OO
.ui
.ButtonElement
.prototype.setActive = function ( value
) {
4178 this.$element
.toggleClass( 'oo-ui-buttonElement-active', !!value
);
4183 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4184 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4185 * items from the group is done through the interface the class provides.
4186 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4188 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4194 * @param {Object} [config] Configuration options
4195 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4196 * is omitted, the group element will use a generated `<div>`.
4198 OO
.ui
.GroupElement
= function OoUiGroupElement( config
) {
4199 // Configuration initialization
4200 config
= config
|| {};
4205 this.aggregateItemEvents
= {};
4208 this.setGroupElement( config
.$group
|| $( '<div>' ) );
4214 * Set the group element.
4216 * If an element is already set, items will be moved to the new element.
4218 * @param {jQuery} $group Element to use as group
4220 OO
.ui
.GroupElement
.prototype.setGroupElement = function ( $group
) {
4223 this.$group
= $group
;
4224 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4225 this.$group
.append( this.items
[ i
].$element
);
4230 * Check if a group contains no items.
4232 * @return {boolean} Group is empty
4234 OO
.ui
.GroupElement
.prototype.isEmpty = function () {
4235 return !this.items
.length
;
4239 * Get all items in the group.
4241 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4242 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4245 * @return {OO.ui.Element[]} An array of items.
4247 OO
.ui
.GroupElement
.prototype.getItems = function () {
4248 return this.items
.slice( 0 );
4252 * Get an item by its data.
4254 * Only the first item with matching data will be returned. To return all matching items,
4255 * use the #getItemsFromData method.
4257 * @param {Object} data Item data to search for
4258 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4260 OO
.ui
.GroupElement
.prototype.getItemFromData = function ( data
) {
4262 hash
= OO
.getHash( data
);
4264 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4265 item
= this.items
[ i
];
4266 if ( hash
=== OO
.getHash( item
.getData() ) ) {
4275 * Get items by their data.
4277 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4279 * @param {Object} data Item data to search for
4280 * @return {OO.ui.Element[]} Items with equivalent data
4282 OO
.ui
.GroupElement
.prototype.getItemsFromData = function ( data
) {
4284 hash
= OO
.getHash( data
),
4287 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4288 item
= this.items
[ i
];
4289 if ( hash
=== OO
.getHash( item
.getData() ) ) {
4298 * Aggregate the events emitted by the group.
4300 * When events are aggregated, the group will listen to all contained items for the event,
4301 * and then emit the event under a new name. The new event will contain an additional leading
4302 * parameter containing the item that emitted the original event. Other arguments emitted from
4303 * the original event are passed through.
4305 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
4306 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
4307 * A `null` value will remove aggregated events.
4309 * @throws {Error} An error is thrown if aggregation already exists.
4311 OO
.ui
.GroupElement
.prototype.aggregate = function ( events
) {
4312 var i
, len
, item
, add
, remove
, itemEvent
, groupEvent
;
4314 for ( itemEvent
in events
) {
4315 groupEvent
= events
[ itemEvent
];
4317 // Remove existing aggregated event
4318 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4319 // Don't allow duplicate aggregations
4321 throw new Error( 'Duplicate item event aggregation for ' + itemEvent
);
4323 // Remove event aggregation from existing items
4324 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4325 item
= this.items
[ i
];
4326 if ( item
.connect
&& item
.disconnect
) {
4328 remove
[ itemEvent
] = [ 'emit', groupEvent
, item
];
4329 item
.disconnect( this, remove
);
4332 // Prevent future items from aggregating event
4333 delete this.aggregateItemEvents
[ itemEvent
];
4336 // Add new aggregate event
4338 // Make future items aggregate event
4339 this.aggregateItemEvents
[ itemEvent
] = groupEvent
;
4340 // Add event aggregation to existing items
4341 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4342 item
= this.items
[ i
];
4343 if ( item
.connect
&& item
.disconnect
) {
4345 add
[ itemEvent
] = [ 'emit', groupEvent
, item
];
4346 item
.connect( this, add
);
4354 * Add items to the group.
4356 * Items will be added to the end of the group array unless the optional `index` parameter specifies
4357 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
4359 * @param {OO.ui.Element[]} items An array of items to add to the group
4360 * @param {number} [index] Index of the insertion point
4363 OO
.ui
.GroupElement
.prototype.addItems = function ( items
, index
) {
4364 var i
, len
, item
, event
, events
, currentIndex
,
4367 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
4370 // Check if item exists then remove it first, effectively "moving" it
4371 currentIndex
= $.inArray( item
, this.items
);
4372 if ( currentIndex
>= 0 ) {
4373 this.removeItems( [ item
] );
4374 // Adjust index to compensate for removal
4375 if ( currentIndex
< index
) {
4380 if ( item
.connect
&& item
.disconnect
&& !$.isEmptyObject( this.aggregateItemEvents
) ) {
4382 for ( event
in this.aggregateItemEvents
) {
4383 events
[ event
] = [ 'emit', this.aggregateItemEvents
[ event
], item
];
4385 item
.connect( this, events
);
4387 item
.setElementGroup( this );
4388 itemElements
.push( item
.$element
.get( 0 ) );
4391 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
4392 this.$group
.append( itemElements
);
4393 this.items
.push
.apply( this.items
, items
);
4394 } else if ( index
=== 0 ) {
4395 this.$group
.prepend( itemElements
);
4396 this.items
.unshift
.apply( this.items
, items
);
4398 this.items
[ index
].$element
.before( itemElements
);
4399 this.items
.splice
.apply( this.items
, [ index
, 0 ].concat( items
) );
4406 * Remove the specified items from a group.
4408 * Removed items are detached (not removed) from the DOM so that they may be reused.
4409 * To remove all items from a group, you may wish to use the #clearItems method instead.
4411 * @param {OO.ui.Element[]} items An array of items to remove
4414 OO
.ui
.GroupElement
.prototype.removeItems = function ( items
) {
4415 var i
, len
, item
, index
, remove
, itemEvent
;
4417 // Remove specific items
4418 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
4420 index
= $.inArray( item
, this.items
);
4421 if ( index
!== -1 ) {
4423 item
.connect
&& item
.disconnect
&&
4424 !$.isEmptyObject( this.aggregateItemEvents
)
4427 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4428 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4430 item
.disconnect( this, remove
);
4432 item
.setElementGroup( null );
4433 this.items
.splice( index
, 1 );
4434 item
.$element
.detach();
4442 * Clear all items from the group.
4444 * Cleared items are detached from the DOM, not removed, so that they may be reused.
4445 * To remove only a subset of items from a group, use the #removeItems method.
4449 OO
.ui
.GroupElement
.prototype.clearItems = function () {
4450 var i
, len
, item
, remove
, itemEvent
;
4453 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4454 item
= this.items
[ i
];
4456 item
.connect
&& item
.disconnect
&&
4457 !$.isEmptyObject( this.aggregateItemEvents
)
4460 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4461 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4463 item
.disconnect( this, remove
);
4465 item
.setElementGroup( null );
4466 item
.$element
.detach();
4474 * DraggableElement is a mixin class used to create elements that can be clicked
4475 * and dragged by a mouse to a new position within a group. This class must be used
4476 * in conjunction with OO.ui.DraggableGroupElement, which provides a container for
4477 * the draggable elements.
4484 OO
.ui
.DraggableElement
= function OoUiDraggableElement() {
4488 // Initialize and events
4490 .attr( 'draggable', true )
4491 .addClass( 'oo-ui-draggableElement' )
4493 dragstart
: this.onDragStart
.bind( this ),
4494 dragover
: this.onDragOver
.bind( this ),
4495 dragend
: this.onDragEnd
.bind( this ),
4496 drop
: this.onDrop
.bind( this )
4500 OO
.initClass( OO
.ui
.DraggableElement
);
4507 * A dragstart event is emitted when the user clicks and begins dragging an item.
4508 * @param {OO.ui.DraggableElement} item The item the user has clicked and is dragging with the mouse.
4513 * A dragend event is emitted when the user drags an item and releases the mouse,
4514 * thus terminating the drag operation.
4519 * A drop event is emitted when the user drags an item and then releases the mouse button
4520 * over a valid target.
4523 /* Static Properties */
4526 * @inheritdoc OO.ui.ButtonElement
4528 OO
.ui
.DraggableElement
.static.cancelButtonMouseDownEvents
= false;
4533 * Respond to dragstart event.
4536 * @param {jQuery.Event} event jQuery event
4539 OO
.ui
.DraggableElement
.prototype.onDragStart = function ( e
) {
4540 var dataTransfer
= e
.originalEvent
.dataTransfer
;
4541 // Define drop effect
4542 dataTransfer
.dropEffect
= 'none';
4543 dataTransfer
.effectAllowed
= 'move';
4544 // We must set up a dataTransfer data property or Firefox seems to
4545 // ignore the fact the element is draggable.
4547 dataTransfer
.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
4549 // The above is only for firefox. No need to set a catch clause
4550 // if it fails, move on.
4552 // Add dragging class
4553 this.$element
.addClass( 'oo-ui-draggableElement-dragging' );
4555 this.emit( 'dragstart', this );
4560 * Respond to dragend event.
4565 OO
.ui
.DraggableElement
.prototype.onDragEnd = function () {
4566 this.$element
.removeClass( 'oo-ui-draggableElement-dragging' );
4567 this.emit( 'dragend' );
4571 * Handle drop event.
4574 * @param {jQuery.Event} event jQuery event
4577 OO
.ui
.DraggableElement
.prototype.onDrop = function ( e
) {
4579 this.emit( 'drop', e
);
4583 * In order for drag/drop to work, the dragover event must
4584 * return false and stop propogation.
4588 OO
.ui
.DraggableElement
.prototype.onDragOver = function ( e
) {
4594 * Store it in the DOM so we can access from the widget drag event
4597 * @param {number} Item index
4599 OO
.ui
.DraggableElement
.prototype.setIndex = function ( index
) {
4600 if ( this.index
!== index
) {
4602 this.$element
.data( 'index', index
);
4610 * @return {number} Item index
4612 OO
.ui
.DraggableElement
.prototype.getIndex = function () {
4617 * DraggableGroupElement is a mixin class used to create a group element to
4618 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
4619 * The class is used with OO.ui.DraggableElement.
4623 * @mixins OO.ui.GroupElement
4626 * @param {Object} [config] Configuration options
4627 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
4628 * should match the layout of the items. Items displayed in a single row
4629 * or in several rows should use horizontal orientation. The vertical orientation should only be
4630 * used when the items are displayed in a single column. Defaults to 'vertical'
4632 OO
.ui
.DraggableGroupElement
= function OoUiDraggableGroupElement( config
) {
4633 // Configuration initialization
4634 config
= config
|| {};
4636 // Parent constructor
4637 OO
.ui
.GroupElement
.call( this, config
);
4640 this.orientation
= config
.orientation
|| 'vertical';
4641 this.dragItem
= null;
4642 this.itemDragOver
= null;
4644 this.sideInsertion
= '';
4648 dragstart
: 'itemDragStart',
4649 dragend
: 'itemDragEnd',
4652 this.connect( this, {
4653 itemDragStart
: 'onItemDragStart',
4654 itemDrop
: 'onItemDrop',
4655 itemDragEnd
: 'onItemDragEnd'
4658 dragover
: $.proxy( this.onDragOver
, this ),
4659 dragleave
: $.proxy( this.onDragLeave
, this )
4663 if ( Array
.isArray( config
.items
) ) {
4664 this.addItems( config
.items
);
4666 this.$placeholder
= $( '<div>' )
4667 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
4669 .addClass( 'oo-ui-draggableGroupElement' )
4670 .append( this.$status
)
4671 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation
=== 'horizontal' )
4672 .prepend( this.$placeholder
);
4676 OO
.mixinClass( OO
.ui
.DraggableGroupElement
, OO
.ui
.GroupElement
);
4681 * A 'reorder' event is emitted when the order of items in the group changes.
4684 * @param {OO.ui.DraggableElement} item Reordered item
4685 * @param {number} [newIndex] New index for the item
4691 * Respond to item drag start event
4694 * @param {OO.ui.DraggableElement} item Dragged item
4696 OO
.ui
.DraggableGroupElement
.prototype.onItemDragStart = function ( item
) {
4699 // Map the index of each object
4700 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4701 this.items
[ i
].setIndex( i
);
4704 if ( this.orientation
=== 'horizontal' ) {
4705 // Set the height of the indicator
4706 this.$placeholder
.css( {
4707 height
: item
.$element
.outerHeight(),
4711 // Set the width of the indicator
4712 this.$placeholder
.css( {
4714 width
: item
.$element
.outerWidth()
4717 this.setDragItem( item
);
4721 * Respond to item drag end event
4725 OO
.ui
.DraggableGroupElement
.prototype.onItemDragEnd = function () {
4726 this.unsetDragItem();
4731 * Handle drop event and switch the order of the items accordingly
4734 * @param {OO.ui.DraggableElement} item Dropped item
4737 OO
.ui
.DraggableGroupElement
.prototype.onItemDrop = function ( item
) {
4738 var toIndex
= item
.getIndex();
4739 // Check if the dropped item is from the current group
4740 // TODO: Figure out a way to configure a list of legally droppable
4741 // elements even if they are not yet in the list
4742 if ( this.getDragItem() ) {
4743 // If the insertion point is 'after', the insertion index
4744 // is shifted to the right (or to the left in RTL, hence 'after')
4745 if ( this.sideInsertion
=== 'after' ) {
4748 // Emit change event
4749 this.emit( 'reorder', this.getDragItem(), toIndex
);
4751 this.unsetDragItem();
4752 // Return false to prevent propogation
4757 * Handle dragleave event.
4761 OO
.ui
.DraggableGroupElement
.prototype.onDragLeave = function () {
4762 // This means the item was dragged outside the widget
4765 .addClass( 'oo-ui-element-hidden' );
4769 * Respond to dragover event
4772 * @param {jQuery.Event} event Event details
4774 OO
.ui
.DraggableGroupElement
.prototype.onDragOver = function ( e
) {
4775 var dragOverObj
, $optionWidget
, itemOffset
, itemMidpoint
, itemBoundingRect
,
4776 itemSize
, cssOutput
, dragPosition
, itemIndex
, itemPosition
,
4777 clientX
= e
.originalEvent
.clientX
,
4778 clientY
= e
.originalEvent
.clientY
;
4780 // Get the OptionWidget item we are dragging over
4781 dragOverObj
= this.getElementDocument().elementFromPoint( clientX
, clientY
);
4782 $optionWidget
= $( dragOverObj
).closest( '.oo-ui-draggableElement' );
4783 if ( $optionWidget
[ 0 ] ) {
4784 itemOffset
= $optionWidget
.offset();
4785 itemBoundingRect
= $optionWidget
[ 0 ].getBoundingClientRect();
4786 itemPosition
= $optionWidget
.position();
4787 itemIndex
= $optionWidget
.data( 'index' );
4792 this.isDragging() &&
4793 itemIndex
!== this.getDragItem().getIndex()
4795 if ( this.orientation
=== 'horizontal' ) {
4796 // Calculate where the mouse is relative to the item width
4797 itemSize
= itemBoundingRect
.width
;
4798 itemMidpoint
= itemBoundingRect
.left
+ itemSize
/ 2;
4799 dragPosition
= clientX
;
4800 // Which side of the item we hover over will dictate
4801 // where the placeholder will appear, on the left or
4804 left
: dragPosition
< itemMidpoint
? itemPosition
.left
: itemPosition
.left
+ itemSize
,
4805 top
: itemPosition
.top
4808 // Calculate where the mouse is relative to the item height
4809 itemSize
= itemBoundingRect
.height
;
4810 itemMidpoint
= itemBoundingRect
.top
+ itemSize
/ 2;
4811 dragPosition
= clientY
;
4812 // Which side of the item we hover over will dictate
4813 // where the placeholder will appear, on the top or
4816 top
: dragPosition
< itemMidpoint
? itemPosition
.top
: itemPosition
.top
+ itemSize
,
4817 left
: itemPosition
.left
4820 // Store whether we are before or after an item to rearrange
4821 // For horizontal layout, we need to account for RTL, as this is flipped
4822 if ( this.orientation
=== 'horizontal' && this.$element
.css( 'direction' ) === 'rtl' ) {
4823 this.sideInsertion
= dragPosition
< itemMidpoint
? 'after' : 'before';
4825 this.sideInsertion
= dragPosition
< itemMidpoint
? 'before' : 'after';
4827 // Add drop indicator between objects
4830 .removeClass( 'oo-ui-element-hidden' );
4832 // This means the item was dragged outside the widget
4835 .addClass( 'oo-ui-element-hidden' );
4842 * Set a dragged item
4844 * @param {OO.ui.DraggableElement} item Dragged item
4846 OO
.ui
.DraggableGroupElement
.prototype.setDragItem = function ( item
) {
4847 this.dragItem
= item
;
4851 * Unset the current dragged item
4853 OO
.ui
.DraggableGroupElement
.prototype.unsetDragItem = function () {
4854 this.dragItem
= null;
4855 this.itemDragOver
= null;
4856 this.$placeholder
.addClass( 'oo-ui-element-hidden' );
4857 this.sideInsertion
= '';
4861 * Get the item that is currently being dragged.
4863 * @return {OO.ui.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
4865 OO
.ui
.DraggableGroupElement
.prototype.getDragItem = function () {
4866 return this.dragItem
;
4870 * Check if an item in the group is currently being dragged.
4872 * @return {Boolean} Item is being dragged
4874 OO
.ui
.DraggableGroupElement
.prototype.isDragging = function () {
4875 return this.getDragItem() !== null;
4879 * IconElement is often mixed into other classes to generate an icon.
4880 * Icons are graphics, about the size of normal text. They are used to aid the user
4881 * in locating a control or to convey information in a space-efficient way. See the
4882 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
4883 * included in the library.
4885 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
4891 * @param {Object} [config] Configuration options
4892 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
4893 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
4894 * the icon element be set to an existing icon instead of the one generated by this class, set a
4895 * value using a jQuery selection. For example:
4897 * // Use a <div> tag instead of a <span>
4899 * // Use an existing icon element instead of the one generated by the class
4900 * $icon: this.$element
4901 * // Use an icon element from a child widget
4902 * $icon: this.childwidget.$element
4903 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
4904 * symbolic names. A map is used for i18n purposes and contains a `default` icon
4905 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
4906 * by the user's language.
4908 * Example of an i18n map:
4910 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
4911 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
4912 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
4913 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
4914 * text. The icon title is displayed when users move the mouse over the icon.
4916 OO
.ui
.IconElement
= function OoUiIconElement( config
) {
4917 // Configuration initialization
4918 config
= config
|| {};
4923 this.iconTitle
= null;
4926 this.setIcon( config
.icon
|| this.constructor.static.icon
);
4927 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
4928 this.setIconElement( config
.$icon
|| $( '<span>' ) );
4933 OO
.initClass( OO
.ui
.IconElement
);
4935 /* Static Properties */
4938 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
4939 * for i18n purposes and contains a `default` icon name and additional names keyed by
4940 * language code. The `default` name is used when no icon is keyed by the user's language.
4942 * Example of an i18n map:
4944 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
4946 * Note: the static property will be overridden if the #icon configuration is used.
4950 * @property {Object|string}
4952 OO
.ui
.IconElement
.static.icon
= null;
4955 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
4956 * function that returns title text, or `null` for no title.
4958 * The static property will be overridden if the #iconTitle configuration is used.
4962 * @property {string|Function|null}
4964 OO
.ui
.IconElement
.static.iconTitle
= null;
4969 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
4970 * applies to the specified icon element instead of the one created by the class. If an icon
4971 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
4972 * and mixin methods will no longer affect the element.
4974 * @param {jQuery} $icon Element to use as icon
4976 OO
.ui
.IconElement
.prototype.setIconElement = function ( $icon
) {
4979 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
4980 .removeAttr( 'title' );
4984 .addClass( 'oo-ui-iconElement-icon' )
4985 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
4986 if ( this.iconTitle
!== null ) {
4987 this.$icon
.attr( 'title', this.iconTitle
);
4992 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
4993 * The icon parameter can also be set to a map of icon names. See the #icon config setting
4996 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
4997 * by language code, or `null` to remove the icon.
5000 OO
.ui
.IconElement
.prototype.setIcon = function ( icon
) {
5001 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
5002 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
5004 if ( this.icon
!== icon
) {
5006 if ( this.icon
!== null ) {
5007 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
5009 if ( icon
!== null ) {
5010 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
5016 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
5017 this.updateThemeClasses();
5023 * Set the icon title. Use `null` to remove the title.
5025 * @param {string|Function|null} iconTitle A text string used as the icon title,
5026 * a function that returns title text, or `null` for no title.
5029 OO
.ui
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
5030 iconTitle
= typeof iconTitle
=== 'function' ||
5031 ( typeof iconTitle
=== 'string' && iconTitle
.length
) ?
5032 OO
.ui
.resolveMsg( iconTitle
) : null;
5034 if ( this.iconTitle
!== iconTitle
) {
5035 this.iconTitle
= iconTitle
;
5037 if ( this.iconTitle
!== null ) {
5038 this.$icon
.attr( 'title', iconTitle
);
5040 this.$icon
.removeAttr( 'title' );
5049 * Get the symbolic name of the icon.
5051 * @return {string} Icon name
5053 OO
.ui
.IconElement
.prototype.getIcon = function () {
5058 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5060 * @return {string} Icon title text
5062 OO
.ui
.IconElement
.prototype.getIconTitle = function () {
5063 return this.iconTitle
;
5067 * IndicatorElement is often mixed into other classes to generate an indicator.
5068 * Indicators are small graphics that are generally used in two ways:
5070 * - To draw attention to the status of an item. For example, an indicator might be
5071 * used to show that an item in a list has errors that need to be resolved.
5072 * - To clarify the function of a control that acts in an exceptional way (a button
5073 * that opens a menu instead of performing an action directly, for example).
5075 * For a list of indicators included in the library, please see the
5076 * [OOjs UI documentation on MediaWiki] [1].
5078 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5084 * @param {Object} [config] Configuration options
5085 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5086 * configuration is omitted, the indicator element will use a generated `<span>`.
5087 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5088 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5090 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5091 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5092 * or a function that returns title text. The indicator title is displayed when users move
5093 * the mouse over the indicator.
5095 OO
.ui
.IndicatorElement
= function OoUiIndicatorElement( config
) {
5096 // Configuration initialization
5097 config
= config
|| {};
5100 this.$indicator
= null;
5101 this.indicator
= null;
5102 this.indicatorTitle
= null;
5105 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
5106 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
5107 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
5112 OO
.initClass( OO
.ui
.IndicatorElement
);
5114 /* Static Properties */
5117 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5118 * The static property will be overridden if the #indicator configuration is used.
5122 * @property {string|null}
5124 OO
.ui
.IndicatorElement
.static.indicator
= null;
5127 * A text string used as the indicator title, a function that returns title text, or `null`
5128 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5132 * @property {string|Function|null}
5134 OO
.ui
.IndicatorElement
.static.indicatorTitle
= null;
5139 * Set the indicator element.
5141 * If an element is already set, it will be cleaned up before setting up the new element.
5143 * @param {jQuery} $indicator Element to use as indicator
5145 OO
.ui
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
5146 if ( this.$indicator
) {
5148 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
5149 .removeAttr( 'title' );
5152 this.$indicator
= $indicator
5153 .addClass( 'oo-ui-indicatorElement-indicator' )
5154 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
5155 if ( this.indicatorTitle
!== null ) {
5156 this.$indicator
.attr( 'title', this.indicatorTitle
);
5161 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5163 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5166 OO
.ui
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
5167 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
5169 if ( this.indicator
!== indicator
) {
5170 if ( this.$indicator
) {
5171 if ( this.indicator
!== null ) {
5172 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
5174 if ( indicator
!== null ) {
5175 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
5178 this.indicator
= indicator
;
5181 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
5182 this.updateThemeClasses();
5188 * Set the indicator title.
5190 * The title is displayed when a user moves the mouse over the indicator.
5192 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5193 * `null` for no indicator title
5196 OO
.ui
.IndicatorElement
.prototype.setIndicatorTitle = function ( indicatorTitle
) {
5197 indicatorTitle
= typeof indicatorTitle
=== 'function' ||
5198 ( typeof indicatorTitle
=== 'string' && indicatorTitle
.length
) ?
5199 OO
.ui
.resolveMsg( indicatorTitle
) : null;
5201 if ( this.indicatorTitle
!== indicatorTitle
) {
5202 this.indicatorTitle
= indicatorTitle
;
5203 if ( this.$indicator
) {
5204 if ( this.indicatorTitle
!== null ) {
5205 this.$indicator
.attr( 'title', indicatorTitle
);
5207 this.$indicator
.removeAttr( 'title' );
5216 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5218 * @return {string} Symbolic name of indicator
5220 OO
.ui
.IndicatorElement
.prototype.getIndicator = function () {
5221 return this.indicator
;
5225 * Get the indicator title.
5227 * The title is displayed when a user moves the mouse over the indicator.
5229 * @return {string} Indicator title text
5231 OO
.ui
.IndicatorElement
.prototype.getIndicatorTitle = function () {
5232 return this.indicatorTitle
;
5236 * LabelElement is often mixed into other classes to generate a label, which
5237 * helps identify the function of an interface element.
5238 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5240 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5246 * @param {Object} [config] Configuration options
5247 * @cfg {jQuery} [$label] The label element created by the class. If this
5248 * configuration is omitted, the label element will use a generated `<span>`.
5249 * @cfg {jQuery|string|Function} [label] The label text. The label can be specified as a plaintext string,
5250 * a jQuery selection of elements, or a function that will produce a string in the future. See the
5251 * [OOjs UI documentation on MediaWiki] [2] for examples.
5252 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5253 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5254 * The label will be truncated to fit if necessary.
5256 OO
.ui
.LabelElement
= function OoUiLabelElement( config
) {
5257 // Configuration initialization
5258 config
= config
|| {};
5263 this.autoFitLabel
= config
.autoFitLabel
=== undefined || !!config
.autoFitLabel
;
5266 this.setLabel( config
.label
|| this.constructor.static.label
);
5267 this.setLabelElement( config
.$label
|| $( '<span>' ) );
5272 OO
.initClass( OO
.ui
.LabelElement
);
5277 * @event labelChange
5278 * @param {string} value
5281 /* Static Properties */
5284 * The label text. The label can be specified as a plaintext string, a function that will
5285 * produce a string in the future, or `null` for no label. The static value will
5286 * be overridden if a label is specified with the #label config option.
5290 * @property {string|Function|null}
5292 OO
.ui
.LabelElement
.static.label
= null;
5297 * Set the label element.
5299 * If an element is already set, it will be cleaned up before setting up the new element.
5301 * @param {jQuery} $label Element to use as label
5303 OO
.ui
.LabelElement
.prototype.setLabelElement = function ( $label
) {
5304 if ( this.$label
) {
5305 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
5308 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
5309 this.setLabelContent( this.label
);
5315 * An empty string will result in the label being hidden. A string containing only whitespace will
5316 * be converted to a single ` `.
5318 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
5319 * text; or null for no label
5322 OO
.ui
.LabelElement
.prototype.setLabel = function ( label
) {
5323 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
5324 label
= ( ( typeof label
=== 'string' && label
.length
) || label
instanceof jQuery
|| label
instanceof OO
.ui
.HtmlSnippet
) ? label
: null;
5326 this.$element
.toggleClass( 'oo-ui-labelElement', !!label
);
5328 if ( this.label
!== label
) {
5329 if ( this.$label
) {
5330 this.setLabelContent( label
);
5333 this.emit( 'labelChange' );
5342 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
5343 * text; or null for no label
5345 OO
.ui
.LabelElement
.prototype.getLabel = function () {
5354 OO
.ui
.LabelElement
.prototype.fitLabel = function () {
5355 if ( this.$label
&& this.$label
.autoEllipsis
&& this.autoFitLabel
) {
5356 this.$label
.autoEllipsis( { hasSpan
: false, tooltip
: true } );
5363 * Set the content of the label.
5365 * Do not call this method until after the label element has been set by #setLabelElement.
5368 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5369 * text; or null for no label
5371 OO
.ui
.LabelElement
.prototype.setLabelContent = function ( label
) {
5372 if ( typeof label
=== 'string' ) {
5373 if ( label
.match( /^\s*$/ ) ) {
5374 // Convert whitespace only string to a single non-breaking space
5375 this.$label
.html( ' ' );
5377 this.$label
.text( label
);
5379 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
5380 this.$label
.html( label
.toString() );
5381 } else if ( label
instanceof jQuery
) {
5382 this.$label
.empty().append( label
);
5384 this.$label
.empty();
5389 * Mixin that adds a menu showing suggested values for a OO.ui.TextInputWidget.
5391 * Subclasses that set the value of #lookupInput from #onLookupMenuItemChoose should
5392 * be aware that this will cause new suggestions to be looked up for the new value. If this is
5393 * not desired, disable lookups with #setLookupsDisabled, then set the value, then re-enable lookups.
5399 * @param {Object} [config] Configuration options
5400 * @cfg {jQuery} [$overlay] Overlay for dropdown; defaults to relative positioning
5401 * @cfg {jQuery} [$container=this.$element] Element to render menu under
5402 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Whether suggestions will be requested
5403 * and shown when the user has not typed anything yet.
5405 OO
.ui
.LookupElement
= function OoUiLookupElement( config
) {
5406 // Configuration initialization
5407 config
= config
|| {};
5410 this.$overlay
= config
.$overlay
|| this.$element
;
5411 this.lookupMenu
= new OO
.ui
.TextInputMenuSelectWidget( this, {
5414 $container
: config
.$container
5417 this.allowSuggestionsWhenEmpty
= config
.allowSuggestionsWhenEmpty
|| false;
5419 this.lookupCache
= {};
5420 this.lookupQuery
= null;
5421 this.lookupRequest
= null;
5422 this.lookupsDisabled
= false;
5423 this.lookupInputFocused
= false;
5427 focus
: this.onLookupInputFocus
.bind( this ),
5428 blur
: this.onLookupInputBlur
.bind( this ),
5429 mousedown
: this.onLookupInputMouseDown
.bind( this )
5431 this.connect( this, { change
: 'onLookupInputChange' } );
5432 this.lookupMenu
.connect( this, {
5433 toggle
: 'onLookupMenuToggle',
5434 choose
: 'onLookupMenuItemChoose'
5438 this.$element
.addClass( 'oo-ui-lookupElement' );
5439 this.lookupMenu
.$element
.addClass( 'oo-ui-lookupElement-menu' );
5440 this.$overlay
.append( this.lookupMenu
.$element
);
5446 * Handle input focus event.
5448 * @param {jQuery.Event} e Input focus event
5450 OO
.ui
.LookupElement
.prototype.onLookupInputFocus = function () {
5451 this.lookupInputFocused
= true;
5452 this.populateLookupMenu();
5456 * Handle input blur event.
5458 * @param {jQuery.Event} e Input blur event
5460 OO
.ui
.LookupElement
.prototype.onLookupInputBlur = function () {
5461 this.closeLookupMenu();
5462 this.lookupInputFocused
= false;
5466 * Handle input mouse down event.
5468 * @param {jQuery.Event} e Input mouse down event
5470 OO
.ui
.LookupElement
.prototype.onLookupInputMouseDown = function () {
5471 // Only open the menu if the input was already focused.
5472 // This way we allow the user to open the menu again after closing it with Esc
5473 // by clicking in the input. Opening (and populating) the menu when initially
5474 // clicking into the input is handled by the focus handler.
5475 if ( this.lookupInputFocused
&& !this.lookupMenu
.isVisible() ) {
5476 this.populateLookupMenu();
5481 * Handle input change event.
5483 * @param {string} value New input value
5485 OO
.ui
.LookupElement
.prototype.onLookupInputChange = function () {
5486 if ( this.lookupInputFocused
) {
5487 this.populateLookupMenu();
5492 * Handle the lookup menu being shown/hidden.
5494 * @param {boolean} visible Whether the lookup menu is now visible.
5496 OO
.ui
.LookupElement
.prototype.onLookupMenuToggle = function ( visible
) {
5498 // When the menu is hidden, abort any active request and clear the menu.
5499 // This has to be done here in addition to closeLookupMenu(), because
5500 // MenuSelectWidget will close itself when the user presses Esc.
5501 this.abortLookupRequest();
5502 this.lookupMenu
.clearItems();
5507 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
5509 * @param {OO.ui.MenuOptionWidget|null} item Selected item
5511 OO
.ui
.LookupElement
.prototype.onLookupMenuItemChoose = function ( item
) {
5513 this.setValue( item
.getData() );
5520 * @return {OO.ui.TextInputMenuSelectWidget}
5522 OO
.ui
.LookupElement
.prototype.getLookupMenu = function () {
5523 return this.lookupMenu
;
5527 * Disable or re-enable lookups.
5529 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
5531 * @param {boolean} disabled Disable lookups
5533 OO
.ui
.LookupElement
.prototype.setLookupsDisabled = function ( disabled
) {
5534 this.lookupsDisabled
= !!disabled
;
5538 * Open the menu. If there are no entries in the menu, this does nothing.
5542 OO
.ui
.LookupElement
.prototype.openLookupMenu = function () {
5543 if ( !this.lookupMenu
.isEmpty() ) {
5544 this.lookupMenu
.toggle( true );
5550 * Close the menu, empty it, and abort any pending request.
5554 OO
.ui
.LookupElement
.prototype.closeLookupMenu = function () {
5555 this.lookupMenu
.toggle( false );
5556 this.abortLookupRequest();
5557 this.lookupMenu
.clearItems();
5562 * Request menu items based on the input's current value, and when they arrive,
5563 * populate the menu with these items and show the menu.
5565 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
5569 OO
.ui
.LookupElement
.prototype.populateLookupMenu = function () {
5571 value
= this.getValue();
5573 if ( this.lookupsDisabled
) {
5577 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
5578 if ( !this.allowSuggestionsWhenEmpty
&& value
=== '' ) {
5579 this.closeLookupMenu();
5580 // Skip population if there is already a request pending for the current value
5581 } else if ( value
!== this.lookupQuery
) {
5582 this.getLookupMenuItems()
5583 .done( function ( items
) {
5584 widget
.lookupMenu
.clearItems();
5585 if ( items
.length
) {
5589 widget
.initializeLookupMenuSelection();
5591 widget
.lookupMenu
.toggle( false );
5594 .fail( function () {
5595 widget
.lookupMenu
.clearItems();
5603 * Select and highlight the first selectable item in the menu.
5607 OO
.ui
.LookupElement
.prototype.initializeLookupMenuSelection = function () {
5608 if ( !this.lookupMenu
.getSelectedItem() ) {
5609 this.lookupMenu
.selectItem( this.lookupMenu
.getFirstSelectableItem() );
5611 this.lookupMenu
.highlightItem( this.lookupMenu
.getSelectedItem() );
5615 * Get lookup menu items for the current query.
5617 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
5618 * the done event. If the request was aborted to make way for a subsequent request, this promise
5619 * will not be rejected: it will remain pending forever.
5621 OO
.ui
.LookupElement
.prototype.getLookupMenuItems = function () {
5623 value
= this.getValue(),
5624 deferred
= $.Deferred(),
5627 this.abortLookupRequest();
5628 if ( Object
.prototype.hasOwnProperty
.call( this.lookupCache
, value
) ) {
5629 deferred
.resolve( this.getLookupMenuOptionsFromData( this.lookupCache
[ value
] ) );
5632 this.lookupQuery
= value
;
5633 ourRequest
= this.lookupRequest
= this.getLookupRequest();
5635 .always( function () {
5636 // We need to pop pending even if this is an old request, otherwise
5637 // the widget will remain pending forever.
5638 // TODO: this assumes that an aborted request will fail or succeed soon after
5639 // being aborted, or at least eventually. It would be nice if we could popPending()
5640 // at abort time, but only if we knew that we hadn't already called popPending()
5641 // for that request.
5642 widget
.popPending();
5644 .done( function ( data
) {
5645 // If this is an old request (and aborting it somehow caused it to still succeed),
5646 // ignore its success completely
5647 if ( ourRequest
=== widget
.lookupRequest
) {
5648 widget
.lookupQuery
= null;
5649 widget
.lookupRequest
= null;
5650 widget
.lookupCache
[ value
] = widget
.getLookupCacheDataFromResponse( data
);
5651 deferred
.resolve( widget
.getLookupMenuOptionsFromData( widget
.lookupCache
[ value
] ) );
5654 .fail( function () {
5655 // If this is an old request (or a request failing because it's being aborted),
5656 // ignore its failure completely
5657 if ( ourRequest
=== widget
.lookupRequest
) {
5658 widget
.lookupQuery
= null;
5659 widget
.lookupRequest
= null;
5664 return deferred
.promise();
5668 * Abort the currently pending lookup request, if any.
5670 OO
.ui
.LookupElement
.prototype.abortLookupRequest = function () {
5671 var oldRequest
= this.lookupRequest
;
5673 // First unset this.lookupRequest to the fail handler will notice
5674 // that the request is no longer current
5675 this.lookupRequest
= null;
5676 this.lookupQuery
= null;
5682 * Get a new request object of the current lookup query value.
5685 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
5687 OO
.ui
.LookupElement
.prototype.getLookupRequest = function () {
5688 // Stub, implemented in subclass
5693 * Pre-process data returned by the request from #getLookupRequest.
5695 * The return value of this function will be cached, and any further queries for the given value
5696 * will use the cache rather than doing API requests.
5699 * @param {Mixed} data Response from server
5700 * @return {Mixed} Cached result data
5702 OO
.ui
.LookupElement
.prototype.getLookupCacheDataFromResponse = function () {
5703 // Stub, implemented in subclass
5708 * Get a list of menu option widgets from the (possibly cached) data returned by
5709 * #getLookupCacheDataFromResponse.
5712 * @param {Mixed} data Cached result data, usually an array
5713 * @return {OO.ui.MenuOptionWidget[]} Menu items
5715 OO
.ui
.LookupElement
.prototype.getLookupMenuOptionsFromData = function () {
5716 // Stub, implemented in subclass
5721 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5722 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5723 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5724 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5730 * @param {Object} [config] Configuration options
5731 * @cfg {Object} [popup] Configuration to pass to popup
5732 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5734 OO
.ui
.PopupElement
= function OoUiPopupElement( config
) {
5735 // Configuration initialization
5736 config
= config
|| {};
5739 this.popup
= new OO
.ui
.PopupWidget( $.extend(
5740 { autoClose
: true },
5742 { $autoCloseIgnore
: this.$element
}
5751 * @return {OO.ui.PopupWidget} Popup widget
5753 OO
.ui
.PopupElement
.prototype.getPopup = function () {
5758 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
5759 * additional functionality to an element created by another class. The class provides
5760 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
5761 * which are used to customize the look and feel of a widget to better describe its
5762 * importance and functionality.
5764 * The library currently contains the following styling flags for general use:
5766 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
5767 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
5768 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
5770 * The flags affect the appearance of the buttons:
5773 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
5774 * var button1 = new OO.ui.ButtonWidget( {
5775 * label: 'Constructive',
5776 * flags: 'constructive'
5778 * var button2 = new OO.ui.ButtonWidget( {
5779 * label: 'Destructive',
5780 * flags: 'destructive'
5782 * var button3 = new OO.ui.ButtonWidget( {
5783 * label: 'Progressive',
5784 * flags: 'progressive'
5786 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
5788 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
5789 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
5791 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
5797 * @param {Object} [config] Configuration options
5798 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
5799 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
5800 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
5801 * @cfg {jQuery} [$flagged] The flagged element. By default,
5802 * the flagged functionality is applied to the element created by the class ($element).
5803 * If a different element is specified, the flagged functionality will be applied to it instead.
5805 OO
.ui
.FlaggedElement
= function OoUiFlaggedElement( config
) {
5806 // Configuration initialization
5807 config
= config
|| {};
5811 this.$flagged
= null;
5814 this.setFlags( config
.flags
);
5815 this.setFlaggedElement( config
.$flagged
|| this.$element
);
5822 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
5823 * parameter contains the name of each modified flag and indicates whether it was
5826 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
5827 * that the flag was added, `false` that the flag was removed.
5833 * Set the flagged element.
5835 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
5836 * If an element is already set, the method will remove the mixin’s effect on that element.
5838 * @param {jQuery} $flagged Element that should be flagged
5840 OO
.ui
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
5841 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
5842 return 'oo-ui-flaggedElement-' + flag
;
5845 if ( this.$flagged
) {
5846 this.$flagged
.removeClass( classNames
);
5849 this.$flagged
= $flagged
.addClass( classNames
);
5853 * Check if the specified flag is set.
5855 * @param {string} flag Name of flag
5856 * @return {boolean} The flag is set
5858 OO
.ui
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
5859 return flag
in this.flags
;
5863 * Get the names of all flags set.
5865 * @return {string[]} Flag names
5867 OO
.ui
.FlaggedElement
.prototype.getFlags = function () {
5868 return Object
.keys( this.flags
);
5877 OO
.ui
.FlaggedElement
.prototype.clearFlags = function () {
5878 var flag
, className
,
5881 classPrefix
= 'oo-ui-flaggedElement-';
5883 for ( flag
in this.flags
) {
5884 className
= classPrefix
+ flag
;
5885 changes
[ flag
] = false;
5886 delete this.flags
[ flag
];
5887 remove
.push( className
);
5890 if ( this.$flagged
) {
5891 this.$flagged
.removeClass( remove
.join( ' ' ) );
5894 this.updateThemeClasses();
5895 this.emit( 'flag', changes
);
5901 * Add one or more flags.
5903 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
5904 * or an object keyed by flag name with a boolean value that indicates whether the flag should
5905 * be added (`true`) or removed (`false`).
5909 OO
.ui
.FlaggedElement
.prototype.setFlags = function ( flags
) {
5910 var i
, len
, flag
, className
,
5914 classPrefix
= 'oo-ui-flaggedElement-';
5916 if ( typeof flags
=== 'string' ) {
5917 className
= classPrefix
+ flags
;
5919 if ( !this.flags
[ flags
] ) {
5920 this.flags
[ flags
] = true;
5921 add
.push( className
);
5923 } else if ( Array
.isArray( flags
) ) {
5924 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
5926 className
= classPrefix
+ flag
;
5928 if ( !this.flags
[ flag
] ) {
5929 changes
[ flag
] = true;
5930 this.flags
[ flag
] = true;
5931 add
.push( className
);
5934 } else if ( OO
.isPlainObject( flags
) ) {
5935 for ( flag
in flags
) {
5936 className
= classPrefix
+ flag
;
5937 if ( flags
[ flag
] ) {
5939 if ( !this.flags
[ flag
] ) {
5940 changes
[ flag
] = true;
5941 this.flags
[ flag
] = true;
5942 add
.push( className
);
5946 if ( this.flags
[ flag
] ) {
5947 changes
[ flag
] = false;
5948 delete this.flags
[ flag
];
5949 remove
.push( className
);
5955 if ( this.$flagged
) {
5957 .addClass( add
.join( ' ' ) )
5958 .removeClass( remove
.join( ' ' ) );
5961 this.updateThemeClasses();
5962 this.emit( 'flag', changes
);
5968 * TitledElement is mixed into other classes to provide a `title` attribute.
5969 * Titles are rendered by the browser and are made visible when the user moves
5970 * the mouse over the element. Titles are not visible on touch devices.
5973 * // TitledElement provides a 'title' attribute to the
5974 * // ButtonWidget class
5975 * var button = new OO.ui.ButtonWidget( {
5976 * label: 'Button with Title',
5977 * title: 'I am a button'
5979 * $( 'body' ).append( button.$element );
5985 * @param {Object} [config] Configuration options
5986 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
5987 * If this config is omitted, the title functionality is applied to $element, the
5988 * element created by the class.
5989 * @cfg {string|Function} [title] The title text or a function that returns text. If
5990 * this config is omitted, the value of the {@link #static-title static title} property is used.
5992 OO
.ui
.TitledElement
= function OoUiTitledElement( config
) {
5993 // Configuration initialization
5994 config
= config
|| {};
5997 this.$titled
= null;
6001 this.setTitle( config
.title
|| this.constructor.static.title
);
6002 this.setTitledElement( config
.$titled
|| this.$element
);
6007 OO
.initClass( OO
.ui
.TitledElement
);
6009 /* Static Properties */
6012 * The title text, a function that returns text, or `null` for no title. The value of the static property
6013 * is overridden if the #title config option is used.
6017 * @property {string|Function|null}
6019 OO
.ui
.TitledElement
.static.title
= null;
6024 * Set the titled element.
6026 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6027 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6029 * @param {jQuery} $titled Element that should use the 'titled' functionality
6031 OO
.ui
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
6032 if ( this.$titled
) {
6033 this.$titled
.removeAttr( 'title' );
6036 this.$titled
= $titled
;
6038 this.$titled
.attr( 'title', this.title
);
6045 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6048 OO
.ui
.TitledElement
.prototype.setTitle = function ( title
) {
6049 title
= typeof title
=== 'string' ? OO
.ui
.resolveMsg( title
) : null;
6051 if ( this.title
!== title
) {
6052 if ( this.$titled
) {
6053 if ( title
!== null ) {
6054 this.$titled
.attr( 'title', title
);
6056 this.$titled
.removeAttr( 'title' );
6068 * @return {string} Title string
6070 OO
.ui
.TitledElement
.prototype.getTitle = function () {
6075 * Element that can be automatically clipped to visible boundaries.
6077 * Whenever the element's natural height changes, you have to call
6078 * #clip to make sure it's still clipping correctly.
6084 * @param {Object} [config] Configuration options
6085 * @cfg {jQuery} [$clippable] Nodes to clip, assigned to #$clippable, omit to use #$element
6087 OO
.ui
.ClippableElement
= function OoUiClippableElement( config
) {
6088 // Configuration initialization
6089 config
= config
|| {};
6092 this.$clippable
= null;
6093 this.clipping
= false;
6094 this.clippedHorizontally
= false;
6095 this.clippedVertically
= false;
6096 this.$clippableContainer
= null;
6097 this.$clippableScroller
= null;
6098 this.$clippableWindow
= null;
6099 this.idealWidth
= null;
6100 this.idealHeight
= null;
6101 this.onClippableContainerScrollHandler
= this.clip
.bind( this );
6102 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
6105 this.setClippableElement( config
.$clippable
|| this.$element
);
6111 * Set clippable element.
6113 * If an element is already set, it will be cleaned up before setting up the new element.
6115 * @param {jQuery} $clippable Element to make clippable
6117 OO
.ui
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
6118 if ( this.$clippable
) {
6119 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
6120 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
6121 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6124 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
6131 * Do not turn clipping on until after the element is attached to the DOM and visible.
6133 * @param {boolean} [clipping] Enable clipping, omit to toggle
6136 OO
.ui
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
6137 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
6139 if ( this.clipping
!== clipping
) {
6140 this.clipping
= clipping
;
6142 this.$clippableContainer
= $( this.getClosestScrollableElementContainer() );
6143 // If the clippable container is the root, we have to listen to scroll events and check
6144 // jQuery.scrollTop on the window because of browser inconsistencies
6145 this.$clippableScroller
= this.$clippableContainer
.is( 'html, body' ) ?
6146 $( OO
.ui
.Element
.static.getWindow( this.$clippableContainer
) ) :
6147 this.$clippableContainer
;
6148 this.$clippableScroller
.on( 'scroll', this.onClippableContainerScrollHandler
);
6149 this.$clippableWindow
= $( this.getElementWindow() )
6150 .on( 'resize', this.onClippableWindowResizeHandler
);
6151 // Initial clip after visible
6154 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
6155 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6157 this.$clippableContainer
= null;
6158 this.$clippableScroller
.off( 'scroll', this.onClippableContainerScrollHandler
);
6159 this.$clippableScroller
= null;
6160 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
6161 this.$clippableWindow
= null;
6169 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6171 * @return {boolean} Element will be clipped to the visible area
6173 OO
.ui
.ClippableElement
.prototype.isClipping = function () {
6174 return this.clipping
;
6178 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6180 * @return {boolean} Part of the element is being clipped
6182 OO
.ui
.ClippableElement
.prototype.isClipped = function () {
6183 return this.clippedHorizontally
|| this.clippedVertically
;
6187 * Check if the right of the element is being clipped by the nearest scrollable container.
6189 * @return {boolean} Part of the element is being clipped
6191 OO
.ui
.ClippableElement
.prototype.isClippedHorizontally = function () {
6192 return this.clippedHorizontally
;
6196 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6198 * @return {boolean} Part of the element is being clipped
6200 OO
.ui
.ClippableElement
.prototype.isClippedVertically = function () {
6201 return this.clippedVertically
;
6205 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6207 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6208 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6210 OO
.ui
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
6211 this.idealWidth
= width
;
6212 this.idealHeight
= height
;
6214 if ( !this.clipping
) {
6215 // Update dimensions
6216 this.$clippable
.css( { width
: width
, height
: height
} );
6218 // While clipping, idealWidth and idealHeight are not considered
6222 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6223 * the element's natural height changes.
6225 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6226 * overlapped by, the visible area of the nearest scrollable container.
6230 OO
.ui
.ClippableElement
.prototype.clip = function () {
6231 if ( !this.clipping
) {
6232 // this.$clippableContainer and this.$clippableWindow are null, so the below will fail
6236 var buffer
= 7, // Chosen by fair dice roll
6237 cOffset
= this.$clippable
.offset(),
6238 $container
= this.$clippableContainer
.is( 'html, body' ) ?
6239 this.$clippableWindow
: this.$clippableContainer
,
6240 ccOffset
= $container
.offset() || { top
: 0, left
: 0 },
6241 ccHeight
= $container
.innerHeight() - buffer
,
6242 ccWidth
= $container
.innerWidth() - buffer
,
6243 cHeight
= this.$clippable
.outerHeight() + buffer
,
6244 cWidth
= this.$clippable
.outerWidth() + buffer
,
6245 scrollTop
= this.$clippableScroller
.scrollTop(),
6246 scrollLeft
= this.$clippableScroller
.scrollLeft(),
6247 desiredWidth
= cOffset
.left
< 0 ?
6248 cWidth
+ cOffset
.left
:
6249 ( ccOffset
.left
+ scrollLeft
+ ccWidth
) - cOffset
.left
,
6250 desiredHeight
= cOffset
.top
< 0 ?
6251 cHeight
+ cOffset
.top
:
6252 ( ccOffset
.top
+ scrollTop
+ ccHeight
) - cOffset
.top
,
6253 naturalWidth
= this.$clippable
.prop( 'scrollWidth' ),
6254 naturalHeight
= this.$clippable
.prop( 'scrollHeight' ),
6255 clipWidth
= desiredWidth
< naturalWidth
,
6256 clipHeight
= desiredHeight
< naturalHeight
;
6259 this.$clippable
.css( { overflowX
: 'scroll', width
: desiredWidth
} );
6261 this.$clippable
.css( { width
: this.idealWidth
|| '', overflowX
: '' } );
6264 this.$clippable
.css( { overflowY
: 'scroll', height
: desiredHeight
} );
6266 this.$clippable
.css( { height
: this.idealHeight
|| '', overflowY
: '' } );
6269 // If we stopped clipping in at least one of the dimensions
6270 if ( !clipWidth
|| !clipHeight
) {
6271 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6274 this.clippedHorizontally
= clipWidth
;
6275 this.clippedVertically
= clipHeight
;
6281 * Generic toolbar tool.
6285 * @extends OO.ui.Widget
6286 * @mixins OO.ui.IconElement
6287 * @mixins OO.ui.FlaggedElement
6290 * @param {OO.ui.ToolGroup} toolGroup
6291 * @param {Object} [config] Configuration options
6292 * @cfg {string|Function} [title] Title text or a function that returns text
6294 OO
.ui
.Tool
= function OoUiTool( toolGroup
, config
) {
6295 // Allow passing positional parameters inside the config object
6296 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
6298 toolGroup
= config
.toolGroup
;
6301 // Configuration initialization
6302 config
= config
|| {};
6304 // Parent constructor
6305 OO
.ui
.Tool
.super.call( this, config
);
6307 // Mixin constructors
6308 OO
.ui
.IconElement
.call( this, config
);
6309 OO
.ui
.FlaggedElement
.call( this, config
);
6312 this.toolGroup
= toolGroup
;
6313 this.toolbar
= this.toolGroup
.getToolbar();
6314 this.active
= false;
6315 this.$title
= $( '<span>' );
6316 this.$accel
= $( '<span>' );
6317 this.$link
= $( '<a>' );
6321 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
6324 this.$title
.addClass( 'oo-ui-tool-title' );
6326 .addClass( 'oo-ui-tool-accel' )
6328 // This may need to be changed if the key names are ever localized,
6329 // but for now they are essentially written in English
6334 .addClass( 'oo-ui-tool-link' )
6335 .append( this.$icon
, this.$title
, this.$accel
)
6336 .prop( 'tabIndex', 0 )
6337 .attr( 'role', 'button' );
6339 .data( 'oo-ui-tool', this )
6341 'oo-ui-tool ' + 'oo-ui-tool-name-' +
6342 this.constructor.static.name
.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
6344 .append( this.$link
);
6345 this.setTitle( config
.title
|| this.constructor.static.title
);
6350 OO
.inheritClass( OO
.ui
.Tool
, OO
.ui
.Widget
);
6351 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.IconElement
);
6352 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.FlaggedElement
);
6360 /* Static Properties */
6366 OO
.ui
.Tool
.static.tagName
= 'span';
6369 * Symbolic name of tool.
6374 * @property {string}
6376 OO
.ui
.Tool
.static.name
= '';
6384 * @property {string}
6386 OO
.ui
.Tool
.static.group
= '';
6391 * Title is used as a tooltip when the tool is part of a bar tool group, or a label when the tool
6392 * is part of a list or menu tool group. If a trigger is associated with an action by the same name
6393 * as the tool, a description of its keyboard shortcut for the appropriate platform will be
6394 * appended to the title if the tool is part of a bar tool group.
6399 * @property {string|Function} Title text or a function that returns text
6401 OO
.ui
.Tool
.static.title
= '';
6404 * Tool can be automatically added to catch-all groups.
6408 * @property {boolean}
6410 OO
.ui
.Tool
.static.autoAddToCatchall
= true;
6413 * Tool can be automatically added to named groups.
6416 * @property {boolean}
6419 OO
.ui
.Tool
.static.autoAddToGroup
= true;
6422 * Check if this tool is compatible with given data.
6426 * @param {Mixed} data Data to check
6427 * @return {boolean} Tool can be used with data
6429 OO
.ui
.Tool
.static.isCompatibleWith = function () {
6436 * Handle the toolbar state being updated.
6438 * This is an abstract method that must be overridden in a concrete subclass.
6442 OO
.ui
.Tool
.prototype.onUpdateState = function () {
6444 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
6449 * Handle the tool being selected.
6451 * This is an abstract method that must be overridden in a concrete subclass.
6455 OO
.ui
.Tool
.prototype.onSelect = function () {
6457 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
6462 * Check if the button is active.
6464 * @return {boolean} Button is active
6466 OO
.ui
.Tool
.prototype.isActive = function () {
6471 * Make the button appear active or inactive.
6473 * @param {boolean} state Make button appear active
6475 OO
.ui
.Tool
.prototype.setActive = function ( state
) {
6476 this.active
= !!state
;
6477 if ( this.active
) {
6478 this.$element
.addClass( 'oo-ui-tool-active' );
6480 this.$element
.removeClass( 'oo-ui-tool-active' );
6485 * Get the tool title.
6487 * @param {string|Function} title Title text or a function that returns text
6490 OO
.ui
.Tool
.prototype.setTitle = function ( title
) {
6491 this.title
= OO
.ui
.resolveMsg( title
);
6497 * Get the tool title.
6499 * @return {string} Title text
6501 OO
.ui
.Tool
.prototype.getTitle = function () {
6506 * Get the tool's symbolic name.
6508 * @return {string} Symbolic name of tool
6510 OO
.ui
.Tool
.prototype.getName = function () {
6511 return this.constructor.static.name
;
6517 OO
.ui
.Tool
.prototype.updateTitle = function () {
6518 var titleTooltips
= this.toolGroup
.constructor.static.titleTooltips
,
6519 accelTooltips
= this.toolGroup
.constructor.static.accelTooltips
,
6520 accel
= this.toolbar
.getToolAccelerator( this.constructor.static.name
),
6523 this.$title
.text( this.title
);
6524 this.$accel
.text( accel
);
6526 if ( titleTooltips
&& typeof this.title
=== 'string' && this.title
.length
) {
6527 tooltipParts
.push( this.title
);
6529 if ( accelTooltips
&& typeof accel
=== 'string' && accel
.length
) {
6530 tooltipParts
.push( accel
);
6532 if ( tooltipParts
.length
) {
6533 this.$link
.attr( 'title', tooltipParts
.join( ' ' ) );
6535 this.$link
.removeAttr( 'title' );
6542 OO
.ui
.Tool
.prototype.destroy = function () {
6543 this.toolbar
.disconnect( this );
6544 this.$element
.remove();
6548 * Collection of tool groups.
6551 * @extends OO.ui.Element
6552 * @mixins OO.EventEmitter
6553 * @mixins OO.ui.GroupElement
6556 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
6557 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating tool groups
6558 * @param {Object} [config] Configuration options
6559 * @cfg {boolean} [actions] Add an actions section opposite to the tools
6560 * @cfg {boolean} [shadow] Add a shadow below the toolbar
6562 OO
.ui
.Toolbar
= function OoUiToolbar( toolFactory
, toolGroupFactory
, config
) {
6563 // Allow passing positional parameters inside the config object
6564 if ( OO
.isPlainObject( toolFactory
) && config
=== undefined ) {
6565 config
= toolFactory
;
6566 toolFactory
= config
.toolFactory
;
6567 toolGroupFactory
= config
.toolGroupFactory
;
6570 // Configuration initialization
6571 config
= config
|| {};
6573 // Parent constructor
6574 OO
.ui
.Toolbar
.super.call( this, config
);
6576 // Mixin constructors
6577 OO
.EventEmitter
.call( this );
6578 OO
.ui
.GroupElement
.call( this, config
);
6581 this.toolFactory
= toolFactory
;
6582 this.toolGroupFactory
= toolGroupFactory
;
6585 this.$bar
= $( '<div>' );
6586 this.$actions
= $( '<div>' );
6587 this.initialized
= false;
6588 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
6592 .add( this.$bar
).add( this.$group
).add( this.$actions
)
6593 .on( 'mousedown', this.onPointerDown
.bind( this ) );
6596 this.$group
.addClass( 'oo-ui-toolbar-tools' );
6597 if ( config
.actions
) {
6598 this.$bar
.append( this.$actions
.addClass( 'oo-ui-toolbar-actions' ) );
6601 .addClass( 'oo-ui-toolbar-bar' )
6602 .append( this.$group
, '<div style="clear:both"></div>' );
6603 if ( config
.shadow
) {
6604 this.$bar
.append( '<div class="oo-ui-toolbar-shadow"></div>' );
6606 this.$element
.addClass( 'oo-ui-toolbar' ).append( this.$bar
);
6611 OO
.inheritClass( OO
.ui
.Toolbar
, OO
.ui
.Element
);
6612 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.EventEmitter
);
6613 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.ui
.GroupElement
);
6618 * Get the tool factory.
6620 * @return {OO.ui.ToolFactory} Tool factory
6622 OO
.ui
.Toolbar
.prototype.getToolFactory = function () {
6623 return this.toolFactory
;
6627 * Get the tool group factory.
6629 * @return {OO.Factory} Tool group factory
6631 OO
.ui
.Toolbar
.prototype.getToolGroupFactory = function () {
6632 return this.toolGroupFactory
;
6636 * Handles mouse down events.
6638 * @param {jQuery.Event} e Mouse down event
6640 OO
.ui
.Toolbar
.prototype.onPointerDown = function ( e
) {
6641 var $closestWidgetToEvent
= $( e
.target
).closest( '.oo-ui-widget' ),
6642 $closestWidgetToToolbar
= this.$element
.closest( '.oo-ui-widget' );
6643 if ( !$closestWidgetToEvent
.length
|| $closestWidgetToEvent
[ 0 ] === $closestWidgetToToolbar
[ 0 ] ) {
6649 * Handle window resize event.
6652 * @param {jQuery.Event} e Window resize event
6654 OO
.ui
.Toolbar
.prototype.onWindowResize = function () {
6655 this.$element
.toggleClass(
6656 'oo-ui-toolbar-narrow',
6657 this.$bar
.width() <= this.narrowThreshold
6662 * Sets up handles and preloads required information for the toolbar to work.
6663 * This must be called after it is attached to a visible document and before doing anything else.
6665 OO
.ui
.Toolbar
.prototype.initialize = function () {
6666 this.initialized
= true;
6667 this.narrowThreshold
= this.$group
.width() + this.$actions
.width();
6668 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler
);
6669 this.onWindowResize();
6675 * Tools can be specified in the following ways:
6677 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
6678 * - All tools in a group: `{ group: 'group-name' }`
6679 * - All tools: `'*'` - Using this will make the group a list with a "More" label by default
6681 * @param {Object.<string,Array>} groups List of tool group configurations
6682 * @param {Array|string} [groups.include] Tools to include
6683 * @param {Array|string} [groups.exclude] Tools to exclude
6684 * @param {Array|string} [groups.promote] Tools to promote to the beginning
6685 * @param {Array|string} [groups.demote] Tools to demote to the end
6687 OO
.ui
.Toolbar
.prototype.setup = function ( groups
) {
6688 var i
, len
, type
, group
,
6690 defaultType
= 'bar';
6692 // Cleanup previous groups
6695 // Build out new groups
6696 for ( i
= 0, len
= groups
.length
; i
< len
; i
++ ) {
6697 group
= groups
[ i
];
6698 if ( group
.include
=== '*' ) {
6699 // Apply defaults to catch-all groups
6700 if ( group
.type
=== undefined ) {
6701 group
.type
= 'list';
6703 if ( group
.label
=== undefined ) {
6704 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
6707 // Check type has been registered
6708 type
= this.getToolGroupFactory().lookup( group
.type
) ? group
.type
: defaultType
;
6710 this.getToolGroupFactory().create( type
, this, group
)
6713 this.addItems( items
);
6717 * Remove all tools and groups from the toolbar.
6719 OO
.ui
.Toolbar
.prototype.reset = function () {
6724 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6725 this.items
[ i
].destroy();
6731 * Destroys toolbar, removing event handlers and DOM elements.
6733 * Call this whenever you are done using a toolbar.
6735 OO
.ui
.Toolbar
.prototype.destroy = function () {
6736 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler
);
6738 this.$element
.remove();
6742 * Check if tool has not been used yet.
6744 * @param {string} name Symbolic name of tool
6745 * @return {boolean} Tool is available
6747 OO
.ui
.Toolbar
.prototype.isToolAvailable = function ( name
) {
6748 return !this.tools
[ name
];
6752 * Prevent tool from being used again.
6754 * @param {OO.ui.Tool} tool Tool to reserve
6756 OO
.ui
.Toolbar
.prototype.reserveTool = function ( tool
) {
6757 this.tools
[ tool
.getName() ] = tool
;
6761 * Allow tool to be used again.
6763 * @param {OO.ui.Tool} tool Tool to release
6765 OO
.ui
.Toolbar
.prototype.releaseTool = function ( tool
) {
6766 delete this.tools
[ tool
.getName() ];
6770 * Get accelerator label for tool.
6772 * This is a stub that should be overridden to provide access to accelerator information.
6774 * @param {string} name Symbolic name of tool
6775 * @return {string|undefined} Tool accelerator label if available
6777 OO
.ui
.Toolbar
.prototype.getToolAccelerator = function () {
6782 * Collection of tools.
6784 * Tools can be specified in the following ways:
6786 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
6787 * - All tools in a group: `{ group: 'group-name' }`
6788 * - All tools: `'*'`
6792 * @extends OO.ui.Widget
6793 * @mixins OO.ui.GroupElement
6796 * @param {OO.ui.Toolbar} toolbar
6797 * @param {Object} [config] Configuration options
6798 * @cfg {Array|string} [include=[]] List of tools to include
6799 * @cfg {Array|string} [exclude=[]] List of tools to exclude
6800 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning
6801 * @cfg {Array|string} [demote=[]] List of tools to demote to the end
6803 OO
.ui
.ToolGroup
= function OoUiToolGroup( toolbar
, config
) {
6804 // Allow passing positional parameters inside the config object
6805 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
6807 toolbar
= config
.toolbar
;
6810 // Configuration initialization
6811 config
= config
|| {};
6813 // Parent constructor
6814 OO
.ui
.ToolGroup
.super.call( this, config
);
6816 // Mixin constructors
6817 OO
.ui
.GroupElement
.call( this, config
);
6820 this.toolbar
= toolbar
;
6822 this.pressed
= null;
6823 this.autoDisabled
= false;
6824 this.include
= config
.include
|| [];
6825 this.exclude
= config
.exclude
|| [];
6826 this.promote
= config
.promote
|| [];
6827 this.demote
= config
.demote
|| [];
6828 this.onCapturedMouseUpHandler
= this.onCapturedMouseUp
.bind( this );
6832 mousedown
: this.onPointerDown
.bind( this ),
6833 mouseup
: this.onPointerUp
.bind( this ),
6834 mouseover
: this.onMouseOver
.bind( this ),
6835 mouseout
: this.onMouseOut
.bind( this )
6837 this.toolbar
.getToolFactory().connect( this, { register
: 'onToolFactoryRegister' } );
6838 this.aggregate( { disable
: 'itemDisable' } );
6839 this.connect( this, { itemDisable
: 'updateDisabled' } );
6842 this.$group
.addClass( 'oo-ui-toolGroup-tools' );
6844 .addClass( 'oo-ui-toolGroup' )
6845 .append( this.$group
);
6851 OO
.inheritClass( OO
.ui
.ToolGroup
, OO
.ui
.Widget
);
6852 OO
.mixinClass( OO
.ui
.ToolGroup
, OO
.ui
.GroupElement
);
6860 /* Static Properties */
6863 * Show labels in tooltips.
6867 * @property {boolean}
6869 OO
.ui
.ToolGroup
.static.titleTooltips
= false;
6872 * Show acceleration labels in tooltips.
6876 * @property {boolean}
6878 OO
.ui
.ToolGroup
.static.accelTooltips
= false;
6881 * Automatically disable the toolgroup when all tools are disabled
6885 * @property {boolean}
6887 OO
.ui
.ToolGroup
.static.autoDisable
= true;
6894 OO
.ui
.ToolGroup
.prototype.isDisabled = function () {
6895 return this.autoDisabled
|| OO
.ui
.ToolGroup
.super.prototype.isDisabled
.apply( this, arguments
);
6901 OO
.ui
.ToolGroup
.prototype.updateDisabled = function () {
6902 var i
, item
, allDisabled
= true;
6904 if ( this.constructor.static.autoDisable
) {
6905 for ( i
= this.items
.length
- 1; i
>= 0; i
-- ) {
6906 item
= this.items
[ i
];
6907 if ( !item
.isDisabled() ) {
6908 allDisabled
= false;
6912 this.autoDisabled
= allDisabled
;
6914 OO
.ui
.ToolGroup
.super.prototype.updateDisabled
.apply( this, arguments
);
6918 * Handle mouse down events.
6920 * @param {jQuery.Event} e Mouse down event
6922 OO
.ui
.ToolGroup
.prototype.onPointerDown = function ( e
) {
6923 if ( !this.isDisabled() && e
.which
=== 1 ) {
6924 this.pressed
= this.getTargetTool( e
);
6925 if ( this.pressed
) {
6926 this.pressed
.setActive( true );
6927 this.getElementDocument().addEventListener(
6928 'mouseup', this.onCapturedMouseUpHandler
, true
6936 * Handle captured mouse up events.
6938 * @param {Event} e Mouse up event
6940 OO
.ui
.ToolGroup
.prototype.onCapturedMouseUp = function ( e
) {
6941 this.getElementDocument().removeEventListener( 'mouseup', this.onCapturedMouseUpHandler
, true );
6942 // onPointerUp may be called a second time, depending on where the mouse is when the button is
6943 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
6944 this.onPointerUp( e
);
6948 * Handle mouse up events.
6950 * @param {jQuery.Event} e Mouse up event
6952 OO
.ui
.ToolGroup
.prototype.onPointerUp = function ( e
) {
6953 var tool
= this.getTargetTool( e
);
6955 if ( !this.isDisabled() && e
.which
=== 1 && this.pressed
&& this.pressed
=== tool
) {
6956 this.pressed
.onSelect();
6959 this.pressed
= null;
6964 * Handle mouse over events.
6966 * @param {jQuery.Event} e Mouse over event
6968 OO
.ui
.ToolGroup
.prototype.onMouseOver = function ( e
) {
6969 var tool
= this.getTargetTool( e
);
6971 if ( this.pressed
&& this.pressed
=== tool
) {
6972 this.pressed
.setActive( true );
6977 * Handle mouse out events.
6979 * @param {jQuery.Event} e Mouse out event
6981 OO
.ui
.ToolGroup
.prototype.onMouseOut = function ( e
) {
6982 var tool
= this.getTargetTool( e
);
6984 if ( this.pressed
&& this.pressed
=== tool
) {
6985 this.pressed
.setActive( false );
6990 * Get the closest tool to a jQuery.Event.
6992 * Only tool links are considered, which prevents other elements in the tool such as popups from
6993 * triggering tool group interactions.
6996 * @param {jQuery.Event} e
6997 * @return {OO.ui.Tool|null} Tool, `null` if none was found
6999 OO
.ui
.ToolGroup
.prototype.getTargetTool = function ( e
) {
7001 $item
= $( e
.target
).closest( '.oo-ui-tool-link' );
7003 if ( $item
.length
) {
7004 tool
= $item
.parent().data( 'oo-ui-tool' );
7007 return tool
&& !tool
.isDisabled() ? tool
: null;
7011 * Handle tool registry register events.
7013 * If a tool is registered after the group is created, we must repopulate the list to account for:
7015 * - a tool being added that may be included
7016 * - a tool already included being overridden
7018 * @param {string} name Symbolic name of tool
7020 OO
.ui
.ToolGroup
.prototype.onToolFactoryRegister = function () {
7025 * Get the toolbar this group is in.
7027 * @return {OO.ui.Toolbar} Toolbar of group
7029 OO
.ui
.ToolGroup
.prototype.getToolbar = function () {
7030 return this.toolbar
;
7034 * Add and remove tools based on configuration.
7036 OO
.ui
.ToolGroup
.prototype.populate = function () {
7037 var i
, len
, name
, tool
,
7038 toolFactory
= this.toolbar
.getToolFactory(),
7042 list
= this.toolbar
.getToolFactory().getTools(
7043 this.include
, this.exclude
, this.promote
, this.demote
7046 // Build a list of needed tools
7047 for ( i
= 0, len
= list
.length
; i
< len
; i
++ ) {
7051 toolFactory
.lookup( name
) &&
7052 // Tool is available or is already in this group
7053 ( this.toolbar
.isToolAvailable( name
) || this.tools
[ name
] )
7055 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
7056 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
7057 this.toolbar
.tools
[ name
] = true;
7058 tool
= this.tools
[ name
];
7060 // Auto-initialize tools on first use
7061 this.tools
[ name
] = tool
= toolFactory
.create( name
, this );
7064 this.toolbar
.reserveTool( tool
);
7066 names
[ name
] = true;
7069 // Remove tools that are no longer needed
7070 for ( name
in this.tools
) {
7071 if ( !names
[ name
] ) {
7072 this.tools
[ name
].destroy();
7073 this.toolbar
.releaseTool( this.tools
[ name
] );
7074 remove
.push( this.tools
[ name
] );
7075 delete this.tools
[ name
];
7078 if ( remove
.length
) {
7079 this.removeItems( remove
);
7081 // Update emptiness state
7083 this.$element
.removeClass( 'oo-ui-toolGroup-empty' );
7085 this.$element
.addClass( 'oo-ui-toolGroup-empty' );
7087 // Re-add tools (moving existing ones to new locations)
7088 this.addItems( add
);
7089 // Disabled state may depend on items
7090 this.updateDisabled();
7094 * Destroy tool group.
7096 OO
.ui
.ToolGroup
.prototype.destroy = function () {
7100 this.toolbar
.getToolFactory().disconnect( this );
7101 for ( name
in this.tools
) {
7102 this.toolbar
.releaseTool( this.tools
[ name
] );
7103 this.tools
[ name
].disconnect( this ).destroy();
7104 delete this.tools
[ name
];
7106 this.$element
.remove();
7110 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
7111 * consists of a header that contains the dialog title, a body with the message, and a footer that
7112 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
7113 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
7115 * There are two basic types of message dialogs, confirmation and alert:
7117 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
7118 * more details about the consequences.
7119 * - **alert**: the dialog title describes which event occurred and the message provides more information
7120 * about why the event occurred.
7122 * The MessageDialog class specifies two actions: ‘accept’, the primary
7123 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
7124 * passing along the selected action.
7126 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
7129 * // Example: Creating and opening a message dialog window.
7130 * var messageDialog = new OO.ui.MessageDialog();
7132 * // Create and append a window manager.
7133 * var windowManager = new OO.ui.WindowManager();
7134 * $( 'body' ).append( windowManager.$element );
7135 * windowManager.addWindows( [ messageDialog ] );
7136 * // Open the window.
7137 * windowManager.openWindow( messageDialog, {
7138 * title: 'Basic message dialog',
7139 * message: 'This is the message'
7142 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
7145 * @extends OO.ui.Dialog
7148 * @param {Object} [config] Configuration options
7150 OO
.ui
.MessageDialog
= function OoUiMessageDialog( config
) {
7151 // Parent constructor
7152 OO
.ui
.MessageDialog
.super.call( this, config
);
7155 this.verticalActionLayout
= null;
7158 this.$element
.addClass( 'oo-ui-messageDialog' );
7163 OO
.inheritClass( OO
.ui
.MessageDialog
, OO
.ui
.Dialog
);
7165 /* Static Properties */
7167 OO
.ui
.MessageDialog
.static.name
= 'message';
7169 OO
.ui
.MessageDialog
.static.size
= 'small';
7171 OO
.ui
.MessageDialog
.static.verbose
= false;
7176 * The title of a confirmation dialog describes what a progressive action will do. The
7177 * title of an alert dialog describes which event occurred.
7181 * @property {jQuery|string|Function|null}
7183 OO
.ui
.MessageDialog
.static.title
= null;
7186 * The message displayed in the dialog body.
7188 * A confirmation message describes the consequences of a progressive action. An alert
7189 * message describes why an event occurred.
7193 * @property {jQuery|string|Function|null}
7195 OO
.ui
.MessageDialog
.static.message
= null;
7197 OO
.ui
.MessageDialog
.static.actions
= [
7198 { action
: 'accept', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-accept' ), flags
: 'primary' },
7199 { action
: 'reject', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-reject' ), flags
: 'safe' }
7207 OO
.ui
.MessageDialog
.prototype.setManager = function ( manager
) {
7208 OO
.ui
.MessageDialog
.super.prototype.setManager
.call( this, manager
);
7211 this.manager
.connect( this, {
7221 OO
.ui
.MessageDialog
.prototype.onActionResize = function ( action
) {
7223 return OO
.ui
.MessageDialog
.super.prototype.onActionResize
.call( this, action
);
7227 * Handle window resized events.
7231 OO
.ui
.MessageDialog
.prototype.onResize = function () {
7233 dialog
.fitActions();
7234 // Wait for CSS transition to finish and do it again :(
7235 setTimeout( function () {
7236 dialog
.fitActions();
7241 * Toggle action layout between vertical and horizontal.
7245 * @param {boolean} [value] Layout actions vertically, omit to toggle
7248 OO
.ui
.MessageDialog
.prototype.toggleVerticalActionLayout = function ( value
) {
7249 value
= value
=== undefined ? !this.verticalActionLayout
: !!value
;
7251 if ( value
!== this.verticalActionLayout
) {
7252 this.verticalActionLayout
= value
;
7254 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value
)
7255 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value
);
7264 OO
.ui
.MessageDialog
.prototype.getActionProcess = function ( action
) {
7266 return new OO
.ui
.Process( function () {
7267 this.close( { action
: action
} );
7270 return OO
.ui
.MessageDialog
.super.prototype.getActionProcess
.call( this, action
);
7276 * @param {Object} [data] Dialog opening data
7277 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
7278 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
7279 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
7280 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
7283 OO
.ui
.MessageDialog
.prototype.getSetupProcess = function ( data
) {
7287 return OO
.ui
.MessageDialog
.super.prototype.getSetupProcess
.call( this, data
)
7288 .next( function () {
7289 this.title
.setLabel(
7290 data
.title
!== undefined ? data
.title
: this.constructor.static.title
7292 this.message
.setLabel(
7293 data
.message
!== undefined ? data
.message
: this.constructor.static.message
7295 this.message
.$element
.toggleClass(
7296 'oo-ui-messageDialog-message-verbose',
7297 data
.verbose
!== undefined ? data
.verbose
: this.constructor.static.verbose
7305 OO
.ui
.MessageDialog
.prototype.getBodyHeight = function () {
7306 var bodyHeight
, oldOverflow
,
7307 $scrollable
= this.container
.$element
;
7309 oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
7310 $scrollable
[ 0 ].style
.overflow
= 'hidden';
7312 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
7314 bodyHeight
= this.text
.$element
.outerHeight( true );
7315 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
7323 OO
.ui
.MessageDialog
.prototype.setDimensions = function ( dim
) {
7324 var $scrollable
= this.container
.$element
;
7325 OO
.ui
.MessageDialog
.super.prototype.setDimensions
.call( this, dim
);
7327 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
7328 // Need to do it after transition completes (250ms), add 50ms just in case.
7329 setTimeout( function () {
7330 var oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
7331 $scrollable
[ 0 ].style
.overflow
= 'hidden';
7333 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
7335 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
7344 OO
.ui
.MessageDialog
.prototype.initialize = function () {
7346 OO
.ui
.MessageDialog
.super.prototype.initialize
.call( this );
7349 this.$actions
= $( '<div>' );
7350 this.container
= new OO
.ui
.PanelLayout( {
7351 scrollable
: true, classes
: [ 'oo-ui-messageDialog-container' ]
7353 this.text
= new OO
.ui
.PanelLayout( {
7354 padded
: true, expanded
: false, classes
: [ 'oo-ui-messageDialog-text' ]
7356 this.message
= new OO
.ui
.LabelWidget( {
7357 classes
: [ 'oo-ui-messageDialog-message' ]
7361 this.title
.$element
.addClass( 'oo-ui-messageDialog-title' );
7362 this.$content
.addClass( 'oo-ui-messageDialog-content' );
7363 this.container
.$element
.append( this.text
.$element
);
7364 this.text
.$element
.append( this.title
.$element
, this.message
.$element
);
7365 this.$body
.append( this.container
.$element
);
7366 this.$actions
.addClass( 'oo-ui-messageDialog-actions' );
7367 this.$foot
.append( this.$actions
);
7373 OO
.ui
.MessageDialog
.prototype.attachActions = function () {
7374 var i
, len
, other
, special
, others
;
7377 OO
.ui
.MessageDialog
.super.prototype.attachActions
.call( this );
7379 special
= this.actions
.getSpecial();
7380 others
= this.actions
.getOthers();
7381 if ( special
.safe
) {
7382 this.$actions
.append( special
.safe
.$element
);
7383 special
.safe
.toggleFramed( false );
7385 if ( others
.length
) {
7386 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
7387 other
= others
[ i
];
7388 this.$actions
.append( other
.$element
);
7389 other
.toggleFramed( false );
7392 if ( special
.primary
) {
7393 this.$actions
.append( special
.primary
.$element
);
7394 special
.primary
.toggleFramed( false );
7397 if ( !this.isOpening() ) {
7398 // If the dialog is currently opening, this will be called automatically soon.
7399 // This also calls #fitActions.
7405 * Fit action actions into columns or rows.
7407 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
7411 OO
.ui
.MessageDialog
.prototype.fitActions = function () {
7413 previous
= this.verticalActionLayout
,
7414 actions
= this.actions
.get();
7417 this.toggleVerticalActionLayout( false );
7418 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
7419 action
= actions
[ i
];
7420 if ( action
.$element
.innerWidth() < action
.$label
.outerWidth( true ) ) {
7421 this.toggleVerticalActionLayout( true );
7426 // Move the body out of the way of the foot
7427 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
7429 if ( this.verticalActionLayout
!== previous
) {
7430 // We changed the layout, window height might need to be updated.
7436 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
7437 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
7438 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
7439 * relevant. The ProcessDialog class is always extended and customized with the actions and content
7440 * required for each process.
7442 * The process dialog box consists of a header that visually represents the ‘working’ state of long
7443 * processes with an animation. The header contains the dialog title as well as
7444 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
7445 * a ‘primary’ action on the right (e.g., ‘Done’).
7447 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
7448 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
7451 * // Example: Creating and opening a process dialog window.
7452 * function MyProcessDialog( config ) {
7453 * MyProcessDialog.super.call( this, config );
7455 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
7457 * MyProcessDialog.static.title = 'Process dialog';
7458 * MyProcessDialog.static.actions = [
7459 * { action: 'save', label: 'Done', flags: 'primary' },
7460 * { label: 'Cancel', flags: 'safe' }
7463 * MyProcessDialog.prototype.initialize = function () {
7464 * MyProcessDialog.super.prototype.initialize.apply( this, arguments );
7465 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true, expanded: false } );
7466 * 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>' );
7467 * this.$body.append( this.content.$element );
7469 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
7470 * var dialog = this;
7472 * return new OO.ui.Process( function () {
7473 * dialog.close( { action: action } );
7476 * return MyProcessDialog.super.prototype.getActionProcess.call( this, action );
7479 * var windowManager = new OO.ui.WindowManager();
7480 * $( 'body' ).append( windowManager.$element );
7482 * var dialog = new MyProcessDialog();
7483 * windowManager.addWindows( [ dialog ] );
7484 * windowManager.openWindow( dialog );
7486 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
7490 * @extends OO.ui.Dialog
7493 * @param {Object} [config] Configuration options
7495 OO
.ui
.ProcessDialog
= function OoUiProcessDialog( config
) {
7496 // Parent constructor
7497 OO
.ui
.ProcessDialog
.super.call( this, config
);
7500 this.$element
.addClass( 'oo-ui-processDialog' );
7505 OO
.inheritClass( OO
.ui
.ProcessDialog
, OO
.ui
.Dialog
);
7510 * Handle dismiss button click events.
7516 OO
.ui
.ProcessDialog
.prototype.onDismissErrorButtonClick = function () {
7521 * Handle retry button click events.
7523 * Hides errors and then tries again.
7527 OO
.ui
.ProcessDialog
.prototype.onRetryButtonClick = function () {
7529 this.executeAction( this.currentAction
);
7535 OO
.ui
.ProcessDialog
.prototype.onActionResize = function ( action
) {
7536 if ( this.actions
.isSpecial( action
) ) {
7539 return OO
.ui
.ProcessDialog
.super.prototype.onActionResize
.call( this, action
);
7545 OO
.ui
.ProcessDialog
.prototype.initialize = function () {
7547 OO
.ui
.ProcessDialog
.super.prototype.initialize
.call( this );
7550 this.$navigation
= $( '<div>' );
7551 this.$location
= $( '<div>' );
7552 this.$safeActions
= $( '<div>' );
7553 this.$primaryActions
= $( '<div>' );
7554 this.$otherActions
= $( '<div>' );
7555 this.dismissButton
= new OO
.ui
.ButtonWidget( {
7556 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' )
7558 this.retryButton
= new OO
.ui
.ButtonWidget();
7559 this.$errors
= $( '<div>' );
7560 this.$errorsTitle
= $( '<div>' );
7563 this.dismissButton
.connect( this, { click
: 'onDismissErrorButtonClick' } );
7564 this.retryButton
.connect( this, { click
: 'onRetryButtonClick' } );
7567 this.title
.$element
.addClass( 'oo-ui-processDialog-title' );
7569 .append( this.title
.$element
)
7570 .addClass( 'oo-ui-processDialog-location' );
7571 this.$safeActions
.addClass( 'oo-ui-processDialog-actions-safe' );
7572 this.$primaryActions
.addClass( 'oo-ui-processDialog-actions-primary' );
7573 this.$otherActions
.addClass( 'oo-ui-processDialog-actions-other' );
7575 .addClass( 'oo-ui-processDialog-errors-title' )
7576 .text( OO
.ui
.msg( 'ooui-dialog-process-error' ) );
7578 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
7579 .append( this.$errorsTitle
, this.dismissButton
.$element
, this.retryButton
.$element
);
7581 .addClass( 'oo-ui-processDialog-content' )
7582 .append( this.$errors
);
7584 .addClass( 'oo-ui-processDialog-navigation' )
7585 .append( this.$safeActions
, this.$location
, this.$primaryActions
);
7586 this.$head
.append( this.$navigation
);
7587 this.$foot
.append( this.$otherActions
);
7593 OO
.ui
.ProcessDialog
.prototype.getActionWidgets = function ( actions
) {
7594 var i
, len
, widgets
= [];
7595 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
7597 new OO
.ui
.ActionWidget( $.extend( { framed
: true }, actions
[ i
] ) )
7606 OO
.ui
.ProcessDialog
.prototype.attachActions = function () {
7607 var i
, len
, other
, special
, others
;
7610 OO
.ui
.ProcessDialog
.super.prototype.attachActions
.call( this );
7612 special
= this.actions
.getSpecial();
7613 others
= this.actions
.getOthers();
7614 if ( special
.primary
) {
7615 this.$primaryActions
.append( special
.primary
.$element
);
7617 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
7618 other
= others
[ i
];
7619 this.$otherActions
.append( other
.$element
);
7621 if ( special
.safe
) {
7622 this.$safeActions
.append( special
.safe
.$element
);
7626 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
7632 OO
.ui
.ProcessDialog
.prototype.executeAction = function ( action
) {
7634 OO
.ui
.ProcessDialog
.super.prototype.executeAction
.call( this, action
)
7635 .fail( function ( errors
) {
7636 process
.showErrors( errors
|| [] );
7641 * Fit label between actions.
7646 OO
.ui
.ProcessDialog
.prototype.fitLabel = function () {
7647 var width
= Math
.max(
7648 this.$safeActions
.is( ':visible' ) ? this.$safeActions
.width() : 0,
7649 this.$primaryActions
.is( ':visible' ) ? this.$primaryActions
.width() : 0
7651 this.$location
.css( { paddingLeft
: width
, paddingRight
: width
} );
7657 * Handle errors that occurred during accept or reject processes.
7660 * @param {OO.ui.Error[]} errors Errors to be handled
7662 OO
.ui
.ProcessDialog
.prototype.showErrors = function ( errors
) {
7663 var i
, len
, $item
, actions
,
7669 for ( i
= 0, len
= errors
.length
; i
< len
; i
++ ) {
7670 if ( !errors
[ i
].isRecoverable() ) {
7671 recoverable
= false;
7673 if ( errors
[ i
].isWarning() ) {
7676 $item
= $( '<div>' )
7677 .addClass( 'oo-ui-processDialog-error' )
7678 .append( errors
[ i
].getMessage() );
7679 items
.push( $item
[ 0 ] );
7681 this.$errorItems
= $( items
);
7682 if ( recoverable
) {
7683 abilities
[this.currentAction
] = true;
7684 // Copy the flags from the first matching action
7685 actions
= this.actions
.get( { actions
: this.currentAction
} );
7686 if ( actions
.length
) {
7687 this.retryButton
.clearFlags().setFlags( actions
[0].getFlags() );
7690 abilities
[this.currentAction
] = false;
7691 this.actions
.setAbilities( abilities
);
7694 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-continue' ) );
7696 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-retry' ) );
7698 this.retryButton
.toggle( recoverable
);
7699 this.$errorsTitle
.after( this.$errorItems
);
7700 this.$errors
.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
7708 OO
.ui
.ProcessDialog
.prototype.hideErrors = function () {
7709 this.$errors
.addClass( 'oo-ui-element-hidden' );
7710 if ( this.$errorItems
) {
7711 this.$errorItems
.remove();
7712 this.$errorItems
= null;
7719 OO
.ui
.ProcessDialog
.prototype.getTeardownProcess = function ( data
) {
7721 return OO
.ui
.ProcessDialog
.super.prototype.getTeardownProcess
.call( this, data
)
7722 .first( function () {
7723 // Make sure to hide errors
7729 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
7730 * which is a widget that is specified by reference before any optional configuration settings.
7732 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
7734 * - **left**: The label is placed before the field-widget and aligned with the left margin.
7735 * A left-alignment is used for forms with many fields.
7736 * - **right**: The label is placed before the field-widget and aligned to the right margin.
7737 * A right-alignment is used for long but familiar forms which users tab through,
7738 * verifying the current field with a quick glance at the label.
7739 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
7740 * that users fill out from top to bottom.
7741 * - **inline**: The label is placed after the field-widget and aligned to the left.
7742 * An inline-alignment is best used with checkboxes or radio buttons.
7744 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
7745 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
7747 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
7749 * @extends OO.ui.Layout
7750 * @mixins OO.ui.LabelElement
7753 * @param {OO.ui.Widget} fieldWidget Field widget
7754 * @param {Object} [config] Configuration options
7755 * @cfg {string} [align='left'] Alignment mode, either 'left', 'right', 'top' or 'inline'
7756 * @cfg {string} [help] Explanatory text shown as a '?' icon.
7758 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
7759 // Allow passing positional parameters inside the config object
7760 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
7761 config
= fieldWidget
;
7762 fieldWidget
= config
.fieldWidget
;
7765 var hasInputWidget
= fieldWidget
instanceof OO
.ui
.InputWidget
;
7767 // Configuration initialization
7768 config
= $.extend( { align
: 'left' }, config
);
7770 // Parent constructor
7771 OO
.ui
.FieldLayout
.super.call( this, config
);
7773 // Mixin constructors
7774 OO
.ui
.LabelElement
.call( this, config
);
7777 this.fieldWidget
= fieldWidget
;
7778 this.$field
= $( '<div>' );
7779 this.$body
= $( '<' + ( hasInputWidget
? 'label' : 'div' ) + '>' );
7781 if ( config
.help
) {
7782 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
7783 classes
: [ 'oo-ui-fieldLayout-help' ],
7788 this.popupButtonWidget
.getPopup().$body
.append(
7790 .text( config
.help
)
7791 .addClass( 'oo-ui-fieldLayout-help-content' )
7793 this.$help
= this.popupButtonWidget
.$element
;
7795 this.$help
= $( [] );
7799 if ( hasInputWidget
) {
7800 this.$label
.on( 'click', this.onLabelClick
.bind( this ) );
7802 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
7806 .addClass( 'oo-ui-fieldLayout' )
7807 .append( this.$help
, this.$body
);
7808 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
7810 .addClass( 'oo-ui-fieldLayout-field' )
7811 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget
.isDisabled() )
7812 .append( this.fieldWidget
.$element
);
7814 this.setAlignment( config
.align
);
7819 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
7820 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.LabelElement
);
7825 * Handle field disable events.
7827 * @param {boolean} value Field is disabled
7829 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
7830 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
7834 * Handle label mouse click events.
7836 * @param {jQuery.Event} e Mouse click event
7838 OO
.ui
.FieldLayout
.prototype.onLabelClick = function () {
7839 this.fieldWidget
.simulateLabelClick();
7846 * @return {OO.ui.Widget} Field widget
7848 OO
.ui
.FieldLayout
.prototype.getField = function () {
7849 return this.fieldWidget
;
7853 * Set the field alignment mode.
7856 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
7859 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
7860 if ( value
!== this.align
) {
7861 // Default to 'left'
7862 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
7866 if ( value
=== 'inline' ) {
7867 this.$body
.append( this.$field
, this.$label
);
7869 this.$body
.append( this.$label
, this.$field
);
7871 // Set classes. The following classes can be used here:
7872 // * oo-ui-fieldLayout-align-left
7873 // * oo-ui-fieldLayout-align-right
7874 // * oo-ui-fieldLayout-align-top
7875 // * oo-ui-fieldLayout-align-inline
7877 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
7879 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
7887 * Layout made of a field, a button, and an optional label.
7890 * @extends OO.ui.FieldLayout
7893 * @param {OO.ui.Widget} fieldWidget Field widget
7894 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
7895 * @param {Object} [config] Configuration options
7896 * @cfg {string} [align='left'] Alignment mode, either 'left', 'right', 'top' or 'inline'
7897 * @cfg {string} [help] Explanatory text shown as a '?' icon.
7899 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
7900 // Allow passing positional parameters inside the config object
7901 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
7902 config
= fieldWidget
;
7903 fieldWidget
= config
.fieldWidget
;
7904 buttonWidget
= config
.buttonWidget
;
7907 // Configuration initialization
7908 config
= $.extend( { align
: 'left' }, config
);
7910 // Parent constructor
7911 OO
.ui
.ActionFieldLayout
.super.call( this, fieldWidget
, config
);
7914 this.fieldWidget
= fieldWidget
;
7915 this.buttonWidget
= buttonWidget
;
7916 this.$button
= $( '<div>' )
7917 .addClass( 'oo-ui-actionFieldLayout-button' )
7918 .append( this.buttonWidget
.$element
);
7919 this.$input
= $( '<div>' )
7920 .addClass( 'oo-ui-actionFieldLayout-input' )
7921 .append( this.fieldWidget
.$element
);
7923 .addClass( 'oo-ui-actionFieldLayout' )
7924 .append( this.$input
, this.$button
);
7929 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
7932 * Layout made of a fieldset and optional legend.
7934 * Just add OO.ui.FieldLayout items.
7937 * @extends OO.ui.Layout
7938 * @mixins OO.ui.IconElement
7939 * @mixins OO.ui.LabelElement
7940 * @mixins OO.ui.GroupElement
7943 * @param {Object} [config] Configuration options
7944 * @cfg {OO.ui.FieldLayout[]} [items] Items to add
7946 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
7947 // Configuration initialization
7948 config
= config
|| {};
7950 // Parent constructor
7951 OO
.ui
.FieldsetLayout
.super.call( this, config
);
7953 // Mixin constructors
7954 OO
.ui
.IconElement
.call( this, config
);
7955 OO
.ui
.LabelElement
.call( this, config
);
7956 OO
.ui
.GroupElement
.call( this, config
);
7958 if ( config
.help
) {
7959 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
7960 classes
: [ 'oo-ui-fieldsetLayout-help' ],
7965 this.popupButtonWidget
.getPopup().$body
.append(
7967 .text( config
.help
)
7968 .addClass( 'oo-ui-fieldsetLayout-help-content' )
7970 this.$help
= this.popupButtonWidget
.$element
;
7972 this.$help
= $( [] );
7977 .addClass( 'oo-ui-fieldsetLayout' )
7978 .prepend( this.$help
, this.$icon
, this.$label
, this.$group
);
7979 if ( Array
.isArray( config
.items
) ) {
7980 this.addItems( config
.items
);
7986 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
7987 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.IconElement
);
7988 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.LabelElement
);
7989 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.GroupElement
);
7992 * Layout with an HTML form.
7995 * @extends OO.ui.Layout
7996 * @mixins OO.ui.GroupElement
7999 * @param {Object} [config] Configuration options
8000 * @cfg {string} [method] HTML form `method` attribute
8001 * @cfg {string} [action] HTML form `action` attribute
8002 * @cfg {string} [enctype] HTML form `enctype` attribute
8003 * @cfg {OO.ui.FieldsetLayout[]} [items] Items to add
8005 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
8006 // Configuration initialization
8007 config
= config
|| {};
8009 // Parent constructor
8010 OO
.ui
.FormLayout
.super.call( this, config
);
8012 // Mixin constructors
8013 OO
.ui
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
8016 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
8020 .addClass( 'oo-ui-formLayout' )
8022 method
: config
.method
,
8023 action
: config
.action
,
8024 enctype
: config
.enctype
8026 if ( Array
.isArray( config
.items
) ) {
8027 this.addItems( config
.items
);
8033 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
8034 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.GroupElement
);
8042 /* Static Properties */
8044 OO
.ui
.FormLayout
.static.tagName
= 'form';
8049 * Handle form submit events.
8051 * @param {jQuery.Event} e Submit event
8054 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
8055 this.emit( 'submit' );
8060 * Layout with a content and menu area.
8062 * The menu area can be positioned at the top, after, bottom or before. The content area will fill
8063 * all remaining space.
8066 * @extends OO.ui.Layout
8069 * @param {Object} [config] Configuration options
8070 * @cfg {number|string} [menuSize='18em'] Size of menu in pixels or any CSS unit
8071 * @cfg {boolean} [showMenu=true] Show menu
8072 * @cfg {string} [position='before'] Position of menu, either `top`, `after`, `bottom` or `before`
8073 * @cfg {boolean} [collapse] Collapse the menu out of view
8075 OO
.ui
.MenuLayout
= function OoUiMenuLayout( config
) {
8076 var positions
= this.constructor.static.menuPositions
;
8078 // Configuration initialization
8079 config
= config
|| {};
8081 // Parent constructor
8082 OO
.ui
.MenuLayout
.super.call( this, config
);
8085 this.showMenu
= config
.showMenu
!== false;
8086 this.menuSize
= config
.menuSize
|| '18em';
8087 this.menuPosition
= positions
[ config
.menuPosition
] || positions
.before
;
8092 * @property {jQuery}
8094 this.$menu
= $( '<div>' );
8098 * @property {jQuery}
8100 this.$content
= $( '<div>' );
8103 this.toggleMenu( this.showMenu
);
8106 .addClass( 'oo-ui-menuLayout-menu' )
8107 .css( this.menuPosition
.sizeProperty
, this.menuSize
);
8108 this.$content
.addClass( 'oo-ui-menuLayout-content' );
8110 .addClass( 'oo-ui-menuLayout ' + this.menuPosition
.className
)
8111 .append( this.$content
, this.$menu
);
8116 OO
.inheritClass( OO
.ui
.MenuLayout
, OO
.ui
.Layout
);
8118 /* Static Properties */
8120 OO
.ui
.MenuLayout
.static.menuPositions
= {
8122 sizeProperty
: 'height',
8123 className
: 'oo-ui-menuLayout-top'
8126 sizeProperty
: 'width',
8127 className
: 'oo-ui-menuLayout-after'
8130 sizeProperty
: 'height',
8131 className
: 'oo-ui-menuLayout-bottom'
8134 sizeProperty
: 'width',
8135 className
: 'oo-ui-menuLayout-before'
8144 * @param {boolean} showMenu Show menu, omit to toggle
8147 OO
.ui
.MenuLayout
.prototype.toggleMenu = function ( showMenu
) {
8148 showMenu
= showMenu
=== undefined ? !this.showMenu
: !!showMenu
;
8150 if ( this.showMenu
!== showMenu
) {
8151 this.showMenu
= showMenu
;
8159 * Check if menu is visible
8161 * @return {boolean} Menu is visible
8163 OO
.ui
.MenuLayout
.prototype.isMenuVisible = function () {
8164 return this.showMenu
;
8170 * @param {number|string} size Size of menu in pixels or any CSS unit
8173 OO
.ui
.MenuLayout
.prototype.setMenuSize = function ( size
) {
8174 this.menuSize
= size
;
8181 * Update menu and content CSS based on current menu size and visibility
8183 * This method is called internally when size or position is changed.
8185 OO
.ui
.MenuLayout
.prototype.updateSizes = function () {
8186 if ( this.showMenu
) {
8188 .css( this.menuPosition
.sizeProperty
, this.menuSize
)
8189 .css( 'overflow', '' );
8190 // Set offsets on all sides. CSS resets all but one with
8191 // 'important' rules so directionality flips are supported
8192 this.$content
.css( {
8194 right
: this.menuSize
,
8195 bottom
: this.menuSize
,
8200 .css( this.menuPosition
.sizeProperty
, 0 )
8201 .css( 'overflow', 'hidden' );
8202 this.$content
.css( {
8214 * @return {number|string} Menu size
8216 OO
.ui
.MenuLayout
.prototype.getMenuSize = function () {
8217 return this.menuSize
;
8221 * Set menu position.
8223 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
8224 * @throws {Error} If position value is not supported
8227 OO
.ui
.MenuLayout
.prototype.setMenuPosition = function ( position
) {
8228 var positions
= this.constructor.static.menuPositions
;
8230 if ( !positions
[ position
] ) {
8231 throw new Error( 'Cannot set position; unsupported position value: ' + position
);
8234 this.$menu
.css( this.menuPosition
.sizeProperty
, '' );
8235 this.$element
.removeClass( this.menuPosition
.className
);
8237 this.menuPosition
= positions
[ position
];
8240 this.$element
.addClass( this.menuPosition
.className
);
8246 * Get menu position.
8248 * @return {string} Menu position
8250 OO
.ui
.MenuLayout
.prototype.getMenuPosition = function () {
8251 return this.menuPosition
;
8255 * Layout containing a series of pages.
8258 * @extends OO.ui.MenuLayout
8261 * @param {Object} [config] Configuration options
8262 * @cfg {boolean} [continuous=false] Show all pages, one after another
8263 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when changing to a page
8264 * @cfg {boolean} [outlined=false] Show an outline
8265 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
8267 OO
.ui
.BookletLayout
= function OoUiBookletLayout( config
) {
8268 // Configuration initialization
8269 config
= config
|| {};
8271 // Parent constructor
8272 OO
.ui
.BookletLayout
.super.call( this, config
);
8275 this.currentPageName
= null;
8277 this.ignoreFocus
= false;
8278 this.stackLayout
= new OO
.ui
.StackLayout( { continuous
: !!config
.continuous
} );
8279 this.$content
.append( this.stackLayout
.$element
);
8280 this.autoFocus
= config
.autoFocus
=== undefined || !!config
.autoFocus
;
8281 this.outlineVisible
= false;
8282 this.outlined
= !!config
.outlined
;
8283 if ( this.outlined
) {
8284 this.editable
= !!config
.editable
;
8285 this.outlineControlsWidget
= null;
8286 this.outlineSelectWidget
= new OO
.ui
.OutlineSelectWidget();
8287 this.outlinePanel
= new OO
.ui
.PanelLayout( { scrollable
: true } );
8288 this.$menu
.append( this.outlinePanel
.$element
);
8289 this.outlineVisible
= true;
8290 if ( this.editable
) {
8291 this.outlineControlsWidget
= new OO
.ui
.OutlineControlsWidget(
8292 this.outlineSelectWidget
8296 this.toggleMenu( this.outlined
);
8299 this.stackLayout
.connect( this, { set: 'onStackLayoutSet' } );
8300 if ( this.outlined
) {
8301 this.outlineSelectWidget
.connect( this, { select
: 'onOutlineSelectWidgetSelect' } );
8303 if ( this.autoFocus
) {
8304 // Event 'focus' does not bubble, but 'focusin' does
8305 this.stackLayout
.$element
.on( 'focusin', this.onStackLayoutFocus
.bind( this ) );
8309 this.$element
.addClass( 'oo-ui-bookletLayout' );
8310 this.stackLayout
.$element
.addClass( 'oo-ui-bookletLayout-stackLayout' );
8311 if ( this.outlined
) {
8312 this.outlinePanel
.$element
8313 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
8314 .append( this.outlineSelectWidget
.$element
);
8315 if ( this.editable
) {
8316 this.outlinePanel
.$element
8317 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
8318 .append( this.outlineControlsWidget
.$element
);
8325 OO
.inheritClass( OO
.ui
.BookletLayout
, OO
.ui
.MenuLayout
);
8331 * @param {OO.ui.PageLayout} page Current page
8336 * @param {OO.ui.PageLayout[]} page Added pages
8337 * @param {number} index Index pages were added at
8342 * @param {OO.ui.PageLayout[]} pages Removed pages
8348 * Handle stack layout focus.
8350 * @param {jQuery.Event} e Focusin event
8352 OO
.ui
.BookletLayout
.prototype.onStackLayoutFocus = function ( e
) {
8355 // Find the page that an element was focused within
8356 $target
= $( e
.target
).closest( '.oo-ui-pageLayout' );
8357 for ( name
in this.pages
) {
8358 // Check for page match, exclude current page to find only page changes
8359 if ( this.pages
[ name
].$element
[ 0 ] === $target
[ 0 ] && name
!== this.currentPageName
) {
8360 this.setPage( name
);
8367 * Handle stack layout set events.
8369 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
8371 OO
.ui
.BookletLayout
.prototype.onStackLayoutSet = function ( page
) {
8374 page
.scrollElementIntoView( { complete: function () {
8375 if ( layout
.autoFocus
) {
8383 * Focus the first input in the current page.
8385 * If no page is selected, the first selectable page will be selected.
8386 * If the focus is already in an element on the current page, nothing will happen.
8388 OO
.ui
.BookletLayout
.prototype.focus = function () {
8389 var $input
, page
= this.stackLayout
.getCurrentItem();
8390 if ( !page
&& this.outlined
) {
8391 this.selectFirstSelectablePage();
8392 page
= this.stackLayout
.getCurrentItem();
8397 // Only change the focus if is not already in the current page
8398 if ( !page
.$element
.find( ':focus' ).length
) {
8399 $input
= page
.$element
.find( ':input:first' );
8400 if ( $input
.length
) {
8401 $input
[ 0 ].focus();
8407 * Handle outline widget select events.
8409 * @param {OO.ui.OptionWidget|null} item Selected item
8411 OO
.ui
.BookletLayout
.prototype.onOutlineSelectWidgetSelect = function ( item
) {
8413 this.setPage( item
.getData() );
8418 * Check if booklet has an outline.
8422 OO
.ui
.BookletLayout
.prototype.isOutlined = function () {
8423 return this.outlined
;
8427 * Check if booklet has editing controls.
8431 OO
.ui
.BookletLayout
.prototype.isEditable = function () {
8432 return this.editable
;
8436 * Check if booklet has a visible outline.
8440 OO
.ui
.BookletLayout
.prototype.isOutlineVisible = function () {
8441 return this.outlined
&& this.outlineVisible
;
8445 * Hide or show the outline.
8447 * @param {boolean} [show] Show outline, omit to invert current state
8450 OO
.ui
.BookletLayout
.prototype.toggleOutline = function ( show
) {
8451 if ( this.outlined
) {
8452 show
= show
=== undefined ? !this.outlineVisible
: !!show
;
8453 this.outlineVisible
= show
;
8454 this.toggleMenu( show
);
8461 * Get the outline widget.
8463 * @param {OO.ui.PageLayout} page Page to be selected
8464 * @return {OO.ui.PageLayout|null} Closest page to another
8466 OO
.ui
.BookletLayout
.prototype.getClosestPage = function ( page
) {
8467 var next
, prev
, level
,
8468 pages
= this.stackLayout
.getItems(),
8469 index
= $.inArray( page
, pages
);
8471 if ( index
!== -1 ) {
8472 next
= pages
[ index
+ 1 ];
8473 prev
= pages
[ index
- 1 ];
8474 // Prefer adjacent pages at the same level
8475 if ( this.outlined
) {
8476 level
= this.outlineSelectWidget
.getItemFromData( page
.getName() ).getLevel();
8479 level
=== this.outlineSelectWidget
.getItemFromData( prev
.getName() ).getLevel()
8485 level
=== this.outlineSelectWidget
.getItemFromData( next
.getName() ).getLevel()
8491 return prev
|| next
|| null;
8495 * Get the outline widget.
8497 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if booklet has no outline
8499 OO
.ui
.BookletLayout
.prototype.getOutline = function () {
8500 return this.outlineSelectWidget
;
8504 * Get the outline controls widget. If the outline is not editable, null is returned.
8506 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
8508 OO
.ui
.BookletLayout
.prototype.getOutlineControls = function () {
8509 return this.outlineControlsWidget
;
8513 * Get a page by name.
8515 * @param {string} name Symbolic name of page
8516 * @return {OO.ui.PageLayout|undefined} Page, if found
8518 OO
.ui
.BookletLayout
.prototype.getPage = function ( name
) {
8519 return this.pages
[ name
];
8523 * Get the current page
8525 * @return {OO.ui.PageLayout|undefined} Current page, if found
8527 OO
.ui
.BookletLayout
.prototype.getCurrentPage = function () {
8528 var name
= this.getCurrentPageName();
8529 return name
? this.getPage( name
) : undefined;
8533 * Get the current page name.
8535 * @return {string|null} Current page name
8537 OO
.ui
.BookletLayout
.prototype.getCurrentPageName = function () {
8538 return this.currentPageName
;
8542 * Add a page to the layout.
8544 * When pages are added with the same names as existing pages, the existing pages will be
8545 * automatically removed before the new pages are added.
8547 * @param {OO.ui.PageLayout[]} pages Pages to add
8548 * @param {number} index Index to insert pages after
8552 OO
.ui
.BookletLayout
.prototype.addPages = function ( pages
, index
) {
8553 var i
, len
, name
, page
, item
, currentIndex
,
8554 stackLayoutPages
= this.stackLayout
.getItems(),
8558 // Remove pages with same names
8559 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
8561 name
= page
.getName();
8563 if ( Object
.prototype.hasOwnProperty
.call( this.pages
, name
) ) {
8564 // Correct the insertion index
8565 currentIndex
= $.inArray( this.pages
[ name
], stackLayoutPages
);
8566 if ( currentIndex
!== -1 && currentIndex
+ 1 < index
) {
8569 remove
.push( this.pages
[ name
] );
8572 if ( remove
.length
) {
8573 this.removePages( remove
);
8577 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
8579 name
= page
.getName();
8580 this.pages
[ page
.getName() ] = page
;
8581 if ( this.outlined
) {
8582 item
= new OO
.ui
.OutlineOptionWidget( { data
: name
} );
8583 page
.setOutlineItem( item
);
8588 if ( this.outlined
&& items
.length
) {
8589 this.outlineSelectWidget
.addItems( items
, index
);
8590 this.selectFirstSelectablePage();
8592 this.stackLayout
.addItems( pages
, index
);
8593 this.emit( 'add', pages
, index
);
8599 * Remove a page from the layout.
8604 OO
.ui
.BookletLayout
.prototype.removePages = function ( pages
) {
8605 var i
, len
, name
, page
,
8608 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
8610 name
= page
.getName();
8611 delete this.pages
[ name
];
8612 if ( this.outlined
) {
8613 items
.push( this.outlineSelectWidget
.getItemFromData( name
) );
8614 page
.setOutlineItem( null );
8617 if ( this.outlined
&& items
.length
) {
8618 this.outlineSelectWidget
.removeItems( items
);
8619 this.selectFirstSelectablePage();
8621 this.stackLayout
.removeItems( pages
);
8622 this.emit( 'remove', pages
);
8628 * Clear all pages from the layout.
8633 OO
.ui
.BookletLayout
.prototype.clearPages = function () {
8635 pages
= this.stackLayout
.getItems();
8638 this.currentPageName
= null;
8639 if ( this.outlined
) {
8640 this.outlineSelectWidget
.clearItems();
8641 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
8642 pages
[ i
].setOutlineItem( null );
8645 this.stackLayout
.clearItems();
8647 this.emit( 'remove', pages
);
8653 * Set the current page by name.
8656 * @param {string} name Symbolic name of page
8658 OO
.ui
.BookletLayout
.prototype.setPage = function ( name
) {
8661 page
= this.pages
[ name
];
8663 if ( name
!== this.currentPageName
) {
8664 if ( this.outlined
) {
8665 selectedItem
= this.outlineSelectWidget
.getSelectedItem();
8666 if ( selectedItem
&& selectedItem
.getData() !== name
) {
8667 this.outlineSelectWidget
.selectItem( this.outlineSelectWidget
.getItemFromData( name
) );
8671 if ( this.currentPageName
&& this.pages
[ this.currentPageName
] ) {
8672 this.pages
[ this.currentPageName
].setActive( false );
8673 // Blur anything focused if the next page doesn't have anything focusable - this
8674 // is not needed if the next page has something focusable because once it is focused
8675 // this blur happens automatically
8676 if ( this.autoFocus
&& !page
.$element
.find( ':input' ).length
) {
8677 $focused
= this.pages
[ this.currentPageName
].$element
.find( ':focus' );
8678 if ( $focused
.length
) {
8679 $focused
[ 0 ].blur();
8683 this.currentPageName
= name
;
8684 this.stackLayout
.setItem( page
);
8685 page
.setActive( true );
8686 this.emit( 'set', page
);
8692 * Select the first selectable page.
8696 OO
.ui
.BookletLayout
.prototype.selectFirstSelectablePage = function () {
8697 if ( !this.outlineSelectWidget
.getSelectedItem() ) {
8698 this.outlineSelectWidget
.selectItem( this.outlineSelectWidget
.getFirstSelectableItem() );
8705 * Layout that expands to cover the entire area of its parent, with optional scrolling and padding.
8708 * @extends OO.ui.Layout
8711 * @param {Object} [config] Configuration options
8712 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
8713 * @cfg {boolean} [padded=false] Pad the content from the edges
8714 * @cfg {boolean} [expanded=true] Expand size to fill the entire parent element
8715 * @cfg {boolean} [framed=false] Wrap in a frame to visually separate from outside content
8717 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
8718 // Configuration initialization
8719 config
= $.extend( {
8726 // Parent constructor
8727 OO
.ui
.PanelLayout
.super.call( this, config
);
8730 this.$element
.addClass( 'oo-ui-panelLayout' );
8731 if ( config
.scrollable
) {
8732 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
8734 if ( config
.padded
) {
8735 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
8737 if ( config
.expanded
) {
8738 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
8740 if ( config
.framed
) {
8741 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
8747 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
8750 * Page within an booklet layout.
8753 * @extends OO.ui.PanelLayout
8756 * @param {string} name Unique symbolic name of page
8757 * @param {Object} [config] Configuration options
8759 OO
.ui
.PageLayout
= function OoUiPageLayout( name
, config
) {
8760 // Allow passing positional parameters inside the config object
8761 if ( OO
.isPlainObject( name
) && config
=== undefined ) {
8766 // Configuration initialization
8767 config
= $.extend( { scrollable
: true }, config
);
8769 // Parent constructor
8770 OO
.ui
.PageLayout
.super.call( this, config
);
8774 this.outlineItem
= null;
8775 this.active
= false;
8778 this.$element
.addClass( 'oo-ui-pageLayout' );
8783 OO
.inheritClass( OO
.ui
.PageLayout
, OO
.ui
.PanelLayout
);
8789 * @param {boolean} active Page is active
8797 * @return {string} Symbolic name of page
8799 OO
.ui
.PageLayout
.prototype.getName = function () {
8804 * Check if page is active.
8806 * @return {boolean} Page is active
8808 OO
.ui
.PageLayout
.prototype.isActive = function () {
8815 * @return {OO.ui.OutlineOptionWidget|null} Outline item widget
8817 OO
.ui
.PageLayout
.prototype.getOutlineItem = function () {
8818 return this.outlineItem
;
8824 * @localdoc Subclasses should override #setupOutlineItem instead of this method to adjust the
8825 * outline item as desired; this method is called for setting (with an object) and unsetting
8826 * (with null) and overriding methods would have to check the value of `outlineItem` to avoid
8827 * operating on null instead of an OO.ui.OutlineOptionWidget object.
8829 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline item widget, null to clear
8832 OO
.ui
.PageLayout
.prototype.setOutlineItem = function ( outlineItem
) {
8833 this.outlineItem
= outlineItem
|| null;
8834 if ( outlineItem
) {
8835 this.setupOutlineItem();
8841 * Setup outline item.
8843 * @localdoc Subclasses should override this method to adjust the outline item as desired.
8845 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline item widget to setup
8848 OO
.ui
.PageLayout
.prototype.setupOutlineItem = function () {
8853 * Set page active state.
8855 * @param {boolean} Page is active
8858 OO
.ui
.PageLayout
.prototype.setActive = function ( active
) {
8861 if ( active
!== this.active
) {
8862 this.active
= active
;
8863 this.$element
.toggleClass( 'oo-ui-pageLayout-active', active
);
8864 this.emit( 'active', this.active
);
8869 * Layout containing a series of mutually exclusive pages.
8872 * @extends OO.ui.PanelLayout
8873 * @mixins OO.ui.GroupElement
8876 * @param {Object} [config] Configuration options
8877 * @cfg {boolean} [continuous=false] Show all pages, one after another
8878 * @cfg {OO.ui.Layout[]} [items] Layouts to add
8880 OO
.ui
.StackLayout
= function OoUiStackLayout( config
) {
8881 // Configuration initialization
8882 config
= $.extend( { scrollable
: true }, config
);
8884 // Parent constructor
8885 OO
.ui
.StackLayout
.super.call( this, config
);
8887 // Mixin constructors
8888 OO
.ui
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
8891 this.currentItem
= null;
8892 this.continuous
= !!config
.continuous
;
8895 this.$element
.addClass( 'oo-ui-stackLayout' );
8896 if ( this.continuous
) {
8897 this.$element
.addClass( 'oo-ui-stackLayout-continuous' );
8899 if ( Array
.isArray( config
.items
) ) {
8900 this.addItems( config
.items
);
8906 OO
.inheritClass( OO
.ui
.StackLayout
, OO
.ui
.PanelLayout
);
8907 OO
.mixinClass( OO
.ui
.StackLayout
, OO
.ui
.GroupElement
);
8913 * @param {OO.ui.Layout|null} item Current item or null if there is no longer a layout shown
8919 * Get the current item.
8921 * @return {OO.ui.Layout|null}
8923 OO
.ui
.StackLayout
.prototype.getCurrentItem = function () {
8924 return this.currentItem
;
8928 * Unset the current item.
8931 * @param {OO.ui.StackLayout} layout
8934 OO
.ui
.StackLayout
.prototype.unsetCurrentItem = function () {
8935 var prevItem
= this.currentItem
;
8936 if ( prevItem
=== null ) {
8940 this.currentItem
= null;
8941 this.emit( 'set', null );
8947 * Adding an existing item (by value) will move it.
8949 * @param {OO.ui.Layout[]} items Items to add
8950 * @param {number} [index] Index to insert items after
8953 OO
.ui
.StackLayout
.prototype.addItems = function ( items
, index
) {
8954 // Update the visibility
8955 this.updateHiddenState( items
, this.currentItem
);
8958 OO
.ui
.GroupElement
.prototype.addItems
.call( this, items
, index
);
8960 if ( !this.currentItem
&& items
.length
) {
8961 this.setItem( items
[ 0 ] );
8970 * Items will be detached, not removed, so they can be used later.
8972 * @param {OO.ui.Layout[]} items Items to remove
8976 OO
.ui
.StackLayout
.prototype.removeItems = function ( items
) {
8978 OO
.ui
.GroupElement
.prototype.removeItems
.call( this, items
);
8980 if ( $.inArray( this.currentItem
, items
) !== -1 ) {
8981 if ( this.items
.length
) {
8982 this.setItem( this.items
[ 0 ] );
8984 this.unsetCurrentItem();
8994 * Items will be detached, not removed, so they can be used later.
8999 OO
.ui
.StackLayout
.prototype.clearItems = function () {
9000 this.unsetCurrentItem();
9001 OO
.ui
.GroupElement
.prototype.clearItems
.call( this );
9009 * Any currently shown item will be hidden.
9011 * FIXME: If the passed item to show has not been added in the items list, then
9012 * this method drops it and unsets the current item.
9014 * @param {OO.ui.Layout} item Item to show
9018 OO
.ui
.StackLayout
.prototype.setItem = function ( item
) {
9019 if ( item
!== this.currentItem
) {
9020 this.updateHiddenState( this.items
, item
);
9022 if ( $.inArray( item
, this.items
) !== -1 ) {
9023 this.currentItem
= item
;
9024 this.emit( 'set', item
);
9026 this.unsetCurrentItem();
9034 * Update the visibility of all items in case of non-continuous view.
9036 * Ensure all items are hidden except for the selected one.
9037 * This method does nothing when the stack is continuous.
9039 * @param {OO.ui.Layout[]} items Item list iterate over
9040 * @param {OO.ui.Layout} [selectedItem] Selected item to show
9042 OO
.ui
.StackLayout
.prototype.updateHiddenState = function ( items
, selectedItem
) {
9045 if ( !this.continuous
) {
9046 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
9047 if ( !selectedItem
|| selectedItem
!== items
[ i
] ) {
9048 items
[ i
].$element
.addClass( 'oo-ui-element-hidden' );
9051 if ( selectedItem
) {
9052 selectedItem
.$element
.removeClass( 'oo-ui-element-hidden' );
9058 * Horizontal bar layout of tools as icon buttons.
9061 * @extends OO.ui.ToolGroup
9064 * @param {OO.ui.Toolbar} toolbar
9065 * @param {Object} [config] Configuration options
9067 OO
.ui
.BarToolGroup
= function OoUiBarToolGroup( toolbar
, config
) {
9068 // Allow passing positional parameters inside the config object
9069 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
9071 toolbar
= config
.toolbar
;
9074 // Parent constructor
9075 OO
.ui
.BarToolGroup
.super.call( this, toolbar
, config
);
9078 this.$element
.addClass( 'oo-ui-barToolGroup' );
9083 OO
.inheritClass( OO
.ui
.BarToolGroup
, OO
.ui
.ToolGroup
);
9085 /* Static Properties */
9087 OO
.ui
.BarToolGroup
.static.titleTooltips
= true;
9089 OO
.ui
.BarToolGroup
.static.accelTooltips
= true;
9091 OO
.ui
.BarToolGroup
.static.name
= 'bar';
9094 * Popup list of tools with an icon and optional label.
9098 * @extends OO.ui.ToolGroup
9099 * @mixins OO.ui.IconElement
9100 * @mixins OO.ui.IndicatorElement
9101 * @mixins OO.ui.LabelElement
9102 * @mixins OO.ui.TitledElement
9103 * @mixins OO.ui.ClippableElement
9106 * @param {OO.ui.Toolbar} toolbar
9107 * @param {Object} [config] Configuration options
9108 * @cfg {string} [header] Text to display at the top of the pop-up
9110 OO
.ui
.PopupToolGroup
= function OoUiPopupToolGroup( toolbar
, config
) {
9111 // Allow passing positional parameters inside the config object
9112 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
9114 toolbar
= config
.toolbar
;
9117 // Configuration initialization
9118 config
= config
|| {};
9120 // Parent constructor
9121 OO
.ui
.PopupToolGroup
.super.call( this, toolbar
, config
);
9123 // Mixin constructors
9124 OO
.ui
.IconElement
.call( this, config
);
9125 OO
.ui
.IndicatorElement
.call( this, config
);
9126 OO
.ui
.LabelElement
.call( this, config
);
9127 OO
.ui
.TitledElement
.call( this, config
);
9128 OO
.ui
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
9131 this.active
= false;
9132 this.dragging
= false;
9133 this.onBlurHandler
= this.onBlur
.bind( this );
9134 this.$handle
= $( '<span>' );
9138 mousedown
: this.onHandlePointerDown
.bind( this ),
9139 mouseup
: this.onHandlePointerUp
.bind( this )
9144 .addClass( 'oo-ui-popupToolGroup-handle' )
9145 .append( this.$icon
, this.$label
, this.$indicator
);
9146 // If the pop-up should have a header, add it to the top of the toolGroup.
9147 // Note: If this feature is useful for other widgets, we could abstract it into an
9148 // OO.ui.HeaderedElement mixin constructor.
9149 if ( config
.header
!== undefined ) {
9151 .prepend( $( '<span>' )
9152 .addClass( 'oo-ui-popupToolGroup-header' )
9153 .text( config
.header
)
9157 .addClass( 'oo-ui-popupToolGroup' )
9158 .prepend( this.$handle
);
9163 OO
.inheritClass( OO
.ui
.PopupToolGroup
, OO
.ui
.ToolGroup
);
9164 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.IconElement
);
9165 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.IndicatorElement
);
9166 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.LabelElement
);
9167 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.TitledElement
);
9168 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.ClippableElement
);
9170 /* Static Properties */
9177 OO
.ui
.PopupToolGroup
.prototype.setDisabled = function () {
9179 OO
.ui
.PopupToolGroup
.super.prototype.setDisabled
.apply( this, arguments
);
9181 if ( this.isDisabled() && this.isElementAttached() ) {
9182 this.setActive( false );
9187 * Handle focus being lost.
9189 * The event is actually generated from a mouseup, so it is not a normal blur event object.
9191 * @param {jQuery.Event} e Mouse up event
9193 OO
.ui
.PopupToolGroup
.prototype.onBlur = function ( e
) {
9194 // Only deactivate when clicking outside the dropdown element
9195 if ( $( e
.target
).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element
[ 0 ] ) {
9196 this.setActive( false );
9203 OO
.ui
.PopupToolGroup
.prototype.onPointerUp = function ( e
) {
9204 // Only close toolgroup when a tool was actually selected
9205 if ( !this.isDisabled() && e
.which
=== 1 && this.pressed
&& this.pressed
=== this.getTargetTool( e
) ) {
9206 this.setActive( false );
9208 return OO
.ui
.PopupToolGroup
.super.prototype.onPointerUp
.call( this, e
);
9212 * Handle mouse up events.
9214 * @param {jQuery.Event} e Mouse up event
9216 OO
.ui
.PopupToolGroup
.prototype.onHandlePointerUp = function () {
9221 * Handle mouse down events.
9223 * @param {jQuery.Event} e Mouse down event
9225 OO
.ui
.PopupToolGroup
.prototype.onHandlePointerDown = function ( e
) {
9226 if ( !this.isDisabled() && e
.which
=== 1 ) {
9227 this.setActive( !this.active
);
9233 * Switch into active mode.
9235 * When active, mouseup events anywhere in the document will trigger deactivation.
9237 OO
.ui
.PopupToolGroup
.prototype.setActive = function ( value
) {
9239 if ( this.active
!== value
) {
9240 this.active
= value
;
9242 this.getElementDocument().addEventListener( 'mouseup', this.onBlurHandler
, true );
9244 // Try anchoring the popup to the left first
9245 this.$element
.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
9246 this.toggleClipping( true );
9247 if ( this.isClippedHorizontally() ) {
9248 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
9249 this.toggleClipping( false );
9251 .removeClass( 'oo-ui-popupToolGroup-left' )
9252 .addClass( 'oo-ui-popupToolGroup-right' );
9253 this.toggleClipping( true );
9256 this.getElementDocument().removeEventListener( 'mouseup', this.onBlurHandler
, true );
9257 this.$element
.removeClass(
9258 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
9260 this.toggleClipping( false );
9266 * Drop down list layout of tools as labeled icon buttons.
9268 * This layout allows some tools to be collapsible, controlled by a "More" / "Fewer" option at the
9269 * bottom of the main list. These are not automatically positioned at the bottom of the list; you
9270 * may want to use the 'promote' and 'demote' configuration options to achieve this.
9273 * @extends OO.ui.PopupToolGroup
9276 * @param {OO.ui.Toolbar} toolbar
9277 * @param {Object} [config] Configuration options
9278 * @cfg {Array} [allowCollapse] List of tools that can be collapsed. Remaining tools will be always
9280 * @cfg {Array} [forceExpand] List of tools that *may not* be collapsed. All remaining tools will be
9281 * allowed to be collapsed.
9282 * @cfg {boolean} [expanded=false] Whether the collapsible tools are expanded by default
9284 OO
.ui
.ListToolGroup
= function OoUiListToolGroup( toolbar
, config
) {
9285 // Allow passing positional parameters inside the config object
9286 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
9288 toolbar
= config
.toolbar
;
9291 // Configuration initialization
9292 config
= config
|| {};
9294 // Properties (must be set before parent constructor, which calls #populate)
9295 this.allowCollapse
= config
.allowCollapse
;
9296 this.forceExpand
= config
.forceExpand
;
9297 this.expanded
= config
.expanded
!== undefined ? config
.expanded
: false;
9298 this.collapsibleTools
= [];
9300 // Parent constructor
9301 OO
.ui
.ListToolGroup
.super.call( this, toolbar
, config
);
9304 this.$element
.addClass( 'oo-ui-listToolGroup' );
9309 OO
.inheritClass( OO
.ui
.ListToolGroup
, OO
.ui
.PopupToolGroup
);
9311 /* Static Properties */
9313 OO
.ui
.ListToolGroup
.static.accelTooltips
= true;
9315 OO
.ui
.ListToolGroup
.static.name
= 'list';
9322 OO
.ui
.ListToolGroup
.prototype.populate = function () {
9323 var i
, len
, allowCollapse
= [];
9325 OO
.ui
.ListToolGroup
.super.prototype.populate
.call( this );
9327 // Update the list of collapsible tools
9328 if ( this.allowCollapse
!== undefined ) {
9329 allowCollapse
= this.allowCollapse
;
9330 } else if ( this.forceExpand
!== undefined ) {
9331 allowCollapse
= OO
.simpleArrayDifference( Object
.keys( this.tools
), this.forceExpand
);
9334 this.collapsibleTools
= [];
9335 for ( i
= 0, len
= allowCollapse
.length
; i
< len
; i
++ ) {
9336 if ( this.tools
[ allowCollapse
[ i
] ] !== undefined ) {
9337 this.collapsibleTools
.push( this.tools
[ allowCollapse
[ i
] ] );
9341 // Keep at the end, even when tools are added
9342 this.$group
.append( this.getExpandCollapseTool().$element
);
9344 this.getExpandCollapseTool().toggle( this.collapsibleTools
.length
!== 0 );
9345 this.updateCollapsibleState();
9348 OO
.ui
.ListToolGroup
.prototype.getExpandCollapseTool = function () {
9349 if ( this.expandCollapseTool
=== undefined ) {
9350 var ExpandCollapseTool = function () {
9351 ExpandCollapseTool
.super.apply( this, arguments
);
9354 OO
.inheritClass( ExpandCollapseTool
, OO
.ui
.Tool
);
9356 ExpandCollapseTool
.prototype.onSelect = function () {
9357 this.toolGroup
.expanded
= !this.toolGroup
.expanded
;
9358 this.toolGroup
.updateCollapsibleState();
9359 this.setActive( false );
9361 ExpandCollapseTool
.prototype.onUpdateState = function () {
9362 // Do nothing. Tool interface requires an implementation of this function.
9365 ExpandCollapseTool
.static.name
= 'more-fewer';
9367 this.expandCollapseTool
= new ExpandCollapseTool( this );
9369 return this.expandCollapseTool
;
9375 OO
.ui
.ListToolGroup
.prototype.onPointerUp = function ( e
) {
9376 var ret
= OO
.ui
.ListToolGroup
.super.prototype.onPointerUp
.call( this, e
);
9378 // Do not close the popup when the user wants to show more/fewer tools
9379 if ( $( e
.target
).closest( '.oo-ui-tool-name-more-fewer' ).length
) {
9380 // Prevent the popup list from being hidden
9381 this.setActive( true );
9387 OO
.ui
.ListToolGroup
.prototype.updateCollapsibleState = function () {
9390 this.getExpandCollapseTool()
9391 .setIcon( this.expanded
? 'collapse' : 'expand' )
9392 .setTitle( OO
.ui
.msg( this.expanded
? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
9394 for ( i
= 0, len
= this.collapsibleTools
.length
; i
< len
; i
++ ) {
9395 this.collapsibleTools
[ i
].toggle( this.expanded
);
9400 * Drop down menu layout of tools as selectable menu items.
9403 * @extends OO.ui.PopupToolGroup
9406 * @param {OO.ui.Toolbar} toolbar
9407 * @param {Object} [config] Configuration options
9409 OO
.ui
.MenuToolGroup
= function OoUiMenuToolGroup( toolbar
, config
) {
9410 // Allow passing positional parameters inside the config object
9411 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
9413 toolbar
= config
.toolbar
;
9416 // Configuration initialization
9417 config
= config
|| {};
9419 // Parent constructor
9420 OO
.ui
.MenuToolGroup
.super.call( this, toolbar
, config
);
9423 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
9426 this.$element
.addClass( 'oo-ui-menuToolGroup' );
9431 OO
.inheritClass( OO
.ui
.MenuToolGroup
, OO
.ui
.PopupToolGroup
);
9433 /* Static Properties */
9435 OO
.ui
.MenuToolGroup
.static.accelTooltips
= true;
9437 OO
.ui
.MenuToolGroup
.static.name
= 'menu';
9442 * Handle the toolbar state being updated.
9444 * When the state changes, the title of each active item in the menu will be joined together and
9445 * used as a label for the group. The label will be empty if none of the items are active.
9447 OO
.ui
.MenuToolGroup
.prototype.onUpdateState = function () {
9451 for ( name
in this.tools
) {
9452 if ( this.tools
[ name
].isActive() ) {
9453 labelTexts
.push( this.tools
[ name
].getTitle() );
9457 this.setLabel( labelTexts
.join( ', ' ) || ' ' );
9461 * Tool that shows a popup when selected.
9465 * @extends OO.ui.Tool
9466 * @mixins OO.ui.PopupElement
9469 * @param {OO.ui.ToolGroup} toolGroup
9470 * @param {Object} [config] Configuration options
9472 OO
.ui
.PopupTool
= function OoUiPopupTool( toolGroup
, config
) {
9473 // Allow passing positional parameters inside the config object
9474 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
9476 toolGroup
= config
.toolGroup
;
9479 // Parent constructor
9480 OO
.ui
.PopupTool
.super.call( this, toolGroup
, config
);
9482 // Mixin constructors
9483 OO
.ui
.PopupElement
.call( this, config
);
9487 .addClass( 'oo-ui-popupTool' )
9488 .append( this.popup
.$element
);
9493 OO
.inheritClass( OO
.ui
.PopupTool
, OO
.ui
.Tool
);
9494 OO
.mixinClass( OO
.ui
.PopupTool
, OO
.ui
.PopupElement
);
9499 * Handle the tool being selected.
9503 OO
.ui
.PopupTool
.prototype.onSelect = function () {
9504 if ( !this.isDisabled() ) {
9505 this.popup
.toggle();
9507 this.setActive( false );
9512 * Handle the toolbar state being updated.
9516 OO
.ui
.PopupTool
.prototype.onUpdateState = function () {
9517 this.setActive( false );
9521 * Tool that has a tool group inside. This is a bad workaround for the lack of proper hierarchical
9522 * menus in toolbars (T74159).
9526 * @extends OO.ui.Tool
9529 * @param {OO.ui.ToolGroup} toolGroup
9530 * @param {Object} [config] Configuration options
9532 OO
.ui
.ToolGroupTool
= function OoUiToolGroupTool( toolGroup
, config
) {
9533 // Allow passing positional parameters inside the config object
9534 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
9536 toolGroup
= config
.toolGroup
;
9539 // Parent constructor
9540 OO
.ui
.ToolGroupTool
.super.call( this, toolGroup
, config
);
9543 this.innerToolGroup
= this.createGroup( this.constructor.static.groupConfig
);
9546 this.$link
.remove();
9548 .addClass( 'oo-ui-toolGroupTool' )
9549 .append( this.innerToolGroup
.$element
);
9554 OO
.inheritClass( OO
.ui
.ToolGroupTool
, OO
.ui
.Tool
);
9556 /* Static Properties */
9559 * Tool group configuration. See OO.ui.Toolbar#setup for the accepted values.
9561 * @property {Object.<string,Array>}
9563 OO
.ui
.ToolGroupTool
.static.groupConfig
= {};
9568 * Handle the tool being selected.
9572 OO
.ui
.ToolGroupTool
.prototype.onSelect = function () {
9573 this.innerToolGroup
.setActive( !this.innerToolGroup
.active
);
9578 * Handle the toolbar state being updated.
9582 OO
.ui
.ToolGroupTool
.prototype.onUpdateState = function () {
9583 this.setActive( false );
9587 * Build a OO.ui.ToolGroup from the configuration.
9589 * @param {Object.<string,Array>} group Tool group configuration. See OO.ui.Toolbar#setup for the
9591 * @return {OO.ui.ListToolGroup}
9593 OO
.ui
.ToolGroupTool
.prototype.createGroup = function ( group
) {
9594 if ( group
.include
=== '*' ) {
9595 // Apply defaults to catch-all groups
9596 if ( group
.label
=== undefined ) {
9597 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
9601 return this.toolbar
.getToolGroupFactory().create( 'list', this.toolbar
, group
);
9605 * Mixin for OO.ui.Widget subclasses to provide OO.ui.GroupElement.
9607 * Use together with OO.ui.ItemWidget to make disabled state inheritable.
9612 * @extends OO.ui.GroupElement
9615 * @param {Object} [config] Configuration options
9617 OO
.ui
.GroupWidget
= function OoUiGroupWidget( config
) {
9618 // Parent constructor
9619 OO
.ui
.GroupWidget
.super.call( this, config
);
9624 OO
.inheritClass( OO
.ui
.GroupWidget
, OO
.ui
.GroupElement
);
9629 * Set the disabled state of the widget.
9631 * This will also update the disabled state of child widgets.
9633 * @param {boolean} disabled Disable widget
9636 OO
.ui
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
9640 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
9641 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
9643 // During construction, #setDisabled is called before the OO.ui.GroupElement constructor
9645 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
9646 this.items
[ i
].updateDisabled();
9654 * Mixin for widgets used as items in widgets that inherit OO.ui.GroupWidget.
9656 * Item widgets have a reference to a OO.ui.GroupWidget while they are attached to the group. This
9657 * allows bidirectional communication.
9659 * Use together with OO.ui.GroupWidget to make disabled state inheritable.
9667 OO
.ui
.ItemWidget
= function OoUiItemWidget() {
9674 * Check if widget is disabled.
9676 * Checks parent if present, making disabled state inheritable.
9678 * @return {boolean} Widget is disabled
9680 OO
.ui
.ItemWidget
.prototype.isDisabled = function () {
9681 return this.disabled
||
9682 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
9686 * Set group element is in.
9688 * @param {OO.ui.GroupElement|null} group Group element, null if none
9691 OO
.ui
.ItemWidget
.prototype.setElementGroup = function ( group
) {
9693 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
9694 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
9696 // Initialize item disabled states
9697 this.updateDisabled();
9703 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
9704 * Controls include moving items up and down, removing items, and adding different kinds of items.
9705 * ####Currently, this class is only used by {@link OO.ui.BookletLayout BookletLayouts}.####
9708 * @extends OO.ui.Widget
9709 * @mixins OO.ui.GroupElement
9710 * @mixins OO.ui.IconElement
9713 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
9714 * @param {Object} [config] Configuration options
9716 OO
.ui
.OutlineControlsWidget
= function OoUiOutlineControlsWidget( outline
, config
) {
9717 // Allow passing positional parameters inside the config object
9718 if ( OO
.isPlainObject( outline
) && config
=== undefined ) {
9720 outline
= config
.outline
;
9723 // Configuration initialization
9724 config
= $.extend( { icon
: 'add' }, config
);
9726 // Parent constructor
9727 OO
.ui
.OutlineControlsWidget
.super.call( this, config
);
9729 // Mixin constructors
9730 OO
.ui
.GroupElement
.call( this, config
);
9731 OO
.ui
.IconElement
.call( this, config
);
9734 this.outline
= outline
;
9735 this.$movers
= $( '<div>' );
9736 this.upButton
= new OO
.ui
.ButtonWidget( {
9739 title
: OO
.ui
.msg( 'ooui-outline-control-move-up' )
9741 this.downButton
= new OO
.ui
.ButtonWidget( {
9744 title
: OO
.ui
.msg( 'ooui-outline-control-move-down' )
9746 this.removeButton
= new OO
.ui
.ButtonWidget( {
9749 title
: OO
.ui
.msg( 'ooui-outline-control-remove' )
9753 outline
.connect( this, {
9754 select
: 'onOutlineChange',
9755 add
: 'onOutlineChange',
9756 remove
: 'onOutlineChange'
9758 this.upButton
.connect( this, { click
: [ 'emit', 'move', -1 ] } );
9759 this.downButton
.connect( this, { click
: [ 'emit', 'move', 1 ] } );
9760 this.removeButton
.connect( this, { click
: [ 'emit', 'remove' ] } );
9763 this.$element
.addClass( 'oo-ui-outlineControlsWidget' );
9764 this.$group
.addClass( 'oo-ui-outlineControlsWidget-items' );
9766 .addClass( 'oo-ui-outlineControlsWidget-movers' )
9767 .append( this.removeButton
.$element
, this.upButton
.$element
, this.downButton
.$element
);
9768 this.$element
.append( this.$icon
, this.$group
, this.$movers
);
9773 OO
.inheritClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.Widget
);
9774 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.GroupElement
);
9775 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.IconElement
);
9781 * @param {number} places Number of places to move
9793 * Handle outline change events.
9795 OO
.ui
.OutlineControlsWidget
.prototype.onOutlineChange = function () {
9796 var i
, len
, firstMovable
, lastMovable
,
9797 items
= this.outline
.getItems(),
9798 selectedItem
= this.outline
.getSelectedItem(),
9799 movable
= selectedItem
&& selectedItem
.isMovable(),
9800 removable
= selectedItem
&& selectedItem
.isRemovable();
9805 while ( ++i
< len
) {
9806 if ( items
[ i
].isMovable() ) {
9807 firstMovable
= items
[ i
];
9813 if ( items
[ i
].isMovable() ) {
9814 lastMovable
= items
[ i
];
9819 this.upButton
.setDisabled( !movable
|| selectedItem
=== firstMovable
);
9820 this.downButton
.setDisabled( !movable
|| selectedItem
=== lastMovable
);
9821 this.removeButton
.setDisabled( !removable
);
9825 * ToggleWidget is mixed into other classes to create widgets with an on/off state.
9826 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
9832 * @param {Object} [config] Configuration options
9833 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
9834 * By default, the toggle is in the 'off' state.
9836 OO
.ui
.ToggleWidget
= function OoUiToggleWidget( config
) {
9837 // Configuration initialization
9838 config
= config
|| {};
9844 this.$element
.addClass( 'oo-ui-toggleWidget' );
9845 this.setValue( !!config
.value
);
9853 * A change event is emitted when the on/off state of the toggle changes.
9855 * @param {boolean} value Value representing the new state of the toggle
9861 * Get the value representing the toggle’s state.
9863 * @return {boolean} The on/off state of the toggle
9865 OO
.ui
.ToggleWidget
.prototype.getValue = function () {
9870 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
9872 * @param {boolean} value The state of the toggle
9876 OO
.ui
.ToggleWidget
.prototype.setValue = function ( value
) {
9878 if ( this.value
!== value
) {
9880 this.emit( 'change', value
);
9881 this.$element
.toggleClass( 'oo-ui-toggleWidget-on', value
);
9882 this.$element
.toggleClass( 'oo-ui-toggleWidget-off', !value
);
9883 this.$element
.attr( 'aria-checked', value
.toString() );
9889 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
9890 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
9891 * removed, and cleared from the group.
9894 * // Example: A ButtonGroupWidget with two buttons
9895 * var button1 = new OO.ui.PopupButtonWidget( {
9896 * label: 'Select a category',
9899 * $content: $( '<p>List of categories...</p>' ),
9904 * var button2 = new OO.ui.ButtonWidget( {
9907 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
9908 * items: [button1, button2]
9910 * $( 'body' ).append( buttonGroup.$element );
9913 * @extends OO.ui.Widget
9914 * @mixins OO.ui.GroupElement
9917 * @param {Object} [config] Configuration options
9918 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
9920 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
9921 // Configuration initialization
9922 config
= config
|| {};
9924 // Parent constructor
9925 OO
.ui
.ButtonGroupWidget
.super.call( this, config
);
9927 // Mixin constructors
9928 OO
.ui
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
9931 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
9932 if ( Array
.isArray( config
.items
) ) {
9933 this.addItems( config
.items
);
9939 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
9940 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.GroupElement
);
9943 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
9944 * feels, and functionality can be customized via the class’s configuration options
9945 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
9948 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
9951 * // A button widget
9952 * var button = new OO.ui.ButtonWidget( {
9953 * label: 'Button with Icon',
9955 * iconTitle: 'Remove'
9957 * $( 'body' ).append( button.$element );
9959 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
9962 * @extends OO.ui.Widget
9963 * @mixins OO.ui.ButtonElement
9964 * @mixins OO.ui.IconElement
9965 * @mixins OO.ui.IndicatorElement
9966 * @mixins OO.ui.LabelElement
9967 * @mixins OO.ui.TitledElement
9968 * @mixins OO.ui.FlaggedElement
9969 * @mixins OO.ui.TabIndexedElement
9972 * @param {Object} [config] Configuration options
9973 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
9974 * @cfg {string} [target] The frame or window in which to open the hyperlink.
9975 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
9977 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
9978 // Configuration initialization
9979 // FIXME: The `nofollow` alias is deprecated and will be removed (T89767)
9980 config
= $.extend( { noFollow
: config
&& config
.nofollow
}, config
);
9982 // Parent constructor
9983 OO
.ui
.ButtonWidget
.super.call( this, config
);
9985 // Mixin constructors
9986 OO
.ui
.ButtonElement
.call( this, config
);
9987 OO
.ui
.IconElement
.call( this, config
);
9988 OO
.ui
.IndicatorElement
.call( this, config
);
9989 OO
.ui
.LabelElement
.call( this, config
);
9990 OO
.ui
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
9991 OO
.ui
.FlaggedElement
.call( this, config
);
9992 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
9997 this.noFollow
= false;
9998 this.isHyperlink
= false;
10001 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
10003 .addClass( 'oo-ui-buttonWidget' )
10004 .append( this.$button
);
10005 this.setHref( config
.href
);
10006 this.setTarget( config
.target
);
10007 this.setNoFollow( config
.noFollow
);
10012 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
10013 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.ButtonElement
);
10014 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.IconElement
);
10015 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.IndicatorElement
);
10016 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.LabelElement
);
10017 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.TitledElement
);
10018 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.FlaggedElement
);
10019 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.TabIndexedElement
);
10026 OO
.ui
.ButtonWidget
.prototype.onMouseDown = function ( e
) {
10027 if ( !this.isDisabled() ) {
10028 // Remove the tab-index while the button is down to prevent the button from stealing focus
10029 this.$button
.removeAttr( 'tabindex' );
10032 return OO
.ui
.ButtonElement
.prototype.onMouseDown
.call( this, e
);
10038 OO
.ui
.ButtonWidget
.prototype.onMouseUp = function ( e
) {
10039 if ( !this.isDisabled() ) {
10040 // Restore the tab-index after the button is up to restore the button's accessibility
10041 this.$button
.attr( 'tabindex', this.tabIndex
);
10044 return OO
.ui
.ButtonElement
.prototype.onMouseUp
.call( this, e
);
10050 OO
.ui
.ButtonWidget
.prototype.onClick = function ( e
) {
10051 var ret
= OO
.ui
.ButtonElement
.prototype.onClick
.call( this, e
);
10052 if ( this.isHyperlink
) {
10061 OO
.ui
.ButtonWidget
.prototype.onKeyPress = function ( e
) {
10062 var ret
= OO
.ui
.ButtonElement
.prototype.onKeyPress
.call( this, e
);
10063 if ( this.isHyperlink
) {
10070 * Get hyperlink location.
10072 * @return {string} Hyperlink location
10074 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
10079 * Get hyperlink target.
10081 * @return {string} Hyperlink target
10083 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
10084 return this.target
;
10088 * Get search engine traversal hint.
10090 * @return {boolean} Whether search engines should avoid traversing this hyperlink
10092 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
10093 return this.noFollow
;
10097 * Set hyperlink location.
10099 * @param {string|null} href Hyperlink location, null to remove
10101 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
10102 href
= typeof href
=== 'string' ? href
: null;
10104 if ( href
!== this.href
) {
10106 if ( href
!== null ) {
10107 this.$button
.attr( 'href', href
);
10108 this.isHyperlink
= true;
10110 this.$button
.removeAttr( 'href' );
10111 this.isHyperlink
= false;
10119 * Set hyperlink target.
10121 * @param {string|null} target Hyperlink target, null to remove
10123 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
10124 target
= typeof target
=== 'string' ? target
: null;
10126 if ( target
!== this.target
) {
10127 this.target
= target
;
10128 if ( target
!== null ) {
10129 this.$button
.attr( 'target', target
);
10131 this.$button
.removeAttr( 'target' );
10139 * Set search engine traversal hint.
10141 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
10143 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
10144 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
10146 if ( noFollow
!== this.noFollow
) {
10147 this.noFollow
= noFollow
;
10149 this.$button
.attr( 'rel', 'nofollow' );
10151 this.$button
.removeAttr( 'rel' );
10159 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
10160 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
10163 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
10164 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
10167 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
10170 * @extends OO.ui.ButtonWidget
10171 * @mixins OO.ui.PendingElement
10174 * @param {Object} [config] Configuration options
10175 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
10176 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
10177 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
10178 * for more information about setting modes.
10179 * @cfg {boolean} [framed=false] Render the action button with a frame
10181 OO
.ui
.ActionWidget
= function OoUiActionWidget( config
) {
10182 // Configuration initialization
10183 config
= $.extend( { framed
: false }, config
);
10185 // Parent constructor
10186 OO
.ui
.ActionWidget
.super.call( this, config
);
10188 // Mixin constructors
10189 OO
.ui
.PendingElement
.call( this, config
);
10192 this.action
= config
.action
|| '';
10193 this.modes
= config
.modes
|| [];
10198 this.$element
.addClass( 'oo-ui-actionWidget' );
10203 OO
.inheritClass( OO
.ui
.ActionWidget
, OO
.ui
.ButtonWidget
);
10204 OO
.mixinClass( OO
.ui
.ActionWidget
, OO
.ui
.PendingElement
);
10209 * A resize event is emitted when the size of the widget changes.
10217 * Check if the action is configured to be available in the specified `mode`.
10219 * @param {string} mode Name of mode
10220 * @return {boolean} The action is configured with the mode
10222 OO
.ui
.ActionWidget
.prototype.hasMode = function ( mode
) {
10223 return this.modes
.indexOf( mode
) !== -1;
10227 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
10231 OO
.ui
.ActionWidget
.prototype.getAction = function () {
10232 return this.action
;
10236 * Get the symbolic name of the mode or modes for which the action is configured to be available.
10238 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
10239 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
10242 * @return {string[]}
10244 OO
.ui
.ActionWidget
.prototype.getModes = function () {
10245 return this.modes
.slice();
10249 * Emit a resize event if the size has changed.
10254 OO
.ui
.ActionWidget
.prototype.propagateResize = function () {
10257 if ( this.isElementAttached() ) {
10258 width
= this.$element
.width();
10259 height
= this.$element
.height();
10261 if ( width
!== this.width
|| height
!== this.height
) {
10262 this.width
= width
;
10263 this.height
= height
;
10264 this.emit( 'resize' );
10274 OO
.ui
.ActionWidget
.prototype.setIcon = function () {
10276 OO
.ui
.IconElement
.prototype.setIcon
.apply( this, arguments
);
10277 this.propagateResize();
10285 OO
.ui
.ActionWidget
.prototype.setLabel = function () {
10287 OO
.ui
.LabelElement
.prototype.setLabel
.apply( this, arguments
);
10288 this.propagateResize();
10296 OO
.ui
.ActionWidget
.prototype.setFlags = function () {
10298 OO
.ui
.FlaggedElement
.prototype.setFlags
.apply( this, arguments
);
10299 this.propagateResize();
10307 OO
.ui
.ActionWidget
.prototype.clearFlags = function () {
10309 OO
.ui
.FlaggedElement
.prototype.clearFlags
.apply( this, arguments
);
10310 this.propagateResize();
10316 * Toggle the visibility of the action button.
10318 * @param {boolean} [show] Show button, omit to toggle visibility
10321 OO
.ui
.ActionWidget
.prototype.toggle = function () {
10323 OO
.ui
.ActionWidget
.super.prototype.toggle
.apply( this, arguments
);
10324 this.propagateResize();
10330 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
10331 * which is used to display additional information or options.
10334 * // Example of a popup button.
10335 * var popupButton = new OO.ui.PopupButtonWidget( {
10336 * label: 'Popup button with options',
10339 * $content: $( '<p>Additional options here.</p>' ),
10344 * // Append the button to the DOM.
10345 * $( 'body' ).append( popupButton.$element );
10348 * @extends OO.ui.ButtonWidget
10349 * @mixins OO.ui.PopupElement
10352 * @param {Object} [config] Configuration options
10354 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
10355 // Parent constructor
10356 OO
.ui
.PopupButtonWidget
.super.call( this, config
);
10358 // Mixin constructors
10359 OO
.ui
.PopupElement
.call( this, config
);
10362 this.connect( this, { click
: 'onAction' } );
10366 .addClass( 'oo-ui-popupButtonWidget' )
10367 .attr( 'aria-haspopup', 'true' )
10368 .append( this.popup
.$element
);
10373 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
10374 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.PopupElement
);
10379 * Handle the button action being triggered.
10383 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
10384 this.popup
.toggle();
10388 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
10389 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
10390 * configured with {@link OO.ui.IconElement icons}, {@link OO.ui.IndicatorElement indicators},
10391 * {@link OO.ui.TitledElement titles}, {@link OO.ui.FlaggedElement styling flags},
10392 * and {@link OO.ui.LabelElement labels}. Please see
10393 * the [OOjs UI documentation][1] on MediaWiki for more information.
10396 * // Toggle buttons in the 'off' and 'on' state.
10397 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
10398 * label: 'Toggle Button off'
10400 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
10401 * label: 'Toggle Button on',
10404 * // Append the buttons to the DOM.
10405 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
10407 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
10410 * @extends OO.ui.ButtonWidget
10411 * @mixins OO.ui.ToggleWidget
10414 * @param {Object} [config] Configuration options
10415 * @cfg {boolean} [value=false] The toggle button’s initial on/off
10416 * state. By default, the button is in the 'off' state.
10418 OO
.ui
.ToggleButtonWidget
= function OoUiToggleButtonWidget( config
) {
10419 // Configuration initialization
10420 config
= config
|| {};
10422 // Parent constructor
10423 OO
.ui
.ToggleButtonWidget
.super.call( this, config
);
10425 // Mixin constructors
10426 OO
.ui
.ToggleWidget
.call( this, config
);
10429 this.connect( this, { click
: 'onAction' } );
10432 this.$element
.addClass( 'oo-ui-toggleButtonWidget' );
10437 OO
.inheritClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.ButtonWidget
);
10438 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.ToggleWidget
);
10445 * Handle the button action being triggered.
10447 OO
.ui
.ToggleButtonWidget
.prototype.onAction = function () {
10448 this.setValue( !this.value
);
10454 OO
.ui
.ToggleButtonWidget
.prototype.setValue = function ( value
) {
10456 if ( value
!== this.value
) {
10457 this.$button
.attr( 'aria-pressed', value
.toString() );
10458 this.setActive( value
);
10461 // Parent method (from mixin)
10462 OO
.ui
.ToggleWidget
.prototype.setValue
.call( this, value
);
10468 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
10469 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
10470 * users can interact with it.
10473 * // Example: A DropdownWidget with a menu that contains three options
10474 * var dropDown = new OO.ui.DropdownWidget( {
10475 * label: 'Dropdown menu: Select a menu option',
10478 * new OO.ui.MenuOptionWidget( {
10482 * new OO.ui.MenuOptionWidget( {
10486 * new OO.ui.MenuOptionWidget( {
10494 * $( 'body' ).append( dropDown.$element );
10496 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
10498 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
10501 * @extends OO.ui.Widget
10502 * @mixins OO.ui.IconElement
10503 * @mixins OO.ui.IndicatorElement
10504 * @mixins OO.ui.LabelElement
10505 * @mixins OO.ui.TitledElement
10506 * @mixins OO.ui.TabIndexedElement
10509 * @param {Object} [config] Configuration options
10510 * @cfg {Object} [menu] Configuration options to pass to menu widget
10512 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
10513 // Configuration initialization
10514 config
= $.extend( { indicator
: 'down' }, config
);
10516 // Parent constructor
10517 OO
.ui
.DropdownWidget
.super.call( this, config
);
10519 // Properties (must be set before TabIndexedElement constructor call)
10520 this.$handle
= this.$( '<span>' );
10522 // Mixin constructors
10523 OO
.ui
.IconElement
.call( this, config
);
10524 OO
.ui
.IndicatorElement
.call( this, config
);
10525 OO
.ui
.LabelElement
.call( this, config
);
10526 OO
.ui
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
10527 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
10530 this.menu
= new OO
.ui
.MenuSelectWidget( $.extend( { widget
: this }, config
.menu
) );
10534 click
: this.onClick
.bind( this ),
10535 keypress
: this.onKeyPress
.bind( this )
10537 this.menu
.connect( this, { select
: 'onMenuSelect' } );
10541 .addClass( 'oo-ui-dropdownWidget-handle' )
10542 .append( this.$icon
, this.$label
, this.$indicator
);
10544 .addClass( 'oo-ui-dropdownWidget' )
10545 .append( this.$handle
, this.menu
.$element
);
10550 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
10551 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.IconElement
);
10552 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.IndicatorElement
);
10553 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.LabelElement
);
10554 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.TitledElement
);
10555 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.TabIndexedElement
);
10562 * @return {OO.ui.MenuSelectWidget} Menu of widget
10564 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
10569 * Handles menu select events.
10572 * @param {OO.ui.MenuOptionWidget} item Selected menu item
10574 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
10581 selectedLabel
= item
.getLabel();
10583 // If the label is a DOM element, clone it, because setLabel will append() it
10584 if ( selectedLabel
instanceof jQuery
) {
10585 selectedLabel
= selectedLabel
.clone();
10588 this.setLabel( selectedLabel
);
10592 * Handle mouse click events.
10595 * @param {jQuery.Event} e Mouse click event
10597 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
10598 if ( !this.isDisabled() && e
.which
=== 1 ) {
10599 this.menu
.toggle();
10605 * Handle key press events.
10608 * @param {jQuery.Event} e Key press event
10610 OO
.ui
.DropdownWidget
.prototype.onKeyPress = function ( e
) {
10611 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
10612 this.menu
.toggle();
10618 * IconWidget is a generic widget for {@link OO.ui.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
10619 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
10620 * for a list of icons included in the library.
10623 * // An icon widget with a label
10624 * var myIcon = new OO.ui.IconWidget( {
10626 * iconTitle: 'Help'
10628 * // Create a label.
10629 * var iconLabel = new OO.ui.LabelWidget( {
10632 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
10634 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
10637 * @extends OO.ui.Widget
10638 * @mixins OO.ui.IconElement
10639 * @mixins OO.ui.TitledElement
10642 * @param {Object} [config] Configuration options
10644 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
10645 // Configuration initialization
10646 config
= config
|| {};
10648 // Parent constructor
10649 OO
.ui
.IconWidget
.super.call( this, config
);
10651 // Mixin constructors
10652 OO
.ui
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
10653 OO
.ui
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
10656 this.$element
.addClass( 'oo-ui-iconWidget' );
10661 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
10662 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.IconElement
);
10663 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.TitledElement
);
10665 /* Static Properties */
10667 OO
.ui
.IconWidget
.static.tagName
= 'span';
10670 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
10671 * attention to the status of an item or to clarify the function of a control. For a list of
10672 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
10675 * // Example of an indicator widget
10676 * var indicator1 = new OO.ui.IndicatorWidget( {
10677 * indicator: 'alert'
10680 * // Create a fieldset layout to add a label
10681 * var fieldset = new OO.ui.FieldsetLayout();
10682 * fieldset.addItems( [
10683 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
10685 * $( 'body' ).append( fieldset.$element );
10687 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
10690 * @extends OO.ui.Widget
10691 * @mixins OO.ui.IndicatorElement
10692 * @mixins OO.ui.TitledElement
10695 * @param {Object} [config] Configuration options
10697 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
10698 // Configuration initialization
10699 config
= config
|| {};
10701 // Parent constructor
10702 OO
.ui
.IndicatorWidget
.super.call( this, config
);
10704 // Mixin constructors
10705 OO
.ui
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
10706 OO
.ui
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
10709 this.$element
.addClass( 'oo-ui-indicatorWidget' );
10714 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
10715 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.IndicatorElement
);
10716 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.TitledElement
);
10718 /* Static Properties */
10720 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
10723 * InputWidget is the base class for all input widgets, which
10724 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
10725 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
10726 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
10728 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
10732 * @extends OO.ui.Widget
10733 * @mixins OO.ui.FlaggedElement
10734 * @mixins OO.ui.TabIndexedElement
10737 * @param {Object} [config] Configuration options
10738 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
10739 * @cfg {string} [value=''] The value of the input.
10740 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
10741 * before it is accepted.
10743 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
10744 // Configuration initialization
10745 config
= config
|| {};
10747 // Parent constructor
10748 OO
.ui
.InputWidget
.super.call( this, config
);
10751 this.$input
= this.getInputElement( config
);
10753 this.inputFilter
= config
.inputFilter
;
10755 // Mixin constructors
10756 OO
.ui
.FlaggedElement
.call( this, config
);
10757 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
10760 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
10764 .attr( 'name', config
.name
)
10765 .prop( 'disabled', this.isDisabled() );
10766 this.$element
.addClass( 'oo-ui-inputWidget' ).append( this.$input
, $( '<span>' ) );
10767 this.setValue( config
.value
);
10772 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
10773 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.FlaggedElement
);
10774 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.TabIndexedElement
);
10781 * A change event is emitted when the value of the input changes.
10783 * @param {string} value
10789 * Get input element.
10791 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
10792 * different circumstances. The element must have a `value` property (like form elements).
10795 * @param {Object} config Configuration options
10796 * @return {jQuery} Input element
10798 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
10799 return $( '<input>' );
10803 * Handle potentially value-changing events.
10806 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
10808 OO
.ui
.InputWidget
.prototype.onEdit = function () {
10810 if ( !this.isDisabled() ) {
10811 // Allow the stack to clear so the value will be updated
10812 setTimeout( function () {
10813 widget
.setValue( widget
.$input
.val() );
10819 * Get the value of the input.
10821 * @return {string} Input value
10823 OO
.ui
.InputWidget
.prototype.getValue = function () {
10824 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
10825 // it, and we won't know unless they're kind enough to trigger a 'change' event.
10826 var value
= this.$input
.val();
10827 if ( this.value
!== value
) {
10828 this.setValue( value
);
10834 * Set the direction of the input, either RTL (right-to-left) or LTR (left-to-right).
10836 * @param {boolean} isRTL
10837 * Direction is right-to-left
10839 OO
.ui
.InputWidget
.prototype.setRTL = function ( isRTL
) {
10840 this.$input
.prop( 'dir', isRTL
? 'rtl' : 'ltr' );
10844 * Set the value of the input.
10846 * @param {string} value New value
10850 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
10851 value
= this.cleanUpValue( value
);
10852 // Update the DOM if it has changed. Note that with cleanUpValue, it
10853 // is possible for the DOM value to change without this.value changing.
10854 if ( this.$input
.val() !== value
) {
10855 this.$input
.val( value
);
10857 if ( this.value
!== value
) {
10858 this.value
= value
;
10859 this.emit( 'change', this.value
);
10865 * Clean up incoming value.
10867 * Ensures value is a string, and converts undefined and null to empty string.
10870 * @param {string} value Original value
10871 * @return {string} Cleaned up value
10873 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
10874 if ( value
=== undefined || value
=== null ) {
10876 } else if ( this.inputFilter
) {
10877 return this.inputFilter( String( value
) );
10879 return String( value
);
10884 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
10885 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
10888 OO
.ui
.InputWidget
.prototype.simulateLabelClick = function () {
10889 if ( !this.isDisabled() ) {
10890 if ( this.$input
.is( ':checkbox, :radio' ) ) {
10891 this.$input
.click();
10893 if ( this.$input
.is( ':input' ) ) {
10894 this.$input
[ 0 ].focus();
10902 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
10903 OO
.ui
.InputWidget
.super.prototype.setDisabled
.call( this, state
);
10904 if ( this.$input
) {
10905 this.$input
.prop( 'disabled', this.isDisabled() );
10915 OO
.ui
.InputWidget
.prototype.focus = function () {
10916 this.$input
[ 0 ].focus();
10925 OO
.ui
.InputWidget
.prototype.blur = function () {
10926 this.$input
[ 0 ].blur();
10931 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
10932 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
10933 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
10934 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
10935 * [OOjs UI documentation on MediaWiki] [1] for more information.
10938 * // A ButtonInputWidget rendered as an HTML button, the default.
10939 * var button = new OO.ui.ButtonInputWidget( {
10940 * label: 'Input button',
10944 * $( 'body' ).append( button.$element );
10946 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
10949 * @extends OO.ui.InputWidget
10950 * @mixins OO.ui.ButtonElement
10951 * @mixins OO.ui.IconElement
10952 * @mixins OO.ui.IndicatorElement
10953 * @mixins OO.ui.LabelElement
10954 * @mixins OO.ui.TitledElement
10955 * @mixins OO.ui.FlaggedElement
10958 * @param {Object} [config] Configuration options
10959 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
10960 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
10961 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
10962 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
10963 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
10965 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
10966 // Configuration initialization
10967 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
10969 // Properties (must be set before parent constructor, which calls #setValue)
10970 this.useInputTag
= config
.useInputTag
;
10972 // Parent constructor
10973 OO
.ui
.ButtonInputWidget
.super.call( this, config
);
10975 // Mixin constructors
10976 OO
.ui
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
10977 OO
.ui
.IconElement
.call( this, config
);
10978 OO
.ui
.IndicatorElement
.call( this, config
);
10979 OO
.ui
.LabelElement
.call( this, config
);
10980 OO
.ui
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
10981 OO
.ui
.FlaggedElement
.call( this, config
);
10984 if ( !config
.useInputTag
) {
10985 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
10987 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
10992 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
10993 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.ButtonElement
);
10994 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.IconElement
);
10995 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.IndicatorElement
);
10996 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.LabelElement
);
10997 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.TitledElement
);
10998 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.FlaggedElement
);
11006 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
11007 var html
= '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + config
.type
+ '">';
11014 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
11016 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
11017 * text, or `null` for no label
11020 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
11021 OO
.ui
.LabelElement
.prototype.setLabel
.call( this, label
);
11023 if ( this.useInputTag
) {
11024 if ( typeof label
=== 'function' ) {
11025 label
= OO
.ui
.resolveMsg( label
);
11027 if ( label
instanceof jQuery
) {
11028 label
= label
.text();
11033 this.$input
.val( label
);
11040 * Set the value of the input.
11042 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
11043 * they do not support {@link #value values}.
11045 * @param {string} value New value
11048 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
11049 if ( !this.useInputTag
) {
11050 OO
.ui
.ButtonInputWidget
.super.prototype.setValue
.call( this, value
);
11056 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
11057 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
11058 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
11059 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
11062 * // An example of selected, unselected, and disabled checkbox inputs
11063 * var checkbox1=new OO.ui.CheckboxInputWidget( {
11067 * var checkbox2=new OO.ui.CheckboxInputWidget( {
11070 * var checkbox3=new OO.ui.CheckboxInputWidget( {
11074 * // Create a fieldset layout with fields for each checkbox.
11075 * var fieldset = new OO.ui.FieldsetLayout( {
11076 * label: 'Checkboxes'
11078 * fieldset.addItems( [
11079 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
11080 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
11081 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
11083 * $( 'body' ).append( fieldset.$element );
11085 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11088 * @extends OO.ui.InputWidget
11091 * @param {Object} [config] Configuration options
11092 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
11094 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
11095 // Configuration initialization
11096 config
= config
|| {};
11098 // Parent constructor
11099 OO
.ui
.CheckboxInputWidget
.super.call( this, config
);
11102 this.$element
.addClass( 'oo-ui-checkboxInputWidget' );
11103 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
11108 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
11116 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
11117 return $( '<input type="checkbox" />' );
11123 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
11125 if ( !this.isDisabled() ) {
11126 // Allow the stack to clear so the value will be updated
11127 setTimeout( function () {
11128 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
11134 * Set selection state of this checkbox.
11136 * @param {boolean} state `true` for selected
11139 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
11141 if ( this.selected
!== state
) {
11142 this.selected
= state
;
11143 this.$input
.prop( 'checked', this.selected
);
11144 this.emit( 'change', this.selected
);
11150 * Check if this checkbox is selected.
11152 * @return {boolean} Checkbox is selected
11154 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
11155 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
11156 // it, and we won't know unless they're kind enough to trigger a 'change' event.
11157 var selected
= this.$input
.prop( 'checked' );
11158 if ( this.selected
!== selected
) {
11159 this.setSelected( selected
);
11161 return this.selected
;
11165 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
11166 * within a {@link OO.ui.FormLayout form}. The selected value is synchronized with the value
11167 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
11168 * more information about input widgets.
11171 * // Example: A DropdownInputWidget with three options
11172 * var dropDown = new OO.ui.DropdownInputWidget( {
11173 * label: 'Dropdown menu: Select a menu option',
11175 * { data: 'a', label: 'First' } ,
11176 * { data: 'b', label: 'Second'} ,
11177 * { data: 'c', label: 'Third' }
11180 * $( 'body' ).append( dropDown.$element );
11182 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11185 * @extends OO.ui.InputWidget
11188 * @param {Object} [config] Configuration options
11189 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
11191 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
11192 // Configuration initialization
11193 config
= config
|| {};
11195 // Properties (must be done before parent constructor which calls #setDisabled)
11196 this.dropdownWidget
= new OO
.ui
.DropdownWidget();
11198 // Parent constructor
11199 OO
.ui
.DropdownInputWidget
.super.call( this, config
);
11202 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
11205 this.setOptions( config
.options
|| [] );
11207 .addClass( 'oo-ui-dropdownInputWidget' )
11208 .append( this.dropdownWidget
.$element
);
11213 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
11221 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
11222 return $( '<input type="hidden">' );
11226 * Handles menu select events.
11229 * @param {OO.ui.MenuOptionWidget} item Selected menu item
11231 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
11232 this.setValue( item
.getData() );
11238 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
11239 var item
= this.dropdownWidget
.getMenu().getItemFromData( value
);
11241 this.dropdownWidget
.getMenu().selectItem( item
);
11243 OO
.ui
.DropdownInputWidget
.super.prototype.setValue
.call( this, value
);
11250 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
11251 this.dropdownWidget
.setDisabled( state
);
11252 OO
.ui
.DropdownInputWidget
.super.prototype.setDisabled
.call( this, state
);
11257 * Set the options available for this input.
11259 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
11262 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
11263 var value
= this.getValue();
11265 // Rebuild the dropdown menu
11266 this.dropdownWidget
.getMenu()
11268 .addItems( options
.map( function ( opt
) {
11269 return new OO
.ui
.MenuOptionWidget( {
11271 label
: opt
.label
!== undefined ? opt
.label
: opt
.data
11275 // Restore the previous value, or reset to something sensible
11276 if ( this.dropdownWidget
.getMenu().getItemFromData( value
) ) {
11277 // Previous value is still available, ensure consistency with the dropdown
11278 this.setValue( value
);
11280 // No longer valid, reset
11281 if ( options
.length
) {
11282 this.setValue( options
[ 0 ].data
);
11292 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
11293 this.dropdownWidget
.getMenu().toggle( true );
11300 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
11301 this.dropdownWidget
.getMenu().toggle( false );
11306 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
11307 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
11308 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
11309 * please see the [OOjs UI documentation on MediaWiki][1].
11312 * // An example of selected, unselected, and disabled radio inputs
11313 * var radio1 = new OO.ui.RadioInputWidget( {
11317 * var radio2 = new OO.ui.RadioInputWidget( {
11320 * var radio3 = new OO.ui.RadioInputWidget( {
11324 * // Create a fieldset layout with fields for each radio button.
11325 * var fieldset = new OO.ui.FieldsetLayout( {
11326 * label: 'Radio inputs'
11328 * fieldset.addItems( [
11329 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
11330 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
11331 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
11333 * $( 'body' ).append( fieldset.$element );
11335 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11338 * @extends OO.ui.InputWidget
11341 * @param {Object} [config] Configuration options
11342 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
11344 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
11345 // Configuration initialization
11346 config
= config
|| {};
11348 // Parent constructor
11349 OO
.ui
.RadioInputWidget
.super.call( this, config
);
11352 this.$element
.addClass( 'oo-ui-radioInputWidget' );
11353 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
11358 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
11366 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
11367 return $( '<input type="radio" />' );
11373 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
11374 // RadioInputWidget doesn't track its state.
11378 * Set selection state of this radio button.
11380 * @param {boolean} state `true` for selected
11383 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
11384 // RadioInputWidget doesn't track its state.
11385 this.$input
.prop( 'checked', state
);
11390 * Check if this radio button is selected.
11392 * @return {boolean} Radio is selected
11394 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
11395 return this.$input
.prop( 'checked' );
11399 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
11400 * size of the field as well as its presentation. In addition, these widgets can be configured
11401 * with {@link OO.ui.IconElement icons}, {@link OO.ui.IndicatorElement indicators}, an optional
11402 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
11403 * which modifies incoming values rather than validating them.
11404 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
11407 * // Example of a text input widget
11408 * var textInput = new OO.ui.TextInputWidget( {
11409 * value: 'Text input'
11411 * $( 'body' ).append( textInput.$element );
11413 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11416 * @extends OO.ui.InputWidget
11417 * @mixins OO.ui.IconElement
11418 * @mixins OO.ui.IndicatorElement
11419 * @mixins OO.ui.PendingElement
11420 * @mixins OO.ui.LabelElement
11423 * @param {Object} [config] Configuration options
11424 * @cfg {string} [type='text'] The value of the HTML `type` attribute
11425 * @cfg {string} [placeholder] Placeholder text
11426 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
11427 * instruct the browser to focus this widget.
11428 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
11429 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
11430 * @cfg {boolean} [multiline=false] Allow multiple lines of text
11431 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
11432 * Use the #maxRows config to specify a maximum number of displayed rows.
11433 * @cfg {boolean} [maxRows=10] Maximum number of rows to display when #autosize is set to true.
11434 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
11435 * the value or placeholder text: `'before'` or `'after'`
11436 * @cfg {boolean} [required=false] Mark the field as required
11437 * @cfg {RegExp|string} [validate] Validation pattern, either a regular expression or the
11438 * symbolic name of a pattern defined by the class: 'non-empty' (the value cannot be an empty string)
11439 * or 'integer' (the value must contain only numbers).
11441 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
11442 // Configuration initialization
11443 config
= $.extend( {
11445 labelPosition
: 'after',
11449 // Parent constructor
11450 OO
.ui
.TextInputWidget
.super.call( this, config
);
11452 // Mixin constructors
11453 OO
.ui
.IconElement
.call( this, config
);
11454 OO
.ui
.IndicatorElement
.call( this, config
);
11455 OO
.ui
.PendingElement
.call( this, config
);
11456 OO
.ui
.LabelElement
.call( this, config
);
11459 this.readOnly
= false;
11460 this.multiline
= !!config
.multiline
;
11461 this.autosize
= !!config
.autosize
;
11462 this.maxRows
= config
.maxRows
;
11463 this.validate
= null;
11465 // Clone for resizing
11466 if ( this.autosize
) {
11467 this.$clone
= this.$input
11469 .insertAfter( this.$input
)
11470 .attr( 'aria-hidden', 'true' )
11471 .addClass( 'oo-ui-element-hidden' );
11474 this.setValidation( config
.validate
);
11475 this.setLabelPosition( config
.labelPosition
);
11479 keypress
: this.onKeyPress
.bind( this ),
11480 blur
: this.setValidityFlag
.bind( this )
11483 focus
: this.onElementAttach
.bind( this )
11485 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
11486 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
11487 this.on( 'labelChange', this.updatePosition
.bind( this ) );
11491 .addClass( 'oo-ui-textInputWidget' )
11492 .append( this.$icon
, this.$indicator
);
11493 this.setReadOnly( !!config
.readOnly
);
11494 if ( config
.placeholder
) {
11495 this.$input
.attr( 'placeholder', config
.placeholder
);
11497 if ( config
.maxLength
!== undefined ) {
11498 this.$input
.attr( 'maxlength', config
.maxLength
);
11500 if ( config
.autofocus
) {
11501 this.$input
.attr( 'autofocus', 'autofocus' );
11503 if ( config
.required
) {
11504 this.$input
.attr( 'required', 'true' );
11506 if ( this.label
|| config
.autosize
) {
11507 this.installParentChangeDetector();
11513 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
11514 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.IconElement
);
11515 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.IndicatorElement
);
11516 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.PendingElement
);
11517 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.LabelElement
);
11519 /* Static properties */
11521 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
11529 * An `enter` event is emitted when the user presses 'enter' inside the text box.
11531 * Not emitted if the input is multiline.
11539 * Handle icon mouse down events.
11542 * @param {jQuery.Event} e Mouse down event
11545 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
11546 if ( e
.which
=== 1 ) {
11547 this.$input
[ 0 ].focus();
11553 * Handle indicator mouse down events.
11556 * @param {jQuery.Event} e Mouse down event
11559 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
11560 if ( e
.which
=== 1 ) {
11561 this.$input
[ 0 ].focus();
11567 * Handle key press events.
11570 * @param {jQuery.Event} e Key press event
11571 * @fires enter If enter key is pressed and input is not multiline
11573 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
11574 if ( e
.which
=== OO
.ui
.Keys
.ENTER
&& !this.multiline
) {
11575 this.emit( 'enter', e
);
11580 * Handle element attach events.
11583 * @param {jQuery.Event} e Element attach event
11585 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
11586 // Any previously calculated size is now probably invalid if we reattached elsewhere
11587 this.valCache
= null;
11589 this.positionLabel();
11595 OO
.ui
.TextInputWidget
.prototype.onEdit = function () {
11599 return OO
.ui
.TextInputWidget
.super.prototype.onEdit
.call( this );
11605 OO
.ui
.TextInputWidget
.prototype.setValue = function ( value
) {
11607 OO
.ui
.TextInputWidget
.super.prototype.setValue
.call( this, value
);
11609 this.setValidityFlag();
11615 * Check if the input is {@link #readOnly read-only}.
11617 * @return {boolean}
11619 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
11620 return this.readOnly
;
11624 * Set the {@link #readOnly read-only} state of the input.
11626 * @param {boolean} state Make input read-only
11629 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
11630 this.readOnly
= !!state
;
11631 this.$input
.prop( 'readOnly', this.readOnly
);
11636 * Support function for making #onElementAttach work across browsers.
11638 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
11639 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
11641 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
11642 * first time that the element gets attached to the documented.
11644 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
11645 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
11646 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
11649 if ( MutationObserver
) {
11650 // The new way. If only it wasn't so ugly.
11652 if ( this.$element
.closest( 'html' ).length
) {
11653 // Widget is attached already, do nothing. This breaks the functionality of this function when
11654 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
11655 // would require observation of the whole document, which would hurt performance of other,
11656 // more important code.
11660 // Find topmost node in the tree
11661 topmostNode
= this.$element
[0];
11662 while ( topmostNode
.parentNode
) {
11663 topmostNode
= topmostNode
.parentNode
;
11666 // We have no way to detect the $element being attached somewhere without observing the entire
11667 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
11668 // parent node of $element, and instead detect when $element is removed from it (and thus
11669 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
11670 // doesn't get attached, we end up back here and create the parent.
11672 mutationObserver
= new MutationObserver( function ( mutations
) {
11673 var i
, j
, removedNodes
;
11674 for ( i
= 0; i
< mutations
.length
; i
++ ) {
11675 removedNodes
= mutations
[ i
].removedNodes
;
11676 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
11677 if ( removedNodes
[ j
] === topmostNode
) {
11678 setTimeout( onRemove
, 0 );
11685 onRemove = function () {
11686 // If the node was attached somewhere else, report it
11687 if ( widget
.$element
.closest( 'html' ).length
) {
11688 widget
.onElementAttach();
11690 mutationObserver
.disconnect();
11691 widget
.installParentChangeDetector();
11694 // Create a fake parent and observe it
11695 fakeParentNode
= $( '<div>' ).append( this.$element
)[0];
11696 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
11698 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
11699 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
11700 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
11705 * Automatically adjust the size of the text input.
11707 * This only affects #multiline inputs that are {@link #autosize autosized}.
11711 OO
.ui
.TextInputWidget
.prototype.adjustSize = function () {
11712 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
, idealHeight
;
11714 if ( this.multiline
&& this.autosize
&& this.$input
.val() !== this.valCache
) {
11716 .val( this.$input
.val() )
11717 .attr( 'rows', '' )
11718 // Set inline height property to 0 to measure scroll height
11719 .css( 'height', 0 );
11721 this.$clone
.removeClass( 'oo-ui-element-hidden' );
11723 this.valCache
= this.$input
.val();
11725 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
11727 // Remove inline height property to measure natural heights
11728 this.$clone
.css( 'height', '' );
11729 innerHeight
= this.$clone
.innerHeight();
11730 outerHeight
= this.$clone
.outerHeight();
11732 // Measure max rows height
11734 .attr( 'rows', this.maxRows
)
11735 .css( 'height', 'auto' )
11737 maxInnerHeight
= this.$clone
.innerHeight();
11739 // Difference between reported innerHeight and scrollHeight with no scrollbars present
11740 // Equals 1 on Blink-based browsers and 0 everywhere else
11741 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
11742 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
11744 this.$clone
.addClass( 'oo-ui-element-hidden' );
11746 // Only apply inline height when expansion beyond natural height is needed
11747 if ( idealHeight
> innerHeight
) {
11748 // Use the difference between the inner and outer height as a buffer
11749 this.$input
.css( 'height', idealHeight
+ ( outerHeight
- innerHeight
) );
11751 this.$input
.css( 'height', '' );
11761 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
11762 return config
.multiline
? $( '<textarea>' ) : $( '<input type="' + config
.type
+ '" />' );
11766 * Check if the input supports multiple lines.
11768 * @return {boolean}
11770 OO
.ui
.TextInputWidget
.prototype.isMultiline = function () {
11771 return !!this.multiline
;
11775 * Check if the input automatically adjusts its size.
11777 * @return {boolean}
11779 OO
.ui
.TextInputWidget
.prototype.isAutosizing = function () {
11780 return !!this.autosize
;
11784 * Select the entire text of the input.
11788 OO
.ui
.TextInputWidget
.prototype.select = function () {
11789 this.$input
.select();
11794 * Set the validation pattern.
11796 * The validation pattern is either a regular expression or the symbolic name of a pattern
11797 * defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
11798 * value must contain only numbers).
11800 * @param {RegExp|string|null} validate Regular expression or the symbolic name of a
11801 * pattern (either ‘integer’ or ‘non-empty’) defined by the class.
11803 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
11804 if ( validate
instanceof RegExp
) {
11805 this.validate
= validate
;
11807 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
11812 * Sets the 'invalid' flag appropriately.
11814 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function () {
11816 this.isValid().done( function ( valid
) {
11817 widget
.setFlags( { invalid
: !valid
} );
11822 * Check if a value is valid.
11824 * This method returns a promise that resolves with a boolean `true` if the current value is
11825 * considered valid according to the supplied {@link #validate validation pattern}.
11827 * @return {jQuery.Deferred} A promise that resolves to a boolean `true` if the value is valid.
11829 OO
.ui
.TextInputWidget
.prototype.isValid = function () {
11830 return $.Deferred().resolve( !!this.getValue().match( this.validate
) ).promise();
11834 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
11836 * @param {string} labelPosition Label position, 'before' or 'after'
11839 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
11840 this.labelPosition
= labelPosition
;
11841 this.updatePosition();
11846 * Deprecated alias of #setLabelPosition
11848 * @deprecated Use setLabelPosition instead.
11850 OO
.ui
.TextInputWidget
.prototype.setPosition
=
11851 OO
.ui
.TextInputWidget
.prototype.setLabelPosition
;
11854 * Update the position of the inline label.
11856 * This method is called by #setLabelPosition, and can also be called on its own if
11857 * something causes the label to be mispositioned.
11862 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
11863 var after
= this.labelPosition
=== 'after';
11866 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
11867 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
11869 if ( this.label
) {
11870 this.positionLabel();
11877 * Position the label by setting the correct padding on the input.
11882 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
11883 // Clear old values
11885 // Clear old values if present
11887 'padding-right': '',
11891 if ( this.label
) {
11892 this.$element
.append( this.$label
);
11894 this.$label
.detach();
11898 var after
= this.labelPosition
=== 'after',
11899 rtl
= this.$element
.css( 'direction' ) === 'rtl',
11900 property
= after
=== rtl
? 'padding-left' : 'padding-right';
11902 this.$input
.css( property
, this.$label
.outerWidth( true ) );
11908 * ComboBoxWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
11909 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
11910 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
11912 * - by typing a value in the text input field. If the value exactly matches the value of a menu
11913 * option, that option will appear to be selected.
11914 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
11917 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
11920 * // Example: A ComboBoxWidget.
11921 * var comboBox = new OO.ui.ComboBoxWidget( {
11922 * label: 'ComboBoxWidget',
11923 * input: { value: 'Option One' },
11926 * new OO.ui.MenuOptionWidget( {
11927 * data: 'Option 1',
11928 * label: 'Option One'
11930 * new OO.ui.MenuOptionWidget( {
11931 * data: 'Option 2',
11932 * label: 'Option Two'
11934 * new OO.ui.MenuOptionWidget( {
11935 * data: 'Option 3',
11936 * label: 'Option Three'
11938 * new OO.ui.MenuOptionWidget( {
11939 * data: 'Option 4',
11940 * label: 'Option Four'
11942 * new OO.ui.MenuOptionWidget( {
11943 * data: 'Option 5',
11944 * label: 'Option Five'
11949 * $( 'body' ).append( comboBox.$element );
11951 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
11954 * @extends OO.ui.Widget
11955 * @mixins OO.ui.TabIndexedElement
11958 * @param {Object} [config] Configuration options
11959 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
11960 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
11961 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
11962 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
11963 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
11965 OO
.ui
.ComboBoxWidget
= function OoUiComboBoxWidget( config
) {
11966 // Configuration initialization
11967 config
= config
|| {};
11969 // Parent constructor
11970 OO
.ui
.ComboBoxWidget
.super.call( this, config
);
11972 // Properties (must be set before TabIndexedElement constructor call)
11973 this.$indicator
= this.$( '<span>' );
11975 // Mixin constructors
11976 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$indicator
} ) );
11979 this.$overlay
= config
.$overlay
|| this.$element
;
11980 this.input
= new OO
.ui
.TextInputWidget( $.extend(
11983 $indicator
: this.$indicator
,
11984 disabled
: this.isDisabled()
11988 this.input
.$input
.eq( 0 ).attr( {
11990 'aria-autocomplete': 'list'
11992 this.menu
= new OO
.ui
.TextInputMenuSelectWidget( this.input
, $.extend(
11996 disabled
: this.isDisabled()
12002 this.$indicator
.on( {
12003 click
: this.onClick
.bind( this ),
12004 keypress
: this.onKeyPress
.bind( this )
12006 this.input
.connect( this, {
12007 change
: 'onInputChange',
12008 enter
: 'onInputEnter'
12010 this.menu
.connect( this, {
12011 choose
: 'onMenuChoose',
12012 add
: 'onMenuItemsChange',
12013 remove
: 'onMenuItemsChange'
12017 this.$element
.addClass( 'oo-ui-comboBoxWidget' ).append( this.input
.$element
);
12018 this.$overlay
.append( this.menu
.$element
);
12019 this.onMenuItemsChange();
12024 OO
.inheritClass( OO
.ui
.ComboBoxWidget
, OO
.ui
.Widget
);
12025 OO
.mixinClass( OO
.ui
.ComboBoxWidget
, OO
.ui
.TabIndexedElement
);
12030 * Get the combobox's menu.
12031 * @return {OO.ui.TextInputMenuSelectWidget} Menu widget
12033 OO
.ui
.ComboBoxWidget
.prototype.getMenu = function () {
12038 * Handle input change events.
12041 * @param {string} value New value
12043 OO
.ui
.ComboBoxWidget
.prototype.onInputChange = function ( value
) {
12044 var match
= this.menu
.getItemFromData( value
);
12046 this.menu
.selectItem( match
);
12047 if ( this.menu
.getHighlightedItem() ) {
12048 this.menu
.highlightItem( match
);
12051 if ( !this.isDisabled() ) {
12052 this.menu
.toggle( true );
12057 * Handle mouse click events.
12061 * @param {jQuery.Event} e Mouse click event
12063 OO
.ui
.ComboBoxWidget
.prototype.onClick = function ( e
) {
12064 if ( !this.isDisabled() && e
.which
=== 1 ) {
12065 this.menu
.toggle();
12066 this.input
.$input
[ 0 ].focus();
12072 * Handle key press events.
12076 * @param {jQuery.Event} e Key press event
12078 OO
.ui
.ComboBoxWidget
.prototype.onKeyPress = function ( e
) {
12079 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
12080 this.menu
.toggle();
12081 this.input
.$input
[ 0 ].focus();
12087 * Handle input enter events.
12091 OO
.ui
.ComboBoxWidget
.prototype.onInputEnter = function () {
12092 if ( !this.isDisabled() ) {
12093 this.menu
.toggle( false );
12098 * Handle menu choose events.
12101 * @param {OO.ui.OptionWidget} item Chosen item
12103 OO
.ui
.ComboBoxWidget
.prototype.onMenuChoose = function ( item
) {
12105 this.input
.setValue( item
.getData() );
12110 * Handle menu item change events.
12114 OO
.ui
.ComboBoxWidget
.prototype.onMenuItemsChange = function () {
12115 var match
= this.menu
.getItemFromData( this.input
.getValue() );
12116 this.menu
.selectItem( match
);
12117 if ( this.menu
.getHighlightedItem() ) {
12118 this.menu
.highlightItem( match
);
12120 this.$element
.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu
.isEmpty() );
12126 OO
.ui
.ComboBoxWidget
.prototype.setDisabled = function ( disabled
) {
12128 OO
.ui
.ComboBoxWidget
.super.prototype.setDisabled
.call( this, disabled
);
12130 if ( this.input
) {
12131 this.input
.setDisabled( this.isDisabled() );
12134 this.menu
.setDisabled( this.isDisabled() );
12141 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
12142 * be configured with a `label` option that is set to a string, a label node, or a function:
12144 * - String: a plaintext string
12145 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
12146 * label that includes a link or special styling, such as a gray color or additional graphical elements.
12147 * - Function: a function that will produce a string in the future. Functions are used
12148 * in cases where the value of the label is not currently defined.
12150 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
12151 * will come into focus when the label is clicked.
12154 * // Examples of LabelWidgets
12155 * var label1 = new OO.ui.LabelWidget( {
12156 * label: 'plaintext label'
12158 * var label2 = new OO.ui.LabelWidget( {
12159 * label: $( '<a href="default.html">jQuery label</a>' )
12161 * // Create a fieldset layout with fields for each example
12162 * var fieldset = new OO.ui.FieldsetLayout();
12163 * fieldset.addItems( [
12164 * new OO.ui.FieldLayout( label1 ),
12165 * new OO.ui.FieldLayout( label2 )
12167 * $( 'body' ).append( fieldset.$element );
12171 * @extends OO.ui.Widget
12172 * @mixins OO.ui.LabelElement
12175 * @param {Object} [config] Configuration options
12176 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
12177 * Clicking the label will focus the specified input field.
12179 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
12180 // Configuration initialization
12181 config
= config
|| {};
12183 // Parent constructor
12184 OO
.ui
.LabelWidget
.super.call( this, config
);
12186 // Mixin constructors
12187 OO
.ui
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
12188 OO
.ui
.TitledElement
.call( this, config
);
12191 this.input
= config
.input
;
12194 if ( this.input
instanceof OO
.ui
.InputWidget
) {
12195 this.$element
.on( 'click', this.onClick
.bind( this ) );
12199 this.$element
.addClass( 'oo-ui-labelWidget' );
12204 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
12205 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.LabelElement
);
12206 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.TitledElement
);
12208 /* Static Properties */
12210 OO
.ui
.LabelWidget
.static.tagName
= 'span';
12215 * Handles label mouse click events.
12218 * @param {jQuery.Event} e Mouse click event
12220 OO
.ui
.LabelWidget
.prototype.onClick = function () {
12221 this.input
.simulateLabelClick();
12226 * OptionWidgets are special elements that can be selected and configured with data. The
12227 * data is often unique for each option, but it does not have to be. OptionWidgets are used
12228 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
12229 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
12231 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
12234 * @extends OO.ui.Widget
12235 * @mixins OO.ui.LabelElement
12236 * @mixins OO.ui.FlaggedElement
12239 * @param {Object} [config] Configuration options
12241 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
12242 // Configuration initialization
12243 config
= config
|| {};
12245 // Parent constructor
12246 OO
.ui
.OptionWidget
.super.call( this, config
);
12248 // Mixin constructors
12249 OO
.ui
.ItemWidget
.call( this );
12250 OO
.ui
.LabelElement
.call( this, config
);
12251 OO
.ui
.FlaggedElement
.call( this, config
);
12254 this.selected
= false;
12255 this.highlighted
= false;
12256 this.pressed
= false;
12260 .data( 'oo-ui-optionWidget', this )
12261 .attr( 'role', 'option' )
12262 .addClass( 'oo-ui-optionWidget' )
12263 .append( this.$label
);
12268 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
12269 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.ItemWidget
);
12270 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.LabelElement
);
12271 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.FlaggedElement
);
12273 /* Static Properties */
12275 OO
.ui
.OptionWidget
.static.selectable
= true;
12277 OO
.ui
.OptionWidget
.static.highlightable
= true;
12279 OO
.ui
.OptionWidget
.static.pressable
= true;
12281 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
12286 * Check if the option can be selected.
12288 * @return {boolean} Item is selectable
12290 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
12291 return this.constructor.static.selectable
&& !this.isDisabled();
12295 * Check if the option can be highlighted. A highlight indicates that the option
12296 * may be selected when a user presses enter or clicks. Disabled items cannot
12299 * @return {boolean} Item is highlightable
12301 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
12302 return this.constructor.static.highlightable
&& !this.isDisabled();
12306 * Check if the option can be pressed. The pressed state occurs when a user mouses
12307 * down on an item, but has not yet let go of the mouse.
12309 * @return {boolean} Item is pressable
12311 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
12312 return this.constructor.static.pressable
&& !this.isDisabled();
12316 * Check if the option is selected.
12318 * @return {boolean} Item is selected
12320 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
12321 return this.selected
;
12325 * Check if the option is highlighted. A highlight indicates that the
12326 * item may be selected when a user presses enter or clicks.
12328 * @return {boolean} Item is highlighted
12330 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
12331 return this.highlighted
;
12335 * Check if the option is pressed. The pressed state occurs when a user mouses
12336 * down on an item, but has not yet let go of the mouse. The item may appear
12337 * selected, but it will not be selected until the user releases the mouse.
12339 * @return {boolean} Item is pressed
12341 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
12342 return this.pressed
;
12346 * Set the option’s selected state. In general, all modifications to the selection
12347 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
12348 * method instead of this method.
12350 * @param {boolean} [state=false] Select option
12353 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
12354 if ( this.constructor.static.selectable
) {
12355 this.selected
= !!state
;
12357 .toggleClass( 'oo-ui-optionWidget-selected', state
)
12358 .attr( 'aria-selected', state
.toString() );
12359 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
12360 this.scrollElementIntoView();
12362 this.updateThemeClasses();
12368 * Set the option’s highlighted state. In general, all programmatic
12369 * modifications to the highlight should be handled by the
12370 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
12371 * method instead of this method.
12373 * @param {boolean} [state=false] Highlight option
12376 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
12377 if ( this.constructor.static.highlightable
) {
12378 this.highlighted
= !!state
;
12379 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
12380 this.updateThemeClasses();
12386 * Set the option’s pressed state. In general, all
12387 * programmatic modifications to the pressed state should be handled by the
12388 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
12389 * method instead of this method.
12391 * @param {boolean} [state=false] Press option
12394 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
12395 if ( this.constructor.static.pressable
) {
12396 this.pressed
= !!state
;
12397 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
12398 this.updateThemeClasses();
12404 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
12405 * with an {@link OO.ui.IconElement icon} and/or {@link OO.ui.IndicatorElement indicator}.
12406 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
12407 * options. For more information about options and selects, please see the
12408 * [OOjs UI documentation on MediaWiki][1].
12411 * // Decorated options in a select widget
12412 * var select = new OO.ui.SelectWidget( {
12414 * new OO.ui.DecoratedOptionWidget( {
12416 * label: 'Option with icon',
12419 * new OO.ui.DecoratedOptionWidget( {
12421 * label: 'Option with indicator',
12422 * indicator: 'next'
12426 * $( 'body' ).append( select.$element );
12428 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
12431 * @extends OO.ui.OptionWidget
12432 * @mixins OO.ui.IconElement
12433 * @mixins OO.ui.IndicatorElement
12436 * @param {Object} [config] Configuration options
12438 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
12439 // Parent constructor
12440 OO
.ui
.DecoratedOptionWidget
.super.call( this, config
);
12442 // Mixin constructors
12443 OO
.ui
.IconElement
.call( this, config
);
12444 OO
.ui
.IndicatorElement
.call( this, config
);
12448 .addClass( 'oo-ui-decoratedOptionWidget' )
12449 .prepend( this.$icon
)
12450 .append( this.$indicator
);
12455 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
12456 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.IconElement
);
12457 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.IndicatorElement
);
12460 * ButtonOptionWidget is a special type of {@link OO.ui.ButtonElement button element} that
12461 * can be selected and configured with data. The class is
12462 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
12463 * [OOjs UI documentation on MediaWiki] [1] for more information.
12465 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
12468 * @extends OO.ui.DecoratedOptionWidget
12469 * @mixins OO.ui.ButtonElement
12470 * @mixins OO.ui.TabIndexedElement
12473 * @param {Object} [config] Configuration options
12475 OO
.ui
.ButtonOptionWidget
= function OoUiButtonOptionWidget( config
) {
12476 // Configuration initialization
12477 config
= $.extend( { tabIndex
: -1 }, config
);
12479 // Parent constructor
12480 OO
.ui
.ButtonOptionWidget
.super.call( this, config
);
12482 // Mixin constructors
12483 OO
.ui
.ButtonElement
.call( this, config
);
12484 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
12487 this.$element
.addClass( 'oo-ui-buttonOptionWidget' );
12488 this.$button
.append( this.$element
.contents() );
12489 this.$element
.append( this.$button
);
12494 OO
.inheritClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
12495 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.ButtonElement
);
12496 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.TabIndexedElement
);
12498 /* Static Properties */
12500 // Allow button mouse down events to pass through so they can be handled by the parent select widget
12501 OO
.ui
.ButtonOptionWidget
.static.cancelButtonMouseDownEvents
= false;
12503 OO
.ui
.ButtonOptionWidget
.static.highlightable
= false;
12510 OO
.ui
.ButtonOptionWidget
.prototype.setSelected = function ( state
) {
12511 OO
.ui
.ButtonOptionWidget
.super.prototype.setSelected
.call( this, state
);
12513 if ( this.constructor.static.selectable
) {
12514 this.setActive( state
);
12521 * RadioOptionWidget is an option widget that looks like a radio button.
12522 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
12523 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
12525 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
12528 * @extends OO.ui.OptionWidget
12531 * @param {Object} [config] Configuration options
12533 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
12534 // Configuration initialization
12535 config
= config
|| {};
12537 // Properties (must be done before parent constructor which calls #setDisabled)
12538 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
12540 // Parent constructor
12541 OO
.ui
.RadioOptionWidget
.super.call( this, config
);
12545 .addClass( 'oo-ui-radioOptionWidget' )
12546 .prepend( this.radio
.$element
);
12551 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
12553 /* Static Properties */
12555 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
12557 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
12559 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
12561 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
12568 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
12569 OO
.ui
.RadioOptionWidget
.super.prototype.setSelected
.call( this, state
);
12571 this.radio
.setSelected( state
);
12579 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
12580 OO
.ui
.RadioOptionWidget
.super.prototype.setDisabled
.call( this, disabled
);
12582 this.radio
.setDisabled( this.isDisabled() );
12588 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
12589 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
12590 * the [OOjs UI documentation on MediaWiki] [1] for more information.
12592 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
12595 * @extends OO.ui.DecoratedOptionWidget
12598 * @param {Object} [config] Configuration options
12600 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
12601 // Configuration initialization
12602 config
= $.extend( { icon
: 'check' }, config
);
12604 // Parent constructor
12605 OO
.ui
.MenuOptionWidget
.super.call( this, config
);
12609 .attr( 'role', 'menuitem' )
12610 .addClass( 'oo-ui-menuOptionWidget' );
12615 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
12617 /* Static Properties */
12619 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
12622 * Section to group one or more items in a OO.ui.MenuSelectWidget.
12625 * @extends OO.ui.DecoratedOptionWidget
12628 * @param {Object} [config] Configuration options
12630 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
12631 // Parent constructor
12632 OO
.ui
.MenuSectionOptionWidget
.super.call( this, config
);
12635 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' );
12640 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
12642 /* Static Properties */
12644 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
12646 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
12649 * Items for an OO.ui.OutlineSelectWidget.
12652 * @extends OO.ui.DecoratedOptionWidget
12655 * @param {Object} [config] Configuration options
12656 * @cfg {number} [level] Indentation level
12657 * @cfg {boolean} [movable] Allow modification from outline controls
12659 OO
.ui
.OutlineOptionWidget
= function OoUiOutlineOptionWidget( config
) {
12660 // Configuration initialization
12661 config
= config
|| {};
12663 // Parent constructor
12664 OO
.ui
.OutlineOptionWidget
.super.call( this, config
);
12668 this.movable
= !!config
.movable
;
12669 this.removable
= !!config
.removable
;
12672 this.$element
.addClass( 'oo-ui-outlineOptionWidget' );
12673 this.setLevel( config
.level
);
12678 OO
.inheritClass( OO
.ui
.OutlineOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
12680 /* Static Properties */
12682 OO
.ui
.OutlineOptionWidget
.static.highlightable
= false;
12684 OO
.ui
.OutlineOptionWidget
.static.scrollIntoViewOnSelect
= true;
12686 OO
.ui
.OutlineOptionWidget
.static.levelClass
= 'oo-ui-outlineOptionWidget-level-';
12688 OO
.ui
.OutlineOptionWidget
.static.levels
= 3;
12693 * Check if item is movable.
12695 * Movability is used by outline controls.
12697 * @return {boolean} Item is movable
12699 OO
.ui
.OutlineOptionWidget
.prototype.isMovable = function () {
12700 return this.movable
;
12704 * Check if item is removable.
12706 * Removability is used by outline controls.
12708 * @return {boolean} Item is removable
12710 OO
.ui
.OutlineOptionWidget
.prototype.isRemovable = function () {
12711 return this.removable
;
12715 * Get indentation level.
12717 * @return {number} Indentation level
12719 OO
.ui
.OutlineOptionWidget
.prototype.getLevel = function () {
12726 * Movability is used by outline controls.
12728 * @param {boolean} movable Item is movable
12731 OO
.ui
.OutlineOptionWidget
.prototype.setMovable = function ( movable
) {
12732 this.movable
= !!movable
;
12733 this.updateThemeClasses();
12738 * Set removability.
12740 * Removability is used by outline controls.
12742 * @param {boolean} movable Item is removable
12745 OO
.ui
.OutlineOptionWidget
.prototype.setRemovable = function ( removable
) {
12746 this.removable
= !!removable
;
12747 this.updateThemeClasses();
12752 * Set indentation level.
12754 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
12757 OO
.ui
.OutlineOptionWidget
.prototype.setLevel = function ( level
) {
12758 var levels
= this.constructor.static.levels
,
12759 levelClass
= this.constructor.static.levelClass
,
12762 this.level
= level
? Math
.max( 0, Math
.min( levels
- 1, level
) ) : 0;
12764 if ( this.level
=== i
) {
12765 this.$element
.addClass( levelClass
+ i
);
12767 this.$element
.removeClass( levelClass
+ i
);
12770 this.updateThemeClasses();
12776 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
12777 * By default, each popup has an anchor that points toward its origin.
12778 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
12781 * // A popup widget.
12782 * var popup = new OO.ui.PopupWidget( {
12783 * $content: $( '<p>Hi there!</p>' ),
12788 * $( 'body' ).append( popup.$element );
12789 * // To display the popup, toggle the visibility to 'true'.
12790 * popup.toggle( true );
12792 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
12795 * @extends OO.ui.Widget
12796 * @mixins OO.ui.LabelElement
12799 * @param {Object} [config] Configuration options
12800 * @cfg {number} [width=320] Width of popup in pixels
12801 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
12802 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
12803 * @cfg {string} [align='center'] Alignment of the popup: `center`, `left`, or `right`.
12804 * If the popup is right-aligned, the right edge of the popup is aligned to the anchor.
12805 * For left-aligned popups, the left edge is aligned to the anchor.
12806 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
12807 * See the [OOjs UI docs on MediaWiki][3] for an example.
12808 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
12809 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
12810 * @cfg {jQuery} [$content] Content to append to the popup's body
12811 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
12812 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
12813 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
12815 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
12816 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
12818 * @cfg {boolean} [padded] Add padding to the popup's body
12820 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
12821 // Configuration initialization
12822 config
= config
|| {};
12824 // Parent constructor
12825 OO
.ui
.PopupWidget
.super.call( this, config
);
12827 // Properties (must be set before ClippableElement constructor call)
12828 this.$body
= $( '<div>' );
12830 // Mixin constructors
12831 OO
.ui
.LabelElement
.call( this, config
);
12832 OO
.ui
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$body
} ) );
12835 this.$popup
= $( '<div>' );
12836 this.$head
= $( '<div>' );
12837 this.$anchor
= $( '<div>' );
12838 // If undefined, will be computed lazily in updateDimensions()
12839 this.$container
= config
.$container
;
12840 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
12841 this.autoClose
= !!config
.autoClose
;
12842 this.$autoCloseIgnore
= config
.$autoCloseIgnore
;
12843 this.transitionTimeout
= null;
12844 this.anchor
= null;
12845 this.width
= config
.width
!== undefined ? config
.width
: 320;
12846 this.height
= config
.height
!== undefined ? config
.height
: null;
12847 this.align
= config
.align
|| 'center';
12848 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
12849 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
12850 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
12853 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
12856 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
12857 this.$body
.addClass( 'oo-ui-popupWidget-body' );
12858 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
12860 .addClass( 'oo-ui-popupWidget-head' )
12861 .append( this.$label
, this.closeButton
.$element
);
12862 if ( !config
.head
) {
12863 this.$head
.addClass( 'oo-ui-element-hidden' );
12866 .addClass( 'oo-ui-popupWidget-popup' )
12867 .append( this.$head
, this.$body
);
12869 .addClass( 'oo-ui-popupWidget' )
12870 .append( this.$popup
, this.$anchor
);
12871 // Move content, which was added to #$element by OO.ui.Widget, to the body
12872 if ( config
.$content
instanceof jQuery
) {
12873 this.$body
.append( config
.$content
);
12875 if ( config
.padded
) {
12876 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
12879 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
12880 // that reference properties not initialized at that time of parent class construction
12881 // TODO: Find a better way to handle post-constructor setup
12882 this.visible
= false;
12883 this.$element
.addClass( 'oo-ui-element-hidden' );
12888 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
12889 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.LabelElement
);
12890 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.ClippableElement
);
12895 * Handles mouse down events.
12898 * @param {MouseEvent} e Mouse down event
12900 OO
.ui
.PopupWidget
.prototype.onMouseDown = function ( e
) {
12902 this.isVisible() &&
12903 !$.contains( this.$element
[ 0 ], e
.target
) &&
12904 ( !this.$autoCloseIgnore
|| !this.$autoCloseIgnore
.has( e
.target
).length
)
12906 this.toggle( false );
12911 * Bind mouse down listener.
12915 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
12916 // Capture clicks outside popup
12917 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler
, true );
12921 * Handles close button click events.
12925 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
12926 if ( this.isVisible() ) {
12927 this.toggle( false );
12932 * Unbind mouse down listener.
12936 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
12937 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler
, true );
12941 * Handles key down events.
12944 * @param {KeyboardEvent} e Key down event
12946 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
12948 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
12951 this.toggle( false );
12952 e
.preventDefault();
12953 e
.stopPropagation();
12958 * Bind key down listener.
12962 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
12963 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
12967 * Unbind key down listener.
12971 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
12972 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
12976 * Show, hide, or toggle the visibility of the anchor.
12978 * @param {boolean} [show] Show anchor, omit to toggle
12980 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
12981 show
= show
=== undefined ? !this.anchored
: !!show
;
12983 if ( this.anchored
!== show
) {
12985 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
12987 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
12989 this.anchored
= show
;
12994 * Check if the anchor is visible.
12996 * @return {boolean} Anchor is visible
12998 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
12999 return this.anchor
;
13005 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
13006 show
= show
=== undefined ? !this.isVisible() : !!show
;
13008 var change
= show
!== this.isVisible();
13011 OO
.ui
.PopupWidget
.super.prototype.toggle
.call( this, show
);
13015 if ( this.autoClose
) {
13016 this.bindMouseDownListener();
13017 this.bindKeyDownListener();
13019 this.updateDimensions();
13020 this.toggleClipping( true );
13022 this.toggleClipping( false );
13023 if ( this.autoClose
) {
13024 this.unbindMouseDownListener();
13025 this.unbindKeyDownListener();
13034 * Set the size of the popup.
13036 * Changing the size may also change the popup's position depending on the alignment.
13038 * @param {number} width Width in pixels
13039 * @param {number} height Height in pixels
13040 * @param {boolean} [transition=false] Use a smooth transition
13043 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
13044 this.width
= width
;
13045 this.height
= height
!== undefined ? height
: null;
13046 if ( this.isVisible() ) {
13047 this.updateDimensions( transition
);
13052 * Update the size and position.
13054 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
13055 * be called automatically.
13057 * @param {boolean} [transition=false] Use a smooth transition
13060 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
13061 var popupOffset
, originOffset
, containerLeft
, containerWidth
, containerRight
,
13062 popupLeft
, popupRight
, overlapLeft
, overlapRight
, anchorWidth
,
13065 if ( !this.$container
) {
13066 // Lazy-initialize $container if not specified in constructor
13067 this.$container
= $( this.getClosestScrollableElementContainer() );
13070 // Set height and width before measuring things, since it might cause our measurements
13071 // to change (e.g. due to scrollbars appearing or disappearing)
13074 height
: this.height
!== null ? this.height
: 'auto'
13077 // Compute initial popupOffset based on alignment
13078 popupOffset
= this.width
* ( { left
: 0, center
: -0.5, right
: -1 } )[ this.align
];
13080 // Figure out if this will cause the popup to go beyond the edge of the container
13081 originOffset
= this.$element
.offset().left
;
13082 containerLeft
= this.$container
.offset().left
;
13083 containerWidth
= this.$container
.innerWidth();
13084 containerRight
= containerLeft
+ containerWidth
;
13085 popupLeft
= popupOffset
- this.containerPadding
;
13086 popupRight
= popupOffset
+ this.containerPadding
+ this.width
+ this.containerPadding
;
13087 overlapLeft
= ( originOffset
+ popupLeft
) - containerLeft
;
13088 overlapRight
= containerRight
- ( originOffset
+ popupRight
);
13090 // Adjust offset to make the popup not go beyond the edge, if needed
13091 if ( overlapRight
< 0 ) {
13092 popupOffset
+= overlapRight
;
13093 } else if ( overlapLeft
< 0 ) {
13094 popupOffset
-= overlapLeft
;
13097 // Adjust offset to avoid anchor being rendered too close to the edge
13098 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
13099 // TODO: Find a measurement that works for CSS anchors and image anchors
13100 anchorWidth
= this.$anchor
[ 0 ].scrollWidth
* 2;
13101 if ( popupOffset
+ this.width
< anchorWidth
) {
13102 popupOffset
= anchorWidth
- this.width
;
13103 } else if ( -popupOffset
< anchorWidth
) {
13104 popupOffset
= -anchorWidth
;
13107 // Prevent transition from being interrupted
13108 clearTimeout( this.transitionTimeout
);
13109 if ( transition
) {
13110 // Enable transition
13111 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
13114 // Position body relative to anchor
13115 this.$popup
.css( 'margin-left', popupOffset
);
13117 if ( transition
) {
13118 // Prevent transitioning after transition is complete
13119 this.transitionTimeout
= setTimeout( function () {
13120 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
13123 // Prevent transitioning immediately
13124 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
13127 // Reevaluate clipping state since we've relocated and resized the popup
13134 * Progress bars visually display the status of an operation, such as a download,
13135 * and can be either determinate or indeterminate:
13137 * - **determinate** process bars show the percent of an operation that is complete.
13139 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
13140 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
13141 * not use percentages.
13143 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
13146 * // Examples of determinate and indeterminate progress bars.
13147 * var progressBar1 = new OO.ui.ProgressBarWidget( {
13150 * var progressBar2 = new OO.ui.ProgressBarWidget();
13152 * // Create a FieldsetLayout to layout progress bars
13153 * var fieldset = new OO.ui.FieldsetLayout;
13154 * fieldset.addItems( [
13155 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
13156 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
13158 * $( 'body' ).append( fieldset.$element );
13161 * @extends OO.ui.Widget
13164 * @param {Object} [config] Configuration options
13165 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
13166 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
13167 * By default, the progress bar is indeterminate.
13169 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
13170 // Configuration initialization
13171 config
= config
|| {};
13173 // Parent constructor
13174 OO
.ui
.ProgressBarWidget
.super.call( this, config
);
13177 this.$bar
= $( '<div>' );
13178 this.progress
= null;
13181 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
13182 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
13185 role
: 'progressbar',
13186 'aria-valuemin': 0,
13187 'aria-valuemax': 100
13189 .addClass( 'oo-ui-progressBarWidget' )
13190 .append( this.$bar
);
13195 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
13197 /* Static Properties */
13199 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
13204 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
13206 * @return {number|boolean} Progress percent
13208 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
13209 return this.progress
;
13213 * Set the percent of the process completed or `false` for an indeterminate process.
13215 * @param {number|boolean} progress Progress percent or `false` for indeterminate
13217 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
13218 this.progress
= progress
;
13220 if ( progress
!== false ) {
13221 this.$bar
.css( 'width', this.progress
+ '%' );
13222 this.$element
.attr( 'aria-valuenow', this.progress
);
13224 this.$bar
.css( 'width', '' );
13225 this.$element
.removeAttr( 'aria-valuenow' );
13227 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress
);
13233 * Search widgets combine a query input, placed above, and a results selection widget, placed below.
13234 * Results are cleared and populated each time the query is changed.
13237 * @extends OO.ui.Widget
13240 * @param {Object} [config] Configuration options
13241 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
13242 * @cfg {string} [value] Initial query value
13244 OO
.ui
.SearchWidget
= function OoUiSearchWidget( config
) {
13245 // Configuration initialization
13246 config
= config
|| {};
13248 // Parent constructor
13249 OO
.ui
.SearchWidget
.super.call( this, config
);
13252 this.query
= new OO
.ui
.TextInputWidget( {
13254 placeholder
: config
.placeholder
,
13255 value
: config
.value
13257 this.results
= new OO
.ui
.SelectWidget();
13258 this.$query
= $( '<div>' );
13259 this.$results
= $( '<div>' );
13262 this.query
.connect( this, {
13263 change
: 'onQueryChange',
13264 enter
: 'onQueryEnter'
13266 this.results
.connect( this, {
13267 highlight
: 'onResultsHighlight',
13268 select
: 'onResultsSelect'
13270 this.query
.$input
.on( 'keydown', this.onQueryKeydown
.bind( this ) );
13274 .addClass( 'oo-ui-searchWidget-query' )
13275 .append( this.query
.$element
);
13277 .addClass( 'oo-ui-searchWidget-results' )
13278 .append( this.results
.$element
);
13280 .addClass( 'oo-ui-searchWidget' )
13281 .append( this.$results
, this.$query
);
13286 OO
.inheritClass( OO
.ui
.SearchWidget
, OO
.ui
.Widget
);
13292 * @param {Object|null} item Item data or null if no item is highlighted
13297 * @param {Object|null} item Item data or null if no item is selected
13303 * Handle query key down events.
13305 * @param {jQuery.Event} e Key down event
13307 OO
.ui
.SearchWidget
.prototype.onQueryKeydown = function ( e
) {
13308 var highlightedItem
, nextItem
,
13309 dir
= e
.which
=== OO
.ui
.Keys
.DOWN
? 1 : ( e
.which
=== OO
.ui
.Keys
.UP
? -1 : 0 );
13312 highlightedItem
= this.results
.getHighlightedItem();
13313 if ( !highlightedItem
) {
13314 highlightedItem
= this.results
.getSelectedItem();
13316 nextItem
= this.results
.getRelativeSelectableItem( highlightedItem
, dir
);
13317 this.results
.highlightItem( nextItem
);
13318 nextItem
.scrollElementIntoView();
13323 * Handle select widget select events.
13325 * Clears existing results. Subclasses should repopulate items according to new query.
13327 * @param {string} value New value
13329 OO
.ui
.SearchWidget
.prototype.onQueryChange = function () {
13331 this.results
.clearItems();
13335 * Handle select widget enter key events.
13337 * Selects highlighted item.
13339 * @param {string} value New value
13341 OO
.ui
.SearchWidget
.prototype.onQueryEnter = function () {
13343 this.results
.selectItem( this.results
.getHighlightedItem() );
13347 * Handle select widget highlight events.
13349 * @param {OO.ui.OptionWidget} item Highlighted item
13352 OO
.ui
.SearchWidget
.prototype.onResultsHighlight = function ( item
) {
13353 this.emit( 'highlight', item
? item
.getData() : null );
13357 * Handle select widget select events.
13359 * @param {OO.ui.OptionWidget} item Selected item
13362 OO
.ui
.SearchWidget
.prototype.onResultsSelect = function ( item
) {
13363 this.emit( 'select', item
? item
.getData() : null );
13367 * Get the query input.
13369 * @return {OO.ui.TextInputWidget} Query input
13371 OO
.ui
.SearchWidget
.prototype.getQuery = function () {
13376 * Get the results list.
13378 * @return {OO.ui.SelectWidget} Select list
13380 OO
.ui
.SearchWidget
.prototype.getResults = function () {
13381 return this.results
;
13385 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
13386 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
13387 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
13390 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
13391 * information, please see the [OOjs UI documentation on MediaWiki][1].
13394 * // Example of a select widget with three options
13395 * var select = new OO.ui.SelectWidget( {
13397 * new OO.ui.OptionWidget( {
13399 * label: 'Option One',
13401 * new OO.ui.OptionWidget( {
13403 * label: 'Option Two',
13405 * new OO.ui.OptionWidget( {
13407 * label: 'Option Three',
13411 * $( 'body' ).append( select.$element );
13413 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
13416 * @extends OO.ui.Widget
13417 * @mixins OO.ui.GroupElement
13420 * @param {Object} [config] Configuration options
13421 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
13422 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
13423 * the [OOjs UI documentation on MediaWiki] [2] for examples.
13424 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
13426 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
13427 // Configuration initialization
13428 config
= config
|| {};
13430 // Parent constructor
13431 OO
.ui
.SelectWidget
.super.call( this, config
);
13433 // Mixin constructors
13434 OO
.ui
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
13437 this.pressed
= false;
13438 this.selecting
= null;
13439 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
13440 this.onMouseMoveHandler
= this.onMouseMove
.bind( this );
13441 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
13444 this.$element
.on( {
13445 mousedown
: this.onMouseDown
.bind( this ),
13446 mouseover
: this.onMouseOver
.bind( this ),
13447 mouseleave
: this.onMouseLeave
.bind( this )
13452 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
13453 .attr( 'role', 'listbox' );
13454 if ( Array
.isArray( config
.items
) ) {
13455 this.addItems( config
.items
);
13461 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
13463 // Need to mixin base class as well
13464 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.GroupElement
);
13465 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.GroupWidget
);
13472 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
13474 * @param {OO.ui.OptionWidget|null} item Highlighted item
13480 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
13481 * pressed state of an option.
13483 * @param {OO.ui.OptionWidget|null} item Pressed item
13489 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
13491 * @param {OO.ui.OptionWidget|null} item Selected item
13496 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
13497 * @param {OO.ui.OptionWidget|null} item Chosen item
13503 * An `add` event is emitted when options are added to the select with the #addItems method.
13505 * @param {OO.ui.OptionWidget[]} items Added items
13506 * @param {number} index Index of insertion point
13512 * A `remove` event is emitted when options are removed from the select with the #clearItems
13513 * or #removeItems methods.
13515 * @param {OO.ui.OptionWidget[]} items Removed items
13521 * Handle mouse down events.
13524 * @param {jQuery.Event} e Mouse down event
13526 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
13529 if ( !this.isDisabled() && e
.which
=== 1 ) {
13530 this.togglePressed( true );
13531 item
= this.getTargetItem( e
);
13532 if ( item
&& item
.isSelectable() ) {
13533 this.pressItem( item
);
13534 this.selecting
= item
;
13535 this.getElementDocument().addEventListener(
13537 this.onMouseUpHandler
,
13540 this.getElementDocument().addEventListener(
13542 this.onMouseMoveHandler
,
13551 * Handle mouse up events.
13554 * @param {jQuery.Event} e Mouse up event
13556 OO
.ui
.SelectWidget
.prototype.onMouseUp = function ( e
) {
13559 this.togglePressed( false );
13560 if ( !this.selecting
) {
13561 item
= this.getTargetItem( e
);
13562 if ( item
&& item
.isSelectable() ) {
13563 this.selecting
= item
;
13566 if ( !this.isDisabled() && e
.which
=== 1 && this.selecting
) {
13567 this.pressItem( null );
13568 this.chooseItem( this.selecting
);
13569 this.selecting
= null;
13572 this.getElementDocument().removeEventListener(
13574 this.onMouseUpHandler
,
13577 this.getElementDocument().removeEventListener(
13579 this.onMouseMoveHandler
,
13587 * Handle mouse move events.
13590 * @param {jQuery.Event} e Mouse move event
13592 OO
.ui
.SelectWidget
.prototype.onMouseMove = function ( e
) {
13595 if ( !this.isDisabled() && this.pressed
) {
13596 item
= this.getTargetItem( e
);
13597 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
13598 this.pressItem( item
);
13599 this.selecting
= item
;
13606 * Handle mouse over events.
13609 * @param {jQuery.Event} e Mouse over event
13611 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
13614 if ( !this.isDisabled() ) {
13615 item
= this.getTargetItem( e
);
13616 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
13622 * Handle mouse leave events.
13625 * @param {jQuery.Event} e Mouse over event
13627 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
13628 if ( !this.isDisabled() ) {
13629 this.highlightItem( null );
13635 * Handle key down events.
13638 * @param {jQuery.Event} e Key down event
13640 OO
.ui
.SelectWidget
.prototype.onKeyDown = function ( e
) {
13643 currentItem
= this.getHighlightedItem() || this.getSelectedItem();
13645 if ( !this.isDisabled() && this.isVisible() ) {
13646 switch ( e
.keyCode
) {
13647 case OO
.ui
.Keys
.ENTER
:
13648 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
13649 // Was only highlighted, now let's select it. No-op if already selected.
13650 this.chooseItem( currentItem
);
13654 case OO
.ui
.Keys
.UP
:
13655 case OO
.ui
.Keys
.LEFT
:
13656 nextItem
= this.getRelativeSelectableItem( currentItem
, -1 );
13659 case OO
.ui
.Keys
.DOWN
:
13660 case OO
.ui
.Keys
.RIGHT
:
13661 nextItem
= this.getRelativeSelectableItem( currentItem
, 1 );
13664 case OO
.ui
.Keys
.ESCAPE
:
13665 case OO
.ui
.Keys
.TAB
:
13666 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
13667 currentItem
.setHighlighted( false );
13669 this.unbindKeyDownListener();
13670 // Don't prevent tabbing away / defocusing
13676 if ( nextItem
.constructor.static.highlightable
) {
13677 this.highlightItem( nextItem
);
13679 this.chooseItem( nextItem
);
13681 nextItem
.scrollElementIntoView();
13685 // Can't just return false, because e is not always a jQuery event
13686 e
.preventDefault();
13687 e
.stopPropagation();
13693 * Bind key down listener.
13697 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
13698 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler
, true );
13702 * Unbind key down listener.
13706 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
13707 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler
, true );
13711 * Get the closest item to a jQuery.Event.
13714 * @param {jQuery.Event} e
13715 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
13717 OO
.ui
.SelectWidget
.prototype.getTargetItem = function ( e
) {
13718 var $item
= $( e
.target
).closest( '.oo-ui-optionWidget' );
13719 if ( $item
.length
) {
13720 return $item
.data( 'oo-ui-optionWidget' );
13726 * Get selected item.
13728 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
13730 OO
.ui
.SelectWidget
.prototype.getSelectedItem = function () {
13733 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
13734 if ( this.items
[ i
].isSelected() ) {
13735 return this.items
[ i
];
13742 * Get highlighted item.
13744 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
13746 OO
.ui
.SelectWidget
.prototype.getHighlightedItem = function () {
13749 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
13750 if ( this.items
[ i
].isHighlighted() ) {
13751 return this.items
[ i
];
13758 * Toggle pressed state.
13760 * Press is a state that occurs when a user mouses down on an item, but
13761 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
13762 * until the user releases the mouse.
13764 * @param {boolean} pressed An option is being pressed
13766 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
13767 if ( pressed
=== undefined ) {
13768 pressed
= !this.pressed
;
13770 if ( pressed
!== this.pressed
) {
13772 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
13773 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
13774 this.pressed
= pressed
;
13779 * Highlight an option. If the `item` param is omitted, no options will be highlighted
13780 * and any existing highlight will be removed. The highlight is mutually exclusive.
13782 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
13786 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
13787 var i
, len
, highlighted
,
13790 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
13791 highlighted
= this.items
[ i
] === item
;
13792 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
13793 this.items
[ i
].setHighlighted( highlighted
);
13798 this.emit( 'highlight', item
);
13805 * Programmatically select an option by its reference. If the `item` parameter is omitted,
13806 * all options will be deselected.
13808 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
13812 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
13813 var i
, len
, selected
,
13816 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
13817 selected
= this.items
[ i
] === item
;
13818 if ( this.items
[ i
].isSelected() !== selected
) {
13819 this.items
[ i
].setSelected( selected
);
13824 this.emit( 'select', item
);
13833 * Press is a state that occurs when a user mouses down on an item, but has not
13834 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
13835 * releases the mouse.
13837 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
13841 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
13842 var i
, len
, pressed
,
13845 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
13846 pressed
= this.items
[ i
] === item
;
13847 if ( this.items
[ i
].isPressed() !== pressed
) {
13848 this.items
[ i
].setPressed( pressed
);
13853 this.emit( 'press', item
);
13862 * Note that ‘choose’ should never be modified programmatically. A user can choose
13863 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
13864 * use the #selectItem method.
13866 * This method is identical to #selectItem, but may vary in subclasses that take additional action
13867 * when users choose an item with the keyboard or mouse.
13869 * @param {OO.ui.OptionWidget} item Item to choose
13873 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
13874 this.selectItem( item
);
13875 this.emit( 'choose', item
);
13881 * Get an option by its position relative to the specified item (or to the start of the option array,
13882 * if item is `null`). The direction in which to search through the option array is specified with a
13883 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
13884 * `null` if there are no options in the array.
13886 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
13887 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
13888 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
13890 OO
.ui
.SelectWidget
.prototype.getRelativeSelectableItem = function ( item
, direction
) {
13891 var currentIndex
, nextIndex
, i
,
13892 increase
= direction
> 0 ? 1 : -1,
13893 len
= this.items
.length
;
13895 if ( item
instanceof OO
.ui
.OptionWidget
) {
13896 currentIndex
= $.inArray( item
, this.items
);
13897 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
13899 // If no item is selected and moving forward, start at the beginning.
13900 // If moving backward, start at the end.
13901 nextIndex
= direction
> 0 ? 0 : len
- 1;
13904 for ( i
= 0; i
< len
; i
++ ) {
13905 item
= this.items
[ nextIndex
];
13906 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() ) {
13909 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
13915 * Get the next selectable item or `null` if there are no selectable items.
13916 * Disabled options and menu-section markers and breaks are not selectable.
13918 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
13920 OO
.ui
.SelectWidget
.prototype.getFirstSelectableItem = function () {
13923 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
13924 item
= this.items
[ i
];
13925 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() ) {
13934 * Add an array of options to the select. Optionally, an index number can be used to
13935 * specify an insertion point.
13937 * @param {OO.ui.OptionWidget[]} items Items to add
13938 * @param {number} [index] Index to insert items after
13942 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
13944 OO
.ui
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
13946 // Always provide an index, even if it was omitted
13947 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
13953 * Remove the specified array of options from the select. Options will be detached
13954 * from the DOM, not removed, so they can be reused later. To remove all options from
13955 * the select, you may wish to use the #clearItems method instead.
13957 * @param {OO.ui.OptionWidget[]} items Items to remove
13961 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
13964 // Deselect items being removed
13965 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
13967 if ( item
.isSelected() ) {
13968 this.selectItem( null );
13973 OO
.ui
.GroupWidget
.prototype.removeItems
.call( this, items
);
13975 this.emit( 'remove', items
);
13981 * Clear all options from the select. Options will be detached from the DOM, not removed,
13982 * so that they can be reused later. To remove a subset of options from the select, use
13983 * the #removeItems method.
13988 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
13989 var items
= this.items
.slice();
13992 OO
.ui
.GroupWidget
.prototype.clearItems
.call( this );
13995 this.selectItem( null );
13997 this.emit( 'remove', items
);
14003 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
14004 * button options and is used together with
14005 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
14006 * highlighting, choosing, and selecting mutually exclusive options. Please see
14007 * the [OOjs UI documentation on MediaWiki] [1] for more information.
14010 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
14011 * var option1 = new OO.ui.ButtonOptionWidget( {
14013 * label: 'Option 1',
14014 * title: 'Button option 1'
14017 * var option2 = new OO.ui.ButtonOptionWidget( {
14019 * label: 'Option 2',
14020 * title: 'Button option 2'
14023 * var option3 = new OO.ui.ButtonOptionWidget( {
14025 * label: 'Option 3',
14026 * title: 'Button option 3'
14029 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
14030 * items: [ option1, option2, option3 ]
14032 * $( 'body' ).append( buttonSelect.$element );
14034 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14037 * @extends OO.ui.SelectWidget
14038 * @mixins OO.ui.TabIndexedElement
14041 * @param {Object} [config] Configuration options
14043 OO
.ui
.ButtonSelectWidget
= function OoUiButtonSelectWidget( config
) {
14044 // Parent constructor
14045 OO
.ui
.ButtonSelectWidget
.super.call( this, config
);
14047 // Mixin constructors
14048 OO
.ui
.TabIndexedElement
.call( this, config
);
14051 this.$element
.on( {
14052 focus
: this.bindKeyDownListener
.bind( this ),
14053 blur
: this.unbindKeyDownListener
.bind( this )
14057 this.$element
.addClass( 'oo-ui-buttonSelectWidget' );
14062 OO
.inheritClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.SelectWidget
);
14063 OO
.mixinClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.TabIndexedElement
);
14066 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
14067 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
14068 * an interface for adding, removing and selecting options.
14069 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
14072 * // A RadioSelectWidget with RadioOptions.
14073 * var option1 = new OO.ui.RadioOptionWidget( {
14075 * label: 'Selected radio option'
14078 * var option2 = new OO.ui.RadioOptionWidget( {
14080 * label: 'Unselected radio option'
14083 * var radioSelect=new OO.ui.RadioSelectWidget( {
14084 * items: [ option1, option2 ]
14087 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
14088 * radioSelect.selectItem( option1 );
14090 * $( 'body' ).append( radioSelect.$element );
14092 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14096 * @extends OO.ui.SelectWidget
14097 * @mixins OO.ui.TabIndexedElement
14100 * @param {Object} [config] Configuration options
14102 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
14103 // Parent constructor
14104 OO
.ui
.RadioSelectWidget
.super.call( this, config
);
14106 // Mixin constructors
14107 OO
.ui
.TabIndexedElement
.call( this, config
);
14110 this.$element
.on( {
14111 focus
: this.bindKeyDownListener
.bind( this ),
14112 blur
: this.unbindKeyDownListener
.bind( this )
14116 this.$element
.addClass( 'oo-ui-radioSelectWidget' );
14121 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
14122 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.TabIndexedElement
);
14125 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
14126 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
14127 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxWidget ComboBoxWidget},
14128 * and {@link OO.ui.LookupElement LookupElement} for examples of widgets that contain menus.
14129 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
14130 * and customized to be opened, closed, and displayed as needed.
14132 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
14133 * mouse outside the menu.
14135 * Menus also have support for keyboard interaction:
14137 * - Enter/Return key: choose and select a menu option
14138 * - Up-arrow key: highlight the previous menu option
14139 * - Down-arrow key: highlight the next menu option
14140 * - Esc key: hide the menu
14142 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
14143 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14146 * @extends OO.ui.SelectWidget
14147 * @mixins OO.ui.ClippableElement
14150 * @param {Object} [config] Configuration options
14151 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
14152 * the text the user types. This config is used by {@link OO.ui.ComboBoxWidget ComboBoxWidget}
14153 * and {@link OO.ui.LookupElement LookupElement}
14154 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu’s active state. If the user clicks the mouse
14155 * anywhere on the page outside of this widget, the menu is hidden.
14156 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
14158 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
14159 // Configuration initialization
14160 config
= config
|| {};
14162 // Parent constructor
14163 OO
.ui
.MenuSelectWidget
.super.call( this, config
);
14165 // Mixin constructors
14166 OO
.ui
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
14169 this.newItems
= null;
14170 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
14171 this.$input
= config
.input
? config
.input
.$input
: null;
14172 this.$widget
= config
.widget
? config
.widget
.$element
: null;
14173 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
14177 .addClass( 'oo-ui-menuSelectWidget' )
14178 .attr( 'role', 'menu' );
14180 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
14181 // that reference properties not initialized at that time of parent class construction
14182 // TODO: Find a better way to handle post-constructor setup
14183 this.visible
= false;
14184 this.$element
.addClass( 'oo-ui-element-hidden' );
14189 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
14190 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.ClippableElement
);
14195 * Handles document mouse down events.
14198 * @param {jQuery.Event} e Key down event
14200 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
14202 !OO
.ui
.contains( this.$element
[ 0 ], e
.target
, true ) &&
14203 ( !this.$widget
|| !OO
.ui
.contains( this.$widget
[ 0 ], e
.target
, true ) )
14205 this.toggle( false );
14212 OO
.ui
.MenuSelectWidget
.prototype.onKeyDown = function ( e
) {
14213 var currentItem
= this.getHighlightedItem() || this.getSelectedItem();
14215 if ( !this.isDisabled() && this.isVisible() ) {
14216 switch ( e
.keyCode
) {
14217 case OO
.ui
.Keys
.LEFT
:
14218 case OO
.ui
.Keys
.RIGHT
:
14219 // Do nothing if a text field is associated, arrow keys will be handled natively
14220 if ( !this.$input
) {
14221 OO
.ui
.MenuSelectWidget
.super.prototype.onKeyDown
.call( this, e
);
14224 case OO
.ui
.Keys
.ESCAPE
:
14225 case OO
.ui
.Keys
.TAB
:
14226 if ( currentItem
) {
14227 currentItem
.setHighlighted( false );
14229 this.toggle( false );
14230 // Don't prevent tabbing away, prevent defocusing
14231 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
14232 e
.preventDefault();
14233 e
.stopPropagation();
14237 OO
.ui
.MenuSelectWidget
.super.prototype.onKeyDown
.call( this, e
);
14246 OO
.ui
.MenuSelectWidget
.prototype.bindKeyDownListener = function () {
14247 if ( this.$input
) {
14248 this.$input
.on( 'keydown', this.onKeyDownHandler
);
14250 OO
.ui
.MenuSelectWidget
.super.prototype.bindKeyDownListener
.call( this );
14257 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyDownListener = function () {
14258 if ( this.$input
) {
14259 this.$input
.off( 'keydown', this.onKeyDownHandler
);
14261 OO
.ui
.MenuSelectWidget
.super.prototype.unbindKeyDownListener
.call( this );
14268 * When a user chooses an item, the menu is closed.
14270 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
14271 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
14272 * @param {OO.ui.OptionWidget} item Item to choose
14275 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
14276 OO
.ui
.MenuSelectWidget
.super.prototype.chooseItem
.call( this, item
);
14277 this.toggle( false );
14284 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
14288 OO
.ui
.MenuSelectWidget
.super.prototype.addItems
.call( this, items
, index
);
14291 if ( !this.newItems
) {
14292 this.newItems
= [];
14295 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
14297 if ( this.isVisible() ) {
14298 // Defer fitting label until item has been attached
14301 this.newItems
.push( item
);
14305 // Reevaluate clipping
14314 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
14316 OO
.ui
.MenuSelectWidget
.super.prototype.removeItems
.call( this, items
);
14318 // Reevaluate clipping
14327 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
14329 OO
.ui
.MenuSelectWidget
.super.prototype.clearItems
.call( this );
14331 // Reevaluate clipping
14340 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
14341 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
14344 change
= visible
!== this.isVisible();
14347 OO
.ui
.MenuSelectWidget
.super.prototype.toggle
.call( this, visible
);
14351 this.bindKeyDownListener();
14353 if ( this.newItems
&& this.newItems
.length
) {
14354 for ( i
= 0, len
= this.newItems
.length
; i
< len
; i
++ ) {
14355 this.newItems
[ i
].fitLabel();
14357 this.newItems
= null;
14359 this.toggleClipping( true );
14362 if ( this.autoHide
) {
14363 this.getElementDocument().addEventListener(
14364 'mousedown', this.onDocumentMouseDownHandler
, true
14368 this.unbindKeyDownListener();
14369 this.getElementDocument().removeEventListener(
14370 'mousedown', this.onDocumentMouseDownHandler
, true
14372 this.toggleClipping( false );
14380 * TextInputMenuSelectWidget is a menu that is specially designed to be positioned beneath
14381 * a {@link OO.ui.TextInputWidget text input} field. The menu's position is automatically
14382 * calculated and maintained when the menu is toggled or the window is resized.
14383 * See OO.ui.ComboBoxWidget for an example of a widget that uses this class.
14386 * @extends OO.ui.MenuSelectWidget
14389 * @param {OO.ui.TextInputWidget} inputWidget Text input widget to provide menu for
14390 * @param {Object} [config] Configuration options
14391 * @cfg {jQuery} [$container=input.$element] Element to render menu under
14393 OO
.ui
.TextInputMenuSelectWidget
= function OoUiTextInputMenuSelectWidget( inputWidget
, config
) {
14394 // Allow passing positional parameters inside the config object
14395 if ( OO
.isPlainObject( inputWidget
) && config
=== undefined ) {
14396 config
= inputWidget
;
14397 inputWidget
= config
.inputWidget
;
14400 // Configuration initialization
14401 config
= config
|| {};
14403 // Parent constructor
14404 OO
.ui
.TextInputMenuSelectWidget
.super.call( this, config
);
14407 this.inputWidget
= inputWidget
;
14408 this.$container
= config
.$container
|| this.inputWidget
.$element
;
14409 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
14412 this.$element
.addClass( 'oo-ui-textInputMenuSelectWidget' );
14417 OO
.inheritClass( OO
.ui
.TextInputMenuSelectWidget
, OO
.ui
.MenuSelectWidget
);
14422 * Handle window resize event.
14425 * @param {jQuery.Event} e Window resize event
14427 OO
.ui
.TextInputMenuSelectWidget
.prototype.onWindowResize = function () {
14434 OO
.ui
.TextInputMenuSelectWidget
.prototype.toggle = function ( visible
) {
14435 visible
= visible
=== undefined ? !this.isVisible() : !!visible
;
14437 var change
= visible
!== this.isVisible();
14439 if ( change
&& visible
) {
14440 // Make sure the width is set before the parent method runs.
14441 // After this we have to call this.position(); again to actually
14442 // position ourselves correctly.
14447 OO
.ui
.TextInputMenuSelectWidget
.super.prototype.toggle
.call( this, visible
);
14450 if ( this.isVisible() ) {
14452 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler
);
14454 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler
);
14462 * Position the menu.
14467 OO
.ui
.TextInputMenuSelectWidget
.prototype.position = function () {
14468 var $container
= this.$container
,
14469 pos
= OO
.ui
.Element
.static.getRelativePosition( $container
, this.$element
.offsetParent() );
14471 // Position under input
14472 pos
.top
+= $container
.height();
14473 this.$element
.css( pos
);
14476 this.setIdealSize( $container
.width() );
14477 // We updated the position, so re-evaluate the clipping state
14484 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
14485 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
14487 * ####Currently, this class is only used by {@link OO.ui.BookletLayout BookletLayouts}.####
14490 * @extends OO.ui.SelectWidget
14491 * @mixins OO.ui.TabIndexedElement
14494 * @param {Object} [config] Configuration options
14496 OO
.ui
.OutlineSelectWidget
= function OoUiOutlineSelectWidget( config
) {
14497 // Parent constructor
14498 OO
.ui
.OutlineSelectWidget
.super.call( this, config
);
14500 // Mixin constructors
14501 OO
.ui
.TabIndexedElement
.call( this, config
);
14504 this.$element
.on( {
14505 focus
: this.bindKeyDownListener
.bind( this ),
14506 blur
: this.unbindKeyDownListener
.bind( this )
14510 this.$element
.addClass( 'oo-ui-outlineSelectWidget' );
14515 OO
.inheritClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.SelectWidget
);
14516 OO
.mixinClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.TabIndexedElement
);
14519 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
14520 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
14521 * visually by a slider in the leftmost position.
14524 * // Toggle switches in the 'off' and 'on' position.
14525 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
14526 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
14530 * // Create a FieldsetLayout to layout and label switches
14531 * var fieldset = new OO.ui.FieldsetLayout( {
14532 * label: 'Toggle switches'
14534 * fieldset.addItems( [
14535 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
14536 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
14538 * $( 'body' ).append( fieldset.$element );
14541 * @extends OO.ui.Widget
14542 * @mixins OO.ui.ToggleWidget
14543 * @mixins OO.ui.TabIndexedElement
14546 * @param {Object} [config] Configuration options
14547 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
14548 * By default, the toggle switch is in the 'off' position.
14550 OO
.ui
.ToggleSwitchWidget
= function OoUiToggleSwitchWidget( config
) {
14551 // Parent constructor
14552 OO
.ui
.ToggleSwitchWidget
.super.call( this, config
);
14554 // Mixin constructors
14555 OO
.ui
.ToggleWidget
.call( this, config
);
14556 OO
.ui
.TabIndexedElement
.call( this, config
);
14559 this.dragging
= false;
14560 this.dragStart
= null;
14561 this.sliding
= false;
14562 this.$glow
= $( '<span>' );
14563 this.$grip
= $( '<span>' );
14566 this.$element
.on( {
14567 click
: this.onClick
.bind( this ),
14568 keypress
: this.onKeyPress
.bind( this )
14572 this.$glow
.addClass( 'oo-ui-toggleSwitchWidget-glow' );
14573 this.$grip
.addClass( 'oo-ui-toggleSwitchWidget-grip' );
14575 .addClass( 'oo-ui-toggleSwitchWidget' )
14576 .attr( 'role', 'checkbox' )
14577 .append( this.$glow
, this.$grip
);
14582 OO
.inheritClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.Widget
);
14583 OO
.mixinClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.ToggleWidget
);
14584 OO
.mixinClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.TabIndexedElement
);
14589 * Handle mouse click events.
14592 * @param {jQuery.Event} e Mouse click event
14594 OO
.ui
.ToggleSwitchWidget
.prototype.onClick = function ( e
) {
14595 if ( !this.isDisabled() && e
.which
=== 1 ) {
14596 this.setValue( !this.value
);
14602 * Handle key press events.
14605 * @param {jQuery.Event} e Key press event
14607 OO
.ui
.ToggleSwitchWidget
.prototype.onKeyPress = function ( e
) {
14608 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
14609 this.setValue( !this.value
);