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-25T22:24:05Z
16 * Namespace for all classes, static methods and static properties.
48 * Get the user's language and any fallback languages.
50 * These language codes are used to localize user interface elements in the user's language.
52 * In environments that provide a localization system, this function should be overridden to
53 * return the user's language(s). The default implementation returns English (en) only.
55 * @return {string[]} Language codes, in descending order of priority
57 OO
.ui
.getUserLanguages = function () {
62 * Get a value in an object keyed by language code.
64 * @param {Object.<string,Mixed>} obj Object keyed by language code
65 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
66 * @param {string} [fallback] Fallback code, used if no matching language can be found
67 * @return {Mixed} Local value
69 OO
.ui
.getLocalValue = function ( obj
, lang
, fallback
) {
76 // Known user language
77 langs
= OO
.ui
.getUserLanguages();
78 for ( i
= 0, len
= langs
.length
; i
< len
; i
++ ) {
85 if ( obj
[ fallback
] ) {
86 return obj
[ fallback
];
88 // First existing language
97 * Check if a node is contained within another node
99 * Similar to jQuery#contains except a list of containers can be supplied
100 * and a boolean argument allows you to include the container in the match list
102 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
103 * @param {HTMLElement} contained Node to find
104 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
105 * @return {boolean} The node is in the list of target nodes
107 OO
.ui
.contains = function ( containers
, contained
, matchContainers
) {
109 if ( !Array
.isArray( containers
) ) {
110 containers
= [ containers
];
112 for ( i
= containers
.length
- 1; i
>= 0; i
-- ) {
113 if ( ( matchContainers
&& contained
=== containers
[ i
] ) || $.contains( containers
[ i
], contained
) ) {
121 * Reconstitute a JavaScript object corresponding to a widget created by
122 * the PHP implementation.
124 * This is an alias for `OO.ui.Element.static.infuse()`.
126 * @param {string|HTMLElement|jQuery} idOrNode
127 * A DOM id (if a string) or node for the widget to infuse.
128 * @return {OO.ui.Element}
129 * The `OO.ui.Element` corresponding to this (infusable) document node.
131 OO
.ui
.infuse = function ( idOrNode
) {
132 return OO
.ui
.Element
.static.infuse( idOrNode
);
137 * Message store for the default implementation of OO.ui.msg
139 * Environments that provide a localization system should not use this, but should override
140 * OO.ui.msg altogether.
145 // Tool tip for a button that moves items in a list down one place
146 'ooui-outline-control-move-down': 'Move item down',
147 // Tool tip for a button that moves items in a list up one place
148 'ooui-outline-control-move-up': 'Move item up',
149 // Tool tip for a button that removes items from a list
150 'ooui-outline-control-remove': 'Remove item',
151 // Label for the toolbar group that contains a list of all other available tools
152 'ooui-toolbar-more': 'More',
153 // Label for the fake tool that expands the full list of tools in a toolbar group
154 'ooui-toolgroup-expand': 'More',
155 // Label for the fake tool that collapses the full list of tools in a toolbar group
156 'ooui-toolgroup-collapse': 'Fewer',
157 // Default label for the accept button of a confirmation dialog
158 'ooui-dialog-message-accept': 'OK',
159 // Default label for the reject button of a confirmation dialog
160 'ooui-dialog-message-reject': 'Cancel',
161 // Title for process dialog error description
162 'ooui-dialog-process-error': 'Something went wrong',
163 // Label for process dialog dismiss error button, visible when describing errors
164 'ooui-dialog-process-dismiss': 'Dismiss',
165 // Label for process dialog retry action button, visible when describing only recoverable errors
166 'ooui-dialog-process-retry': 'Try again',
167 // Label for process dialog retry action button, visible when describing only warnings
168 'ooui-dialog-process-continue': 'Continue'
172 * Get a localized message.
174 * In environments that provide a localization system, this function should be overridden to
175 * return the message translated in the user's language. The default implementation always returns
178 * After the message key, message parameters may optionally be passed. In the default implementation,
179 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
180 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
181 * they support unnamed, ordered message parameters.
184 * @param {string} key Message key
185 * @param {Mixed...} [params] Message parameters
186 * @return {string} Translated message with parameters substituted
188 OO
.ui
.msg = function ( key
) {
189 var message
= messages
[ key
],
190 params
= Array
.prototype.slice
.call( arguments
, 1 );
191 if ( typeof message
=== 'string' ) {
192 // Perform $1 substitution
193 message
= message
.replace( /\$(\d+)/g, function ( unused
, n
) {
194 var i
= parseInt( n
, 10 );
195 return params
[ i
- 1 ] !== undefined ? params
[ i
- 1 ] : '$' + n
;
198 // Return placeholder if message not found
199 message
= '[' + key
+ ']';
205 * Package a message and arguments for deferred resolution.
207 * Use this when you are statically specifying a message and the message may not yet be present.
209 * @param {string} key Message key
210 * @param {Mixed...} [params] Message parameters
211 * @return {Function} Function that returns the resolved message when executed
213 OO
.ui
.deferMsg = function () {
214 var args
= arguments
;
216 return OO
.ui
.msg
.apply( OO
.ui
, args
);
223 * If the message is a function it will be executed, otherwise it will pass through directly.
225 * @param {Function|string} msg Deferred message, or message text
226 * @return {string} Resolved message
228 OO
.ui
.resolveMsg = function ( msg
) {
229 if ( $.isFunction( msg
) ) {
238 * Element that can be marked as pending.
244 * @param {Object} [config] Configuration options
245 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
247 OO
.ui
.PendingElement
= function OoUiPendingElement( config
) {
248 // Configuration initialization
249 config
= config
|| {};
253 this.$pending
= null;
256 this.setPendingElement( config
.$pending
|| this.$element
);
261 OO
.initClass( OO
.ui
.PendingElement
);
266 * Set the pending element (and clean up any existing one).
268 * @param {jQuery} $pending The element to set to pending.
270 OO
.ui
.PendingElement
.prototype.setPendingElement = function ( $pending
) {
271 if ( this.$pending
) {
272 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
275 this.$pending
= $pending
;
276 if ( this.pending
> 0 ) {
277 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
282 * Check if input is pending.
286 OO
.ui
.PendingElement
.prototype.isPending = function () {
287 return !!this.pending
;
291 * Increase the pending stack.
295 OO
.ui
.PendingElement
.prototype.pushPending = function () {
296 if ( this.pending
=== 0 ) {
297 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
298 this.updateThemeClasses();
306 * Reduce the pending stack.
312 OO
.ui
.PendingElement
.prototype.popPending = function () {
313 if ( this.pending
=== 1 ) {
314 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
315 this.updateThemeClasses();
317 this.pending
= Math
.max( 0, this.pending
- 1 );
323 * ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them.
324 * Actions can be made available for specific contexts (modes) and circumstances
325 * (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
327 * ActionSets contain two types of actions:
329 * - Special: Special actions are the first visible actions with special flags, such as 'safe' and 'primary', the default special flags. Additional special flags can be configured in subclasses with the static #specialFlags property.
330 * - Other: Other actions include all non-special visible actions.
332 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
335 * // Example: An action set used in a process dialog
336 * function MyProcessDialog( config ) {
337 * MyProcessDialog.super.call( this, config );
339 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
340 * MyProcessDialog.static.title = 'An action set in a process dialog';
341 * // An action set that uses modes ('edit' and 'help' mode, in this example).
342 * MyProcessDialog.static.actions = [
343 * { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] },
344 * { action: 'help', modes: 'edit', label: 'Help' },
345 * { modes: 'edit', label: 'Cancel', flags: 'safe' },
346 * { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
349 * MyProcessDialog.prototype.initialize = function () {
350 * MyProcessDialog.super.prototype.initialize.apply( this, arguments );
351 * this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
352 * this.panel1.$element.append( '<p>This dialog uses an action set (continue, help, cancel, back) configured with modes. This is edit mode. Click \'help\' to see help mode.</p>' );
353 * this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
354 * this.panel2.$element.append( '<p>This is help mode. Only the \'back\' action widget is configured to be visible here. Click \'back\' to return to \'edit\' mode.</p>' );
355 * this.stackLayout = new OO.ui.StackLayout( {
356 * items: [ this.panel1, this.panel2 ]
358 * this.$body.append( this.stackLayout.$element );
360 * MyProcessDialog.prototype.getSetupProcess = function ( data ) {
361 * return MyProcessDialog.super.prototype.getSetupProcess.call( this, data )
362 * .next( function () {
363 * this.actions.setMode( 'edit' );
366 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
367 * if ( action === 'help' ) {
368 * this.actions.setMode( 'help' );
369 * this.stackLayout.setItem( this.panel2 );
370 * } else if ( action === 'back' ) {
371 * this.actions.setMode( 'edit' );
372 * this.stackLayout.setItem( this.panel1 );
373 * } else if ( action === 'continue' ) {
375 * return new OO.ui.Process( function () {
379 * return MyProcessDialog.super.prototype.getActionProcess.call( this, action );
381 * MyProcessDialog.prototype.getBodyHeight = function () {
382 * return this.panel1.$element.outerHeight( true );
384 * var windowManager = new OO.ui.WindowManager();
385 * $( 'body' ).append( windowManager.$element );
386 * var dialog = new MyProcessDialog( {
389 * windowManager.addWindows( [ dialog ] );
390 * windowManager.openWindow( dialog );
392 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
396 * @mixins OO.EventEmitter
399 * @param {Object} [config] Configuration options
401 OO
.ui
.ActionSet
= function OoUiActionSet( config
) {
402 // Configuration initialization
403 config
= config
|| {};
405 // Mixin constructors
406 OO
.EventEmitter
.call( this );
411 actions
: 'getAction',
415 this.categorized
= {};
418 this.organized
= false;
419 this.changing
= false;
420 this.changed
= false;
425 OO
.mixinClass( OO
.ui
.ActionSet
, OO
.EventEmitter
);
427 /* Static Properties */
430 * Symbolic name of the flags used to identify special actions. Special actions are displayed in the
431 * header of a {@link OO.ui.ProcessDialog process dialog}.
432 * See the [OOjs UI documentation on MediaWiki][2] for more information and examples.
434 * [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
441 OO
.ui
.ActionSet
.static.specialFlags
= [ 'safe', 'primary' ];
448 * A 'click' event is emitted when an action is clicked.
450 * @param {OO.ui.ActionWidget} action Action that was clicked
456 * A 'resize' event is emitted when an action widget is resized.
458 * @param {OO.ui.ActionWidget} action Action that was resized
464 * An 'add' event is emitted when actions are {@link #method-add added} to the action set.
466 * @param {OO.ui.ActionWidget[]} added Actions added
472 * A 'remove' event is emitted when actions are {@link #method-remove removed}
473 * or {@link #clear cleared}.
475 * @param {OO.ui.ActionWidget[]} added Actions removed
481 * A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
482 * or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed.
489 * Handle action change events.
494 OO
.ui
.ActionSet
.prototype.onActionChange = function () {
495 this.organized
= false;
496 if ( this.changing
) {
499 this.emit( 'change' );
504 * Check if an action is one of the special actions.
506 * @param {OO.ui.ActionWidget} action Action to check
507 * @return {boolean} Action is special
509 OO
.ui
.ActionSet
.prototype.isSpecial = function ( action
) {
512 for ( flag
in this.special
) {
513 if ( action
=== this.special
[ flag
] ) {
522 * Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
525 * @param {Object} [filters] Filters to use, omit to get all actions
526 * @param {string|string[]} [filters.actions] Actions that action widgets must have
527 * @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
528 * @param {string|string[]} [filters.modes] Modes that action widgets must have
529 * @param {boolean} [filters.visible] Action widgets must be visible
530 * @param {boolean} [filters.disabled] Action widgets must be disabled
531 * @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
533 OO
.ui
.ActionSet
.prototype.get = function ( filters
) {
534 var i
, len
, list
, category
, actions
, index
, match
, matches
;
539 // Collect category candidates
541 for ( category
in this.categorized
) {
542 list
= filters
[ category
];
544 if ( !Array
.isArray( list
) ) {
547 for ( i
= 0, len
= list
.length
; i
< len
; i
++ ) {
548 actions
= this.categorized
[ category
][ list
[ i
] ];
549 if ( Array
.isArray( actions
) ) {
550 matches
.push
.apply( matches
, actions
);
555 // Remove by boolean filters
556 for ( i
= 0, len
= matches
.length
; i
< len
; i
++ ) {
557 match
= matches
[ i
];
559 ( filters
.visible
!== undefined && match
.isVisible() !== filters
.visible
) ||
560 ( filters
.disabled
!== undefined && match
.isDisabled() !== filters
.disabled
)
562 matches
.splice( i
, 1 );
568 for ( i
= 0, len
= matches
.length
; i
< len
; i
++ ) {
569 match
= matches
[ i
];
570 index
= matches
.lastIndexOf( match
);
571 while ( index
!== i
) {
572 matches
.splice( index
, 1 );
574 index
= matches
.lastIndexOf( match
);
579 return this.list
.slice();
583 * Get 'special' actions.
585 * Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'.
586 * Special flags can be configured in subclasses by changing the static #specialFlags property.
588 * @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
590 OO
.ui
.ActionSet
.prototype.getSpecial = function () {
592 return $.extend( {}, this.special
);
596 * Get 'other' actions.
598 * Other actions include all non-special visible action widgets.
600 * @return {OO.ui.ActionWidget[]} 'Other' action widgets
602 OO
.ui
.ActionSet
.prototype.getOthers = function () {
604 return this.others
.slice();
608 * Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
609 * to be available in the specified mode will be made visible. All other actions will be hidden.
611 * @param {string} mode The mode. Only actions configured to be available in the specified
612 * mode will be made visible.
617 OO
.ui
.ActionSet
.prototype.setMode = function ( mode
) {
620 this.changing
= true;
621 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
622 action
= this.list
[ i
];
623 action
.toggle( action
.hasMode( mode
) );
626 this.organized
= false;
627 this.changing
= false;
628 this.emit( 'change' );
634 * Set the abilities of the specified actions.
636 * Action widgets that are configured with the specified actions will be enabled
637 * or disabled based on the boolean values specified in the `actions`
640 * @param {Object.<string,boolean>} actions A list keyed by action name with boolean
641 * values that indicate whether or not the action should be enabled.
644 OO
.ui
.ActionSet
.prototype.setAbilities = function ( actions
) {
645 var i
, len
, action
, item
;
647 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
648 item
= this.list
[ i
];
649 action
= item
.getAction();
650 if ( actions
[ action
] !== undefined ) {
651 item
.setDisabled( !actions
[ action
] );
659 * Executes a function once per action.
661 * When making changes to multiple actions, use this method instead of iterating over the actions
662 * manually to defer emitting a #change event until after all actions have been changed.
664 * @param {Object|null} actions Filters to use to determine which actions to iterate over; see #get
665 * @param {Function} callback Callback to run for each action; callback is invoked with three
666 * arguments: the action, the action's index, the list of actions being iterated over
669 OO
.ui
.ActionSet
.prototype.forEach = function ( filter
, callback
) {
670 this.changed
= false;
671 this.changing
= true;
672 this.get( filter
).forEach( callback
);
673 this.changing
= false;
674 if ( this.changed
) {
675 this.emit( 'change' );
682 * Add action widgets to the action set.
684 * @param {OO.ui.ActionWidget[]} actions Action widgets to add
689 OO
.ui
.ActionSet
.prototype.add = function ( actions
) {
692 this.changing
= true;
693 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
694 action
= actions
[ i
];
695 action
.connect( this, {
696 click
: [ 'emit', 'click', action
],
697 resize
: [ 'emit', 'resize', action
],
698 toggle
: [ 'onActionChange' ]
700 this.list
.push( action
);
702 this.organized
= false;
703 this.emit( 'add', actions
);
704 this.changing
= false;
705 this.emit( 'change' );
711 * Remove action widgets from the set.
713 * To remove all actions, you may wish to use the #clear method instead.
715 * @param {OO.ui.ActionWidget[]} actions Action widgets to remove
720 OO
.ui
.ActionSet
.prototype.remove = function ( actions
) {
721 var i
, len
, index
, action
;
723 this.changing
= true;
724 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
725 action
= actions
[ i
];
726 index
= this.list
.indexOf( action
);
727 if ( index
!== -1 ) {
728 action
.disconnect( this );
729 this.list
.splice( index
, 1 );
732 this.organized
= false;
733 this.emit( 'remove', actions
);
734 this.changing
= false;
735 this.emit( 'change' );
741 * Remove all action widets from the set.
743 * To remove only specified actions, use the {@link #method-remove remove} method instead.
749 OO
.ui
.ActionSet
.prototype.clear = function () {
751 removed
= this.list
.slice();
753 this.changing
= true;
754 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
755 action
= this.list
[ i
];
756 action
.disconnect( this );
761 this.organized
= false;
762 this.emit( 'remove', removed
);
763 this.changing
= false;
764 this.emit( 'change' );
772 * This is called whenever organized information is requested. It will only reorganize the actions
773 * if something has changed since the last time it ran.
778 OO
.ui
.ActionSet
.prototype.organize = function () {
779 var i
, iLen
, j
, jLen
, flag
, action
, category
, list
, item
, special
,
780 specialFlags
= this.constructor.static.specialFlags
;
782 if ( !this.organized
) {
783 this.categorized
= {};
786 for ( i
= 0, iLen
= this.list
.length
; i
< iLen
; i
++ ) {
787 action
= this.list
[ i
];
788 if ( action
.isVisible() ) {
789 // Populate categories
790 for ( category
in this.categories
) {
791 if ( !this.categorized
[ category
] ) {
792 this.categorized
[ category
] = {};
794 list
= action
[ this.categories
[ category
] ]();
795 if ( !Array
.isArray( list
) ) {
798 for ( j
= 0, jLen
= list
.length
; j
< jLen
; j
++ ) {
800 if ( !this.categorized
[ category
][ item
] ) {
801 this.categorized
[ category
][ item
] = [];
803 this.categorized
[ category
][ item
].push( action
);
806 // Populate special/others
808 for ( j
= 0, jLen
= specialFlags
.length
; j
< jLen
; j
++ ) {
809 flag
= specialFlags
[ j
];
810 if ( !this.special
[ flag
] && action
.hasFlag( flag
) ) {
811 this.special
[ flag
] = action
;
817 this.others
.push( action
);
821 this.organized
= true;
828 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
829 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
830 * connected to them and can't be interacted with.
836 * @param {Object} [config] Configuration options
837 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
838 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
840 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
841 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
842 * @cfg {string} [text] Text to insert
843 * @cfg {Array} [content] An array of content elements to append (after #text).
844 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
845 * Instances of OO.ui.Element will have their $element appended.
846 * @cfg {jQuery} [$content] Content elements to append (after #text)
847 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
848 * Data can also be specified with the #setData method.
850 OO
.ui
.Element
= function OoUiElement( config
) {
851 // Configuration initialization
852 config
= config
|| {};
857 this.data
= config
.data
;
858 this.$element
= config
.$element
||
859 $( document
.createElement( this.getTagName() ) );
860 this.elementGroup
= null;
861 this.debouncedUpdateThemeClassesHandler
= this.debouncedUpdateThemeClasses
.bind( this );
862 this.updateThemeClassesPending
= false;
865 if ( Array
.isArray( config
.classes
) ) {
866 this.$element
.addClass( config
.classes
.join( ' ' ) );
869 this.$element
.attr( 'id', config
.id
);
872 this.$element
.text( config
.text
);
874 if ( config
.content
) {
875 // The `content` property treats plain strings as text; use an
876 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
877 // appropriate $element appended.
878 this.$element
.append( config
.content
.map( function ( v
) {
879 if ( typeof v
=== 'string' ) {
880 // Escape string so it is properly represented in HTML.
881 return document
.createTextNode( v
);
882 } else if ( v
instanceof OO
.ui
.HtmlSnippet
) {
885 } else if ( v
instanceof OO
.ui
.Element
) {
891 if ( config
.$content
) {
892 // The `$content` property treats plain strings as HTML.
893 this.$element
.append( config
.$content
);
899 OO
.initClass( OO
.ui
.Element
);
901 /* Static Properties */
904 * The name of the HTML tag used by the element.
906 * The static value may be ignored if the #getTagName method is overridden.
912 OO
.ui
.Element
.static.tagName
= 'div';
917 * Reconstitute a JavaScript object corresponding to a widget created
918 * by the PHP implementation.
920 * @param {string|HTMLElement|jQuery} idOrNode
921 * A DOM id (if a string) or node for the widget to infuse.
922 * @return {OO.ui.Element}
923 * The `OO.ui.Element` corresponding to this (infusable) document node.
924 * For `Tag` objects emitted on the HTML side (used occasionally for content)
925 * the value returned is a newly-created Element wrapping around the existing
928 OO
.ui
.Element
.static.infuse = function ( idOrNode
) {
929 var obj
= OO
.ui
.Element
.static.unsafeInfuse( idOrNode
, true );
930 // Verify that the type matches up.
931 // FIXME: uncomment after T89721 is fixed (see T90929)
933 if ( !( obj instanceof this['class'] ) ) {
934 throw new Error( 'Infusion type mismatch!' );
941 * Implementation helper for `infuse`; skips the type check and has an
942 * extra property so that only the top-level invocation touches the DOM.
944 * @param {string|HTMLElement|jQuery} idOrNode
945 * @param {boolean} top True only for top-level invocation.
946 * @return {OO.ui.Element}
948 OO
.ui
.Element
.static.unsafeInfuse = function ( idOrNode
, top
) {
949 // look for a cached result of a previous infusion.
950 var id
, $elem
, data
, cls
, obj
;
951 if ( typeof idOrNode
=== 'string' ) {
953 $elem
= $( document
.getElementById( id
) );
955 $elem
= $( idOrNode
);
956 id
= $elem
.attr( 'id' );
958 data
= $elem
.data( 'ooui-infused' );
961 if ( data
=== true ) {
962 throw new Error( 'Circular dependency! ' + id
);
966 if ( !$elem
.length
) {
967 throw new Error( 'Widget not found: ' + id
);
969 data
= $elem
.attr( 'data-ooui' );
971 throw new Error( 'No infusion data found: ' + id
);
974 data
= $.parseJSON( data
);
978 if ( !( data
&& data
._
) ) {
979 throw new Error( 'No valid infusion data found: ' + id
);
981 if ( data
._
=== 'Tag' ) {
982 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
983 return new OO
.ui
.Element( { $element
: $elem
} );
987 throw new Error( 'Unknown widget type: ' + id
);
989 $elem
.data( 'ooui-infused', true ); // prevent loops
990 data
.id
= id
; // implicit
991 data
= OO
.copy( data
, null, function deserialize( value
) {
992 if ( OO
.isPlainObject( value
) ) {
994 return OO
.ui
.Element
.static.unsafeInfuse( value
.tag
, false );
997 return new OO
.ui
.HtmlSnippet( value
.html
);
1001 // jscs:disable requireCapitalizedConstructors
1002 obj
= new cls( data
); // rebuild widget
1003 // now replace old DOM with this new DOM.
1005 $elem
.replaceWith( obj
.$element
);
1007 obj
.$element
.data( 'ooui-infused', obj
);
1008 // set the 'data-ooui' attribute so we can identify infused widgets
1009 obj
.$element
.attr( 'data-ooui', '' );
1014 * Get a jQuery function within a specific document.
1017 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
1018 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
1020 * @return {Function} Bound jQuery function
1022 OO
.ui
.Element
.static.getJQuery = function ( context
, $iframe
) {
1023 function wrapper( selector
) {
1024 return $( selector
, wrapper
.context
);
1027 wrapper
.context
= this.getDocument( context
);
1030 wrapper
.$iframe
= $iframe
;
1037 * Get the document of an element.
1040 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
1041 * @return {HTMLDocument|null} Document object
1043 OO
.ui
.Element
.static.getDocument = function ( obj
) {
1044 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
1045 return ( obj
[ 0 ] && obj
[ 0 ].ownerDocument
) ||
1046 // Empty jQuery selections might have a context
1049 obj
.ownerDocument
||
1053 ( obj
.nodeType
=== 9 && obj
) ||
1058 * Get the window of an element or document.
1061 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
1062 * @return {Window} Window object
1064 OO
.ui
.Element
.static.getWindow = function ( obj
) {
1065 var doc
= this.getDocument( obj
);
1066 return doc
.parentWindow
|| doc
.defaultView
;
1070 * Get the direction of an element or document.
1073 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
1074 * @return {string} Text direction, either 'ltr' or 'rtl'
1076 OO
.ui
.Element
.static.getDir = function ( obj
) {
1079 if ( obj
instanceof jQuery
) {
1082 isDoc
= obj
.nodeType
=== 9;
1083 isWin
= obj
.document
!== undefined;
1084 if ( isDoc
|| isWin
) {
1090 return $( obj
).css( 'direction' );
1094 * Get the offset between two frames.
1096 * TODO: Make this function not use recursion.
1099 * @param {Window} from Window of the child frame
1100 * @param {Window} [to=window] Window of the parent frame
1101 * @param {Object} [offset] Offset to start with, used internally
1102 * @return {Object} Offset object, containing left and top properties
1104 OO
.ui
.Element
.static.getFrameOffset = function ( from, to
, offset
) {
1105 var i
, len
, frames
, frame
, rect
;
1111 offset
= { top
: 0, left
: 0 };
1113 if ( from.parent
=== from ) {
1117 // Get iframe element
1118 frames
= from.parent
.document
.getElementsByTagName( 'iframe' );
1119 for ( i
= 0, len
= frames
.length
; i
< len
; i
++ ) {
1120 if ( frames
[ i
].contentWindow
=== from ) {
1121 frame
= frames
[ i
];
1126 // Recursively accumulate offset values
1128 rect
= frame
.getBoundingClientRect();
1129 offset
.left
+= rect
.left
;
1130 offset
.top
+= rect
.top
;
1131 if ( from !== to
) {
1132 this.getFrameOffset( from.parent
, offset
);
1139 * Get the offset between two elements.
1141 * The two elements may be in a different frame, but in that case the frame $element is in must
1142 * be contained in the frame $anchor is in.
1145 * @param {jQuery} $element Element whose position to get
1146 * @param {jQuery} $anchor Element to get $element's position relative to
1147 * @return {Object} Translated position coordinates, containing top and left properties
1149 OO
.ui
.Element
.static.getRelativePosition = function ( $element
, $anchor
) {
1150 var iframe
, iframePos
,
1151 pos
= $element
.offset(),
1152 anchorPos
= $anchor
.offset(),
1153 elementDocument
= this.getDocument( $element
),
1154 anchorDocument
= this.getDocument( $anchor
);
1156 // If $element isn't in the same document as $anchor, traverse up
1157 while ( elementDocument
!== anchorDocument
) {
1158 iframe
= elementDocument
.defaultView
.frameElement
;
1160 throw new Error( '$element frame is not contained in $anchor frame' );
1162 iframePos
= $( iframe
).offset();
1163 pos
.left
+= iframePos
.left
;
1164 pos
.top
+= iframePos
.top
;
1165 elementDocument
= iframe
.ownerDocument
;
1167 pos
.left
-= anchorPos
.left
;
1168 pos
.top
-= anchorPos
.top
;
1173 * Get element border sizes.
1176 * @param {HTMLElement} el Element to measure
1177 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1179 OO
.ui
.Element
.static.getBorders = function ( el
) {
1180 var doc
= el
.ownerDocument
,
1181 win
= doc
.parentWindow
|| doc
.defaultView
,
1182 style
= win
&& win
.getComputedStyle
?
1183 win
.getComputedStyle( el
, null ) :
1186 top
= parseFloat( style
? style
.borderTopWidth
: $el
.css( 'borderTopWidth' ) ) || 0,
1187 left
= parseFloat( style
? style
.borderLeftWidth
: $el
.css( 'borderLeftWidth' ) ) || 0,
1188 bottom
= parseFloat( style
? style
.borderBottomWidth
: $el
.css( 'borderBottomWidth' ) ) || 0,
1189 right
= parseFloat( style
? style
.borderRightWidth
: $el
.css( 'borderRightWidth' ) ) || 0;
1200 * Get dimensions of an element or window.
1203 * @param {HTMLElement|Window} el Element to measure
1204 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1206 OO
.ui
.Element
.static.getDimensions = function ( el
) {
1208 doc
= el
.ownerDocument
|| el
.document
,
1209 win
= doc
.parentWindow
|| doc
.defaultView
;
1211 if ( win
=== el
|| el
=== doc
.documentElement
) {
1214 borders
: { top
: 0, left
: 0, bottom
: 0, right
: 0 },
1216 top
: $win
.scrollTop(),
1217 left
: $win
.scrollLeft()
1219 scrollbar
: { right
: 0, bottom
: 0 },
1223 bottom
: $win
.innerHeight(),
1224 right
: $win
.innerWidth()
1230 borders
: this.getBorders( el
),
1232 top
: $el
.scrollTop(),
1233 left
: $el
.scrollLeft()
1236 right
: $el
.innerWidth() - el
.clientWidth
,
1237 bottom
: $el
.innerHeight() - el
.clientHeight
1239 rect
: el
.getBoundingClientRect()
1245 * Get scrollable object parent
1247 * documentElement can't be used to get or set the scrollTop
1248 * property on Blink. Changing and testing its value lets us
1249 * use 'body' or 'documentElement' based on what is working.
1251 * https://code.google.com/p/chromium/issues/detail?id=303131
1254 * @param {HTMLElement} el Element to find scrollable parent for
1255 * @return {HTMLElement} Scrollable parent
1257 OO
.ui
.Element
.static.getRootScrollableElement = function ( el
) {
1258 var scrollTop
, body
;
1260 if ( OO
.ui
.scrollableElement
=== undefined ) {
1261 body
= el
.ownerDocument
.body
;
1262 scrollTop
= body
.scrollTop
;
1265 if ( body
.scrollTop
=== 1 ) {
1266 body
.scrollTop
= scrollTop
;
1267 OO
.ui
.scrollableElement
= 'body';
1269 OO
.ui
.scrollableElement
= 'documentElement';
1273 return el
.ownerDocument
[ OO
.ui
.scrollableElement
];
1277 * Get closest scrollable container.
1279 * Traverses up until either a scrollable element or the root is reached, in which case the window
1283 * @param {HTMLElement} el Element to find scrollable container for
1284 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1285 * @return {HTMLElement} Closest scrollable container
1287 OO
.ui
.Element
.static.getClosestScrollableContainer = function ( el
, dimension
) {
1289 props
= [ 'overflow' ],
1290 $parent
= $( el
).parent();
1292 if ( dimension
=== 'x' || dimension
=== 'y' ) {
1293 props
.push( 'overflow-' + dimension
);
1296 while ( $parent
.length
) {
1297 if ( $parent
[ 0 ] === this.getRootScrollableElement( el
) ) {
1298 return $parent
[ 0 ];
1302 val
= $parent
.css( props
[ i
] );
1303 if ( val
=== 'auto' || val
=== 'scroll' ) {
1304 return $parent
[ 0 ];
1307 $parent
= $parent
.parent();
1309 return this.getDocument( el
).body
;
1313 * Scroll element into view.
1316 * @param {HTMLElement} el Element to scroll into view
1317 * @param {Object} [config] Configuration options
1318 * @param {string} [config.duration] jQuery animation duration value
1319 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1320 * to scroll in both directions
1321 * @param {Function} [config.complete] Function to call when scrolling completes
1323 OO
.ui
.Element
.static.scrollIntoView = function ( el
, config
) {
1324 // Configuration initialization
1325 config
= config
|| {};
1328 callback
= typeof config
.complete
=== 'function' && config
.complete
,
1329 sc
= this.getClosestScrollableContainer( el
, config
.direction
),
1331 eld
= this.getDimensions( el
),
1332 scd
= this.getDimensions( sc
),
1333 $win
= $( this.getWindow( el
) );
1335 // Compute the distances between the edges of el and the edges of the scroll viewport
1336 if ( $sc
.is( 'html, body' ) ) {
1337 // If the scrollable container is the root, this is easy
1340 bottom
: $win
.innerHeight() - eld
.rect
.bottom
,
1341 left
: eld
.rect
.left
,
1342 right
: $win
.innerWidth() - eld
.rect
.right
1345 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1347 top
: eld
.rect
.top
- ( scd
.rect
.top
+ scd
.borders
.top
),
1348 bottom
: scd
.rect
.bottom
- scd
.borders
.bottom
- scd
.scrollbar
.bottom
- eld
.rect
.bottom
,
1349 left
: eld
.rect
.left
- ( scd
.rect
.left
+ scd
.borders
.left
),
1350 right
: scd
.rect
.right
- scd
.borders
.right
- scd
.scrollbar
.right
- eld
.rect
.right
1354 if ( !config
.direction
|| config
.direction
=== 'y' ) {
1355 if ( rel
.top
< 0 ) {
1356 anim
.scrollTop
= scd
.scroll
.top
+ rel
.top
;
1357 } else if ( rel
.top
> 0 && rel
.bottom
< 0 ) {
1358 anim
.scrollTop
= scd
.scroll
.top
+ Math
.min( rel
.top
, -rel
.bottom
);
1361 if ( !config
.direction
|| config
.direction
=== 'x' ) {
1362 if ( rel
.left
< 0 ) {
1363 anim
.scrollLeft
= scd
.scroll
.left
+ rel
.left
;
1364 } else if ( rel
.left
> 0 && rel
.right
< 0 ) {
1365 anim
.scrollLeft
= scd
.scroll
.left
+ Math
.min( rel
.left
, -rel
.right
);
1368 if ( !$.isEmptyObject( anim
) ) {
1369 $sc
.stop( true ).animate( anim
, config
.duration
|| 'fast' );
1371 $sc
.queue( function ( next
) {
1384 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1385 * and reserve space for them, because it probably doesn't.
1387 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1388 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1389 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1390 * and then reattach (or show) them back.
1393 * @param {HTMLElement} el Element to reconsider the scrollbars on
1395 OO
.ui
.Element
.static.reconsiderScrollbars = function ( el
) {
1396 var i
, len
, nodes
= [];
1397 // Detach all children
1398 while ( el
.firstChild
) {
1399 nodes
.push( el
.firstChild
);
1400 el
.removeChild( el
.firstChild
);
1403 void el
.offsetHeight
;
1404 // Reattach all children
1405 for ( i
= 0, len
= nodes
.length
; i
< len
; i
++ ) {
1406 el
.appendChild( nodes
[ i
] );
1413 * Toggle visibility of an element.
1415 * @param {boolean} [show] Make element visible, omit to toggle visibility
1419 OO
.ui
.Element
.prototype.toggle = function ( show
) {
1420 show
= show
=== undefined ? !this.visible
: !!show
;
1422 if ( show
!== this.isVisible() ) {
1423 this.visible
= show
;
1424 this.$element
.toggleClass( 'oo-ui-element-hidden', !this.visible
);
1425 this.emit( 'toggle', show
);
1432 * Check if element is visible.
1434 * @return {boolean} element is visible
1436 OO
.ui
.Element
.prototype.isVisible = function () {
1437 return this.visible
;
1443 * @return {Mixed} Element data
1445 OO
.ui
.Element
.prototype.getData = function () {
1452 * @param {Mixed} Element data
1455 OO
.ui
.Element
.prototype.setData = function ( data
) {
1461 * Check if element supports one or more methods.
1463 * @param {string|string[]} methods Method or list of methods to check
1464 * @return {boolean} All methods are supported
1466 OO
.ui
.Element
.prototype.supports = function ( methods
) {
1470 methods
= Array
.isArray( methods
) ? methods
: [ methods
];
1471 for ( i
= 0, len
= methods
.length
; i
< len
; i
++ ) {
1472 if ( $.isFunction( this[ methods
[ i
] ] ) ) {
1477 return methods
.length
=== support
;
1481 * Update the theme-provided classes.
1483 * @localdoc This is called in element mixins and widget classes any time state changes.
1484 * Updating is debounced, minimizing overhead of changing multiple attributes and
1485 * guaranteeing that theme updates do not occur within an element's constructor
1487 OO
.ui
.Element
.prototype.updateThemeClasses = function () {
1488 if ( !this.updateThemeClassesPending
) {
1489 this.updateThemeClassesPending
= true;
1490 setTimeout( this.debouncedUpdateThemeClassesHandler
);
1497 OO
.ui
.Element
.prototype.debouncedUpdateThemeClasses = function () {
1498 OO
.ui
.theme
.updateElementClasses( this );
1499 this.updateThemeClassesPending
= false;
1503 * Get the HTML tag name.
1505 * Override this method to base the result on instance information.
1507 * @return {string} HTML tag name
1509 OO
.ui
.Element
.prototype.getTagName = function () {
1510 return this.constructor.static.tagName
;
1514 * Check if the element is attached to the DOM
1515 * @return {boolean} The element is attached to the DOM
1517 OO
.ui
.Element
.prototype.isElementAttached = function () {
1518 return $.contains( this.getElementDocument(), this.$element
[ 0 ] );
1522 * Get the DOM document.
1524 * @return {HTMLDocument} Document object
1526 OO
.ui
.Element
.prototype.getElementDocument = function () {
1527 // Don't cache this in other ways either because subclasses could can change this.$element
1528 return OO
.ui
.Element
.static.getDocument( this.$element
);
1532 * Get the DOM window.
1534 * @return {Window} Window object
1536 OO
.ui
.Element
.prototype.getElementWindow = function () {
1537 return OO
.ui
.Element
.static.getWindow( this.$element
);
1541 * Get closest scrollable container.
1543 OO
.ui
.Element
.prototype.getClosestScrollableElementContainer = function () {
1544 return OO
.ui
.Element
.static.getClosestScrollableContainer( this.$element
[ 0 ] );
1548 * Get group element is in.
1550 * @return {OO.ui.GroupElement|null} Group element, null if none
1552 OO
.ui
.Element
.prototype.getElementGroup = function () {
1553 return this.elementGroup
;
1557 * Set group element is in.
1559 * @param {OO.ui.GroupElement|null} group Group element, null if none
1562 OO
.ui
.Element
.prototype.setElementGroup = function ( group
) {
1563 this.elementGroup
= group
;
1568 * Scroll element into view.
1570 * @param {Object} [config] Configuration options
1572 OO
.ui
.Element
.prototype.scrollElementIntoView = function ( config
) {
1573 return OO
.ui
.Element
.static.scrollIntoView( this.$element
[ 0 ], config
);
1577 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1578 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1579 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1580 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1581 * and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1585 * @extends OO.ui.Element
1586 * @mixins OO.EventEmitter
1589 * @param {Object} [config] Configuration options
1591 OO
.ui
.Layout
= function OoUiLayout( config
) {
1592 // Configuration initialization
1593 config
= config
|| {};
1595 // Parent constructor
1596 OO
.ui
.Layout
.super.call( this, config
);
1598 // Mixin constructors
1599 OO
.EventEmitter
.call( this );
1602 this.$element
.addClass( 'oo-ui-layout' );
1607 OO
.inheritClass( OO
.ui
.Layout
, OO
.ui
.Element
);
1608 OO
.mixinClass( OO
.ui
.Layout
, OO
.EventEmitter
);
1611 * Widgets are compositions of one or more OOjs UI elements that users can both view
1612 * and interact with. All widgets can be configured and modified via a standard API,
1613 * and their state can change dynamically according to a model.
1617 * @extends OO.ui.Element
1618 * @mixins OO.EventEmitter
1621 * @param {Object} [config] Configuration options
1622 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1623 * appearance reflects this state.
1625 OO
.ui
.Widget
= function OoUiWidget( config
) {
1626 // Initialize config
1627 config
= $.extend( { disabled
: false }, config
);
1629 // Parent constructor
1630 OO
.ui
.Widget
.super.call( this, config
);
1632 // Mixin constructors
1633 OO
.EventEmitter
.call( this );
1636 this.disabled
= null;
1637 this.wasDisabled
= null;
1640 this.$element
.addClass( 'oo-ui-widget' );
1641 this.setDisabled( !!config
.disabled
);
1646 OO
.inheritClass( OO
.ui
.Widget
, OO
.ui
.Element
);
1647 OO
.mixinClass( OO
.ui
.Widget
, OO
.EventEmitter
);
1654 * A 'disable' event is emitted when a widget is disabled.
1656 * @param {boolean} disabled Widget is disabled
1662 * A 'toggle' event is emitted when the visibility of the widget changes.
1664 * @param {boolean} visible Widget is visible
1670 * Check if the widget is disabled.
1672 * @return {boolean} Widget is disabled
1674 OO
.ui
.Widget
.prototype.isDisabled = function () {
1675 return this.disabled
;
1679 * Set the 'disabled' state of the widget.
1681 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1683 * @param {boolean} disabled Disable widget
1686 OO
.ui
.Widget
.prototype.setDisabled = function ( disabled
) {
1689 this.disabled
= !!disabled
;
1690 isDisabled
= this.isDisabled();
1691 if ( isDisabled
!== this.wasDisabled
) {
1692 this.$element
.toggleClass( 'oo-ui-widget-disabled', isDisabled
);
1693 this.$element
.toggleClass( 'oo-ui-widget-enabled', !isDisabled
);
1694 this.$element
.attr( 'aria-disabled', isDisabled
.toString() );
1695 this.emit( 'disable', isDisabled
);
1696 this.updateThemeClasses();
1698 this.wasDisabled
= isDisabled
;
1704 * Update the disabled state, in case of changes in parent widget.
1708 OO
.ui
.Widget
.prototype.updateDisabled = function () {
1709 this.setDisabled( this.disabled
);
1714 * A window is a container for elements that are in a child frame. They are used with
1715 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
1716 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
1717 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
1718 * the window manager will choose a sensible fallback.
1720 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
1721 * different processes are executed:
1723 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
1724 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
1727 * - {@link #getSetupProcess} method is called and its result executed
1728 * - {@link #getReadyProcess} method is called and its result executed
1730 * **opened**: The window is now open
1732 * **closing**: The closing stage begins when the window manager's
1733 * {@link OO.ui.WindowManager#closeWindow closeWindow}
1734 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
1736 * - {@link #getHoldProcess} method is called and its result executed
1737 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
1739 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
1740 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
1741 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
1742 * processing can complete. Always assume window processes are executed asynchronously.
1744 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
1746 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
1750 * @extends OO.ui.Element
1751 * @mixins OO.EventEmitter
1754 * @param {Object} [config] Configuration options
1755 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
1756 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
1758 OO
.ui
.Window
= function OoUiWindow( config
) {
1759 // Configuration initialization
1760 config
= config
|| {};
1762 // Parent constructor
1763 OO
.ui
.Window
.super.call( this, config
);
1765 // Mixin constructors
1766 OO
.EventEmitter
.call( this );
1769 this.manager
= null;
1770 this.size
= config
.size
|| this.constructor.static.size
;
1771 this.$frame
= $( '<div>' );
1772 this.$overlay
= $( '<div>' );
1773 this.$content
= $( '<div>' );
1776 this.$overlay
.addClass( 'oo-ui-window-overlay' );
1778 .addClass( 'oo-ui-window-content' )
1779 .attr( 'tabIndex', 0 );
1781 .addClass( 'oo-ui-window-frame' )
1782 .append( this.$content
);
1785 .addClass( 'oo-ui-window' )
1786 .append( this.$frame
, this.$overlay
);
1788 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
1789 // that reference properties not initialized at that time of parent class construction
1790 // TODO: Find a better way to handle post-constructor setup
1791 this.visible
= false;
1792 this.$element
.addClass( 'oo-ui-element-hidden' );
1797 OO
.inheritClass( OO
.ui
.Window
, OO
.ui
.Element
);
1798 OO
.mixinClass( OO
.ui
.Window
, OO
.EventEmitter
);
1800 /* Static Properties */
1803 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
1805 * The static size is used if no #size is configured during construction.
1809 * @property {string}
1811 OO
.ui
.Window
.static.size
= 'medium';
1816 * Handle mouse down events.
1819 * @param {jQuery.Event} e Mouse down event
1821 OO
.ui
.Window
.prototype.onMouseDown = function ( e
) {
1822 // Prevent clicking on the click-block from stealing focus
1823 if ( e
.target
=== this.$element
[ 0 ] ) {
1829 * Check if the window has been initialized.
1831 * Initialization occurs when a window is added to a manager.
1833 * @return {boolean} Window has been initialized
1835 OO
.ui
.Window
.prototype.isInitialized = function () {
1836 return !!this.manager
;
1840 * Check if the window is visible.
1842 * @return {boolean} Window is visible
1844 OO
.ui
.Window
.prototype.isVisible = function () {
1845 return this.visible
;
1849 * Check if the window is opening.
1851 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
1854 * @return {boolean} Window is opening
1856 OO
.ui
.Window
.prototype.isOpening = function () {
1857 return this.manager
.isOpening( this );
1861 * Check if the window is closing.
1863 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
1865 * @return {boolean} Window is closing
1867 OO
.ui
.Window
.prototype.isClosing = function () {
1868 return this.manager
.isClosing( this );
1872 * Check if the window is opened.
1874 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
1876 * @return {boolean} Window is opened
1878 OO
.ui
.Window
.prototype.isOpened = function () {
1879 return this.manager
.isOpened( this );
1883 * Get the window manager.
1885 * All windows must be attached to a window manager, which is used to open
1886 * and close the window and control its presentation.
1888 * @return {OO.ui.WindowManager} Manager of window
1890 OO
.ui
.Window
.prototype.getManager = function () {
1891 return this.manager
;
1895 * Get the symbolic name of the window size (e.g., `small` or `medium`).
1897 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
1899 OO
.ui
.Window
.prototype.getSize = function () {
1904 * Disable transitions on window's frame for the duration of the callback function, then enable them
1908 * @param {Function} callback Function to call while transitions are disabled
1910 OO
.ui
.Window
.prototype.withoutSizeTransitions = function ( callback
) {
1911 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
1912 // Disable transitions first, otherwise we'll get values from when the window was animating.
1914 styleObj
= this.$frame
[ 0 ].style
;
1915 oldTransition
= styleObj
.transition
|| styleObj
.OTransition
|| styleObj
.MsTransition
||
1916 styleObj
.MozTransition
|| styleObj
.WebkitTransition
;
1917 styleObj
.transition
= styleObj
.OTransition
= styleObj
.MsTransition
=
1918 styleObj
.MozTransition
= styleObj
.WebkitTransition
= 'none';
1920 // Force reflow to make sure the style changes done inside callback really are not transitioned
1921 this.$frame
.height();
1922 styleObj
.transition
= styleObj
.OTransition
= styleObj
.MsTransition
=
1923 styleObj
.MozTransition
= styleObj
.WebkitTransition
= oldTransition
;
1927 * Get the height of the full window contents (i.e., the window head, body and foot together).
1929 * What consistitutes the head, body, and foot varies depending on the window type.
1930 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
1931 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
1932 * and special actions in the head, and dialog content in the body.
1934 * To get just the height of the dialog body, use the #getBodyHeight method.
1936 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
1938 OO
.ui
.Window
.prototype.getContentHeight = function () {
1941 bodyStyleObj
= this.$body
[ 0 ].style
,
1942 frameStyleObj
= this.$frame
[ 0 ].style
;
1944 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
1945 // Disable transitions first, otherwise we'll get values from when the window was animating.
1946 this.withoutSizeTransitions( function () {
1947 var oldHeight
= frameStyleObj
.height
,
1948 oldPosition
= bodyStyleObj
.position
;
1949 frameStyleObj
.height
= '1px';
1950 // Force body to resize to new width
1951 bodyStyleObj
.position
= 'relative';
1952 bodyHeight
= win
.getBodyHeight();
1953 frameStyleObj
.height
= oldHeight
;
1954 bodyStyleObj
.position
= oldPosition
;
1958 // Add buffer for border
1959 ( this.$frame
.outerHeight() - this.$frame
.innerHeight() ) +
1960 // Use combined heights of children
1961 ( this.$head
.outerHeight( true ) + bodyHeight
+ this.$foot
.outerHeight( true ) )
1966 * Get the height of the window body.
1968 * To get the height of the full window contents (the window body, head, and foot together),
1969 * use #getContentHeight.
1971 * When this function is called, the window will temporarily have been resized
1972 * to height=1px, so .scrollHeight measurements can be taken accurately.
1974 * @return {number} Height of the window body in pixels
1976 OO
.ui
.Window
.prototype.getBodyHeight = function () {
1977 return this.$body
[ 0 ].scrollHeight
;
1981 * Get the directionality of the frame (right-to-left or left-to-right).
1983 * @return {string} Directionality: `'ltr'` or `'rtl'`
1985 OO
.ui
.Window
.prototype.getDir = function () {
1990 * Get the 'setup' process.
1992 * The setup process is used to set up a window for use in a particular context,
1993 * based on the `data` argument. This method is called during the opening phase of the window’s
1996 * Override this method to add additional steps to the ‘setup’ process the parent method provides
1997 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2000 * To add window content that persists between openings, you may wish to use the #initialize method
2004 * @param {Object} [data] Window opening data
2005 * @return {OO.ui.Process} Setup process
2007 OO
.ui
.Window
.prototype.getSetupProcess = function () {
2008 return new OO
.ui
.Process();
2012 * Get the ‘ready’ process.
2014 * The ready process is used to ready a window for use in a particular
2015 * context, based on the `data` argument. This method is called during the opening phase of
2016 * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
2018 * Override this method to add additional steps to the ‘ready’ process the parent method
2019 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
2020 * methods of OO.ui.Process.
2023 * @param {Object} [data] Window opening data
2024 * @return {OO.ui.Process} Ready process
2026 OO
.ui
.Window
.prototype.getReadyProcess = function () {
2027 return new OO
.ui
.Process();
2031 * Get the 'hold' process.
2033 * The hold proccess is used to keep a window from being used in a particular context,
2034 * based on the `data` argument. This method is called during the closing phase of the window’s
2037 * Override this method to add additional steps to the 'hold' process the parent method provides
2038 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2042 * @param {Object} [data] Window closing data
2043 * @return {OO.ui.Process} Hold process
2045 OO
.ui
.Window
.prototype.getHoldProcess = function () {
2046 return new OO
.ui
.Process();
2050 * Get the ‘teardown’ process.
2052 * The teardown process is used to teardown a window after use. During teardown,
2053 * user interactions within the window are conveyed and the window is closed, based on the `data`
2054 * argument. This method is called during the closing phase of the window’s lifecycle.
2056 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
2057 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2061 * @param {Object} [data] Window closing data
2062 * @return {OO.ui.Process} Teardown process
2064 OO
.ui
.Window
.prototype.getTeardownProcess = function () {
2065 return new OO
.ui
.Process();
2069 * Set the window manager.
2071 * This will cause the window to initialize. Calling it more than once will cause an error.
2073 * @param {OO.ui.WindowManager} manager Manager for this window
2074 * @throws {Error} An error is thrown if the method is called more than once
2077 OO
.ui
.Window
.prototype.setManager = function ( manager
) {
2078 if ( this.manager
) {
2079 throw new Error( 'Cannot set window manager, window already has a manager' );
2082 this.manager
= manager
;
2089 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2091 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2095 OO
.ui
.Window
.prototype.setSize = function ( size
) {
2102 * Update the window size.
2104 * @throws {Error} An error is thrown if the window is not attached to a window manager
2107 OO
.ui
.Window
.prototype.updateSize = function () {
2108 if ( !this.manager
) {
2109 throw new Error( 'Cannot update window size, must be attached to a manager' );
2112 this.manager
.updateWindowSize( this );
2118 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2119 * when the window is opening. In general, setDimensions should not be called directly.
2121 * To set the size of the window, use the #setSize method.
2123 * @param {Object} dim CSS dimension properties
2124 * @param {string|number} [dim.width] Width
2125 * @param {string|number} [dim.minWidth] Minimum width
2126 * @param {string|number} [dim.maxWidth] Maximum width
2127 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2128 * @param {string|number} [dim.minWidth] Minimum height
2129 * @param {string|number} [dim.maxWidth] Maximum height
2132 OO
.ui
.Window
.prototype.setDimensions = function ( dim
) {
2135 styleObj
= this.$frame
[ 0 ].style
;
2137 // Calculate the height we need to set using the correct width
2138 if ( dim
.height
=== undefined ) {
2139 this.withoutSizeTransitions( function () {
2140 var oldWidth
= styleObj
.width
;
2141 win
.$frame
.css( 'width', dim
.width
|| '' );
2142 height
= win
.getContentHeight();
2143 styleObj
.width
= oldWidth
;
2146 height
= dim
.height
;
2150 width
: dim
.width
|| '',
2151 minWidth
: dim
.minWidth
|| '',
2152 maxWidth
: dim
.maxWidth
|| '',
2153 height
: height
|| '',
2154 minHeight
: dim
.minHeight
|| '',
2155 maxHeight
: dim
.maxHeight
|| ''
2162 * Initialize window contents.
2164 * Before the window is opened for the first time, #initialize is called so that content that
2165 * persists between openings can be added to the window.
2167 * To set up a window with new content each time the window opens, use #getSetupProcess.
2169 * @throws {Error} An error is thrown if the window is not attached to a window manager
2172 OO
.ui
.Window
.prototype.initialize = function () {
2173 if ( !this.manager
) {
2174 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2178 this.$head
= $( '<div>' );
2179 this.$body
= $( '<div>' );
2180 this.$foot
= $( '<div>' );
2181 this.dir
= OO
.ui
.Element
.static.getDir( this.$content
) || 'ltr';
2182 this.$document
= $( this.getElementDocument() );
2185 this.$element
.on( 'mousedown', this.onMouseDown
.bind( this ) );
2188 this.$head
.addClass( 'oo-ui-window-head' );
2189 this.$body
.addClass( 'oo-ui-window-body' );
2190 this.$foot
.addClass( 'oo-ui-window-foot' );
2191 this.$content
.append( this.$head
, this.$body
, this.$foot
);
2199 * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
2200 * method, which returns a promise resolved when the window is done opening.
2202 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2204 * @param {Object} [data] Window opening data
2205 * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
2206 * if the window fails to open. When the promise is resolved successfully, the first argument of the
2207 * value is a new promise, which is resolved when the window begins closing.
2208 * @throws {Error} An error is thrown if the window is not attached to a window manager
2210 OO
.ui
.Window
.prototype.open = function ( data
) {
2211 if ( !this.manager
) {
2212 throw new Error( 'Cannot open window, must be attached to a manager' );
2215 return this.manager
.openWindow( this, data
);
2221 * This method is a wrapper around a call to the window
2222 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
2223 * which returns a closing promise resolved when the window is done closing.
2225 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2226 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2227 * the window closes.
2229 * @param {Object} [data] Window closing data
2230 * @return {jQuery.Promise} Promise resolved when window is closed
2231 * @throws {Error} An error is thrown if the window is not attached to a window manager
2233 OO
.ui
.Window
.prototype.close = function ( data
) {
2234 if ( !this.manager
) {
2235 throw new Error( 'Cannot close window, must be attached to a manager' );
2238 return this.manager
.closeWindow( this, data
);
2244 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2247 * @param {Object} [data] Window opening data
2248 * @return {jQuery.Promise} Promise resolved when window is setup
2250 OO
.ui
.Window
.prototype.setup = function ( data
) {
2252 deferred
= $.Deferred();
2254 this.toggle( true );
2256 this.getSetupProcess( data
).execute().done( function () {
2257 // Force redraw by asking the browser to measure the elements' widths
2258 win
.$element
.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2259 win
.$content
.addClass( 'oo-ui-window-content-setup' ).width();
2263 return deferred
.promise();
2269 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2272 * @param {Object} [data] Window opening data
2273 * @return {jQuery.Promise} Promise resolved when window is ready
2275 OO
.ui
.Window
.prototype.ready = function ( data
) {
2277 deferred
= $.Deferred();
2279 this.$content
.focus();
2280 this.getReadyProcess( data
).execute().done( function () {
2281 // Force redraw by asking the browser to measure the elements' widths
2282 win
.$element
.addClass( 'oo-ui-window-ready' ).width();
2283 win
.$content
.addClass( 'oo-ui-window-content-ready' ).width();
2287 return deferred
.promise();
2293 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2296 * @param {Object} [data] Window closing data
2297 * @return {jQuery.Promise} Promise resolved when window is held
2299 OO
.ui
.Window
.prototype.hold = function ( data
) {
2301 deferred
= $.Deferred();
2303 this.getHoldProcess( data
).execute().done( function () {
2304 // Get the focused element within the window's content
2305 var $focus
= win
.$content
.find( OO
.ui
.Element
.static.getDocument( win
.$content
).activeElement
);
2307 // Blur the focused element
2308 if ( $focus
.length
) {
2312 // Force redraw by asking the browser to measure the elements' widths
2313 win
.$element
.removeClass( 'oo-ui-window-ready' ).width();
2314 win
.$content
.removeClass( 'oo-ui-window-content-ready' ).width();
2318 return deferred
.promise();
2324 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2327 * @param {Object} [data] Window closing data
2328 * @return {jQuery.Promise} Promise resolved when window is torn down
2330 OO
.ui
.Window
.prototype.teardown = function ( data
) {
2333 return this.getTeardownProcess( data
).execute()
2334 .done( function () {
2335 // Force redraw by asking the browser to measure the elements' widths
2336 win
.$element
.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2337 win
.$content
.removeClass( 'oo-ui-window-content-setup' ).width();
2338 win
.toggle( false );
2343 * The Dialog class serves as the base class for the other types of dialogs.
2344 * Unless extended to include controls, the rendered dialog box is a simple window
2345 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2346 * which opens, closes, and controls the presentation of the window. See the
2347 * [OOjs UI documentation on MediaWiki] [1] for more information.
2350 * // A simple dialog window.
2351 * function MyDialog( config ) {
2352 * MyDialog.super.call( this, config );
2354 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2355 * MyDialog.prototype.initialize = function () {
2356 * MyDialog.super.prototype.initialize.call( this );
2357 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2358 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2359 * this.$body.append( this.content.$element );
2361 * MyDialog.prototype.getBodyHeight = function () {
2362 * return this.content.$element.outerHeight( true );
2364 * var myDialog = new MyDialog( {
2367 * // Create and append a window manager, which opens and closes the window.
2368 * var windowManager = new OO.ui.WindowManager();
2369 * $( 'body' ).append( windowManager.$element );
2370 * windowManager.addWindows( [ myDialog ] );
2371 * // Open the window!
2372 * windowManager.openWindow( myDialog );
2374 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2378 * @extends OO.ui.Window
2379 * @mixins OO.ui.PendingElement
2382 * @param {Object} [config] Configuration options
2384 OO
.ui
.Dialog
= function OoUiDialog( config
) {
2385 // Parent constructor
2386 OO
.ui
.Dialog
.super.call( this, config
);
2388 // Mixin constructors
2389 OO
.ui
.PendingElement
.call( this );
2392 this.actions
= new OO
.ui
.ActionSet();
2393 this.attachedActions
= [];
2394 this.currentAction
= null;
2395 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
2398 this.actions
.connect( this, {
2399 click
: 'onActionClick',
2400 resize
: 'onActionResize',
2401 change
: 'onActionsChange'
2406 .addClass( 'oo-ui-dialog' )
2407 .attr( 'role', 'dialog' );
2412 OO
.inheritClass( OO
.ui
.Dialog
, OO
.ui
.Window
);
2413 OO
.mixinClass( OO
.ui
.Dialog
, OO
.ui
.PendingElement
);
2415 /* Static Properties */
2418 * Symbolic name of dialog.
2420 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2421 * Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
2423 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2428 * @property {string}
2430 OO
.ui
.Dialog
.static.name
= '';
2435 * The title can be specified as a plaintext string, a {@link OO.ui.LabelElement Label} node, or a function
2436 * that will produce a Label node or string. The title can also be specified with data passed to the
2437 * constructor (see #getSetupProcess). In this case, the static value will be overriden.
2442 * @property {jQuery|string|Function}
2444 OO
.ui
.Dialog
.static.title
= '';
2447 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2449 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2450 * value will be overriden.
2452 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
2456 * @property {Object[]}
2458 OO
.ui
.Dialog
.static.actions
= [];
2461 * Close the dialog when the 'Esc' key is pressed.
2466 * @property {boolean}
2468 OO
.ui
.Dialog
.static.escapable
= true;
2473 * Handle frame document key down events.
2476 * @param {jQuery.Event} e Key down event
2478 OO
.ui
.Dialog
.prototype.onDocumentKeyDown = function ( e
) {
2479 if ( e
.which
=== OO
.ui
.Keys
.ESCAPE
) {
2482 e
.stopPropagation();
2487 * Handle action resized events.
2490 * @param {OO.ui.ActionWidget} action Action that was resized
2492 OO
.ui
.Dialog
.prototype.onActionResize = function () {
2493 // Override in subclass
2497 * Handle action click events.
2500 * @param {OO.ui.ActionWidget} action Action that was clicked
2502 OO
.ui
.Dialog
.prototype.onActionClick = function ( action
) {
2503 if ( !this.isPending() ) {
2504 this.executeAction( action
.getAction() );
2509 * Handle actions change event.
2513 OO
.ui
.Dialog
.prototype.onActionsChange = function () {
2514 this.detachActions();
2515 if ( !this.isClosing() ) {
2516 this.attachActions();
2521 * Get the set of actions used by the dialog.
2523 * @return {OO.ui.ActionSet}
2525 OO
.ui
.Dialog
.prototype.getActions = function () {
2526 return this.actions
;
2530 * Get a process for taking action.
2532 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
2533 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
2534 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
2537 * @param {string} [action] Symbolic name of action
2538 * @return {OO.ui.Process} Action process
2540 OO
.ui
.Dialog
.prototype.getActionProcess = function ( action
) {
2541 return new OO
.ui
.Process()
2542 .next( function () {
2544 // An empty action always closes the dialog without data, which should always be
2545 // safe and make no changes
2554 * @param {Object} [data] Dialog opening data
2555 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
2556 * the {@link #static-title static title}
2557 * @param {Object[]} [data.actions] List of configuration options for each
2558 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
2560 OO
.ui
.Dialog
.prototype.getSetupProcess = function ( data
) {
2564 return OO
.ui
.Dialog
.super.prototype.getSetupProcess
.call( this, data
)
2565 .next( function () {
2566 var config
= this.constructor.static,
2567 actions
= data
.actions
!== undefined ? data
.actions
: config
.actions
;
2569 this.title
.setLabel(
2570 data
.title
!== undefined ? data
.title
: this.constructor.static.title
2572 this.actions
.add( this.getActionWidgets( actions
) );
2574 if ( this.constructor.static.escapable
) {
2575 this.$document
.on( 'keydown', this.onDocumentKeyDownHandler
);
2583 OO
.ui
.Dialog
.prototype.getTeardownProcess = function ( data
) {
2585 return OO
.ui
.Dialog
.super.prototype.getTeardownProcess
.call( this, data
)
2586 .first( function () {
2587 if ( this.constructor.static.escapable
) {
2588 this.$document
.off( 'keydown', this.onDocumentKeyDownHandler
);
2591 this.actions
.clear();
2592 this.currentAction
= null;
2599 OO
.ui
.Dialog
.prototype.initialize = function () {
2601 OO
.ui
.Dialog
.super.prototype.initialize
.call( this );
2604 this.title
= new OO
.ui
.LabelWidget();
2607 this.$content
.addClass( 'oo-ui-dialog-content' );
2608 this.setPendingElement( this.$head
);
2612 * Get action widgets from a list of configs
2614 * @param {Object[]} actions Action widget configs
2615 * @return {OO.ui.ActionWidget[]} Action widgets
2617 OO
.ui
.Dialog
.prototype.getActionWidgets = function ( actions
) {
2618 var i
, len
, widgets
= [];
2619 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
2621 new OO
.ui
.ActionWidget( actions
[ i
] )
2628 * Attach action actions.
2632 OO
.ui
.Dialog
.prototype.attachActions = function () {
2633 // Remember the list of potentially attached actions
2634 this.attachedActions
= this.actions
.get();
2638 * Detach action actions.
2643 OO
.ui
.Dialog
.prototype.detachActions = function () {
2646 // Detach all actions that may have been previously attached
2647 for ( i
= 0, len
= this.attachedActions
.length
; i
< len
; i
++ ) {
2648 this.attachedActions
[ i
].$element
.detach();
2650 this.attachedActions
= [];
2654 * Execute an action.
2656 * @param {string} action Symbolic name of action to execute
2657 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
2659 OO
.ui
.Dialog
.prototype.executeAction = function ( action
) {
2661 this.currentAction
= action
;
2662 return this.getActionProcess( action
).execute()
2663 .always( this.popPending
.bind( this ) );
2667 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
2668 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
2669 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
2670 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
2671 * pertinent data and reused.
2673 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
2674 * `opened`, and `closing`, which represent the primary stages of the cycle:
2676 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
2677 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
2679 * - an `opening` event is emitted with an `opening` promise
2680 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
2681 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
2682 * window and its result executed
2683 * - a `setup` progress notification is emitted from the `opening` promise
2684 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
2685 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
2686 * window and its result executed
2687 * - a `ready` progress notification is emitted from the `opening` promise
2688 * - the `opening` promise is resolved with an `opened` promise
2690 * **Opened**: the window is now open.
2692 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
2693 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
2694 * to close the window.
2696 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
2697 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
2698 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
2699 * window and its result executed
2700 * - a `hold` progress notification is emitted from the `closing` promise
2701 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
2702 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
2703 * window and its result executed
2704 * - a `teardown` progress notification is emitted from the `closing` promise
2705 * - the `closing` promise is resolved. The window is now closed
2707 * See the [OOjs UI documentation on MediaWiki][1] for more information.
2709 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2712 * @extends OO.ui.Element
2713 * @mixins OO.EventEmitter
2716 * @param {Object} [config] Configuration options
2717 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
2718 * Note that window classes that are instantiated with a factory must have
2719 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
2720 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
2722 OO
.ui
.WindowManager
= function OoUiWindowManager( config
) {
2723 // Configuration initialization
2724 config
= config
|| {};
2726 // Parent constructor
2727 OO
.ui
.WindowManager
.super.call( this, config
);
2729 // Mixin constructors
2730 OO
.EventEmitter
.call( this );
2733 this.factory
= config
.factory
;
2734 this.modal
= config
.modal
=== undefined || !!config
.modal
;
2736 this.opening
= null;
2738 this.closing
= null;
2739 this.preparingToOpen
= null;
2740 this.preparingToClose
= null;
2741 this.currentWindow
= null;
2742 this.globalEvents
= false;
2743 this.$ariaHidden
= null;
2744 this.onWindowResizeTimeout
= null;
2745 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
2746 this.afterWindowResizeHandler
= this.afterWindowResize
.bind( this );
2750 .addClass( 'oo-ui-windowManager' )
2751 .toggleClass( 'oo-ui-windowManager-modal', this.modal
);
2756 OO
.inheritClass( OO
.ui
.WindowManager
, OO
.ui
.Element
);
2757 OO
.mixinClass( OO
.ui
.WindowManager
, OO
.EventEmitter
);
2762 * An 'opening' event is emitted when the window begins to be opened.
2765 * @param {OO.ui.Window} win Window that's being opened
2766 * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
2767 * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
2768 * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
2769 * @param {Object} data Window opening data
2773 * A 'closing' event is emitted when the window begins to be closed.
2776 * @param {OO.ui.Window} win Window that's being closed
2777 * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
2778 * is closed successfully. The promise emits `hold` and `teardown` notifications when those
2779 * processes are complete. When the `closing` promise is resolved, the first argument of its value
2780 * is the closing data.
2781 * @param {Object} data Window closing data
2785 * A 'resize' event is emitted when a window is resized.
2788 * @param {OO.ui.Window} win Window that was resized
2791 /* Static Properties */
2794 * Map of the symbolic name of each window size and its CSS properties.
2798 * @property {Object}
2800 OO
.ui
.WindowManager
.static.sizes
= {
2814 // These can be non-numeric because they are never used in calculations
2821 * Symbolic name of the default window size.
2823 * The default size is used if the window's requested size is not recognized.
2827 * @property {string}
2829 OO
.ui
.WindowManager
.static.defaultSize
= 'medium';
2834 * Handle window resize events.
2837 * @param {jQuery.Event} e Window resize event
2839 OO
.ui
.WindowManager
.prototype.onWindowResize = function () {
2840 clearTimeout( this.onWindowResizeTimeout
);
2841 this.onWindowResizeTimeout
= setTimeout( this.afterWindowResizeHandler
, 200 );
2845 * Handle window resize events.
2848 * @param {jQuery.Event} e Window resize event
2850 OO
.ui
.WindowManager
.prototype.afterWindowResize = function () {
2851 if ( this.currentWindow
) {
2852 this.updateWindowSize( this.currentWindow
);
2857 * Check if window is opening.
2859 * @return {boolean} Window is opening
2861 OO
.ui
.WindowManager
.prototype.isOpening = function ( win
) {
2862 return win
=== this.currentWindow
&& !!this.opening
&& this.opening
.state() === 'pending';
2866 * Check if window is closing.
2868 * @return {boolean} Window is closing
2870 OO
.ui
.WindowManager
.prototype.isClosing = function ( win
) {
2871 return win
=== this.currentWindow
&& !!this.closing
&& this.closing
.state() === 'pending';
2875 * Check if window is opened.
2877 * @return {boolean} Window is opened
2879 OO
.ui
.WindowManager
.prototype.isOpened = function ( win
) {
2880 return win
=== this.currentWindow
&& !!this.opened
&& this.opened
.state() === 'pending';
2884 * Check if a window is being managed.
2886 * @param {OO.ui.Window} win Window to check
2887 * @return {boolean} Window is being managed
2889 OO
.ui
.WindowManager
.prototype.hasWindow = function ( win
) {
2892 for ( name
in this.windows
) {
2893 if ( this.windows
[ name
] === win
) {
2902 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
2904 * @param {OO.ui.Window} win Window being opened
2905 * @param {Object} [data] Window opening data
2906 * @return {number} Milliseconds to wait
2908 OO
.ui
.WindowManager
.prototype.getSetupDelay = function () {
2913 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
2915 * @param {OO.ui.Window} win Window being opened
2916 * @param {Object} [data] Window opening data
2917 * @return {number} Milliseconds to wait
2919 OO
.ui
.WindowManager
.prototype.getReadyDelay = function () {
2924 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
2926 * @param {OO.ui.Window} win Window being closed
2927 * @param {Object} [data] Window closing data
2928 * @return {number} Milliseconds to wait
2930 OO
.ui
.WindowManager
.prototype.getHoldDelay = function () {
2935 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
2936 * executing the ‘teardown’ process.
2938 * @param {OO.ui.Window} win Window being closed
2939 * @param {Object} [data] Window closing data
2940 * @return {number} Milliseconds to wait
2942 OO
.ui
.WindowManager
.prototype.getTeardownDelay = function () {
2943 return this.modal
? 250 : 0;
2947 * Get a window by its symbolic name.
2949 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
2950 * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
2951 * for more information about using factories.
2952 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2954 * @param {string} name Symbolic name of the window
2955 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
2956 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
2957 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
2959 OO
.ui
.WindowManager
.prototype.getWindow = function ( name
) {
2960 var deferred
= $.Deferred(),
2961 win
= this.windows
[ name
];
2963 if ( !( win
instanceof OO
.ui
.Window
) ) {
2964 if ( this.factory
) {
2965 if ( !this.factory
.lookup( name
) ) {
2966 deferred
.reject( new OO
.ui
.Error(
2967 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
2970 win
= this.factory
.create( name
);
2971 this.addWindows( [ win
] );
2972 deferred
.resolve( win
);
2975 deferred
.reject( new OO
.ui
.Error(
2976 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
2980 deferred
.resolve( win
);
2983 return deferred
.promise();
2987 * Get current window.
2989 * @return {OO.ui.Window|null} Currently opening/opened/closing window
2991 OO
.ui
.WindowManager
.prototype.getCurrentWindow = function () {
2992 return this.currentWindow
;
2998 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
2999 * @param {Object} [data] Window opening data
3000 * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
3001 * See {@link #event-opening 'opening' event} for more information about `opening` promises.
3004 OO
.ui
.WindowManager
.prototype.openWindow = function ( win
, data
) {
3006 opening
= $.Deferred();
3008 // Argument handling
3009 if ( typeof win
=== 'string' ) {
3010 return this.getWindow( win
).then( function ( win
) {
3011 return manager
.openWindow( win
, data
);
3016 if ( !this.hasWindow( win
) ) {
3017 opening
.reject( new OO
.ui
.Error(
3018 'Cannot open window: window is not attached to manager'
3020 } else if ( this.preparingToOpen
|| this.opening
|| this.opened
) {
3021 opening
.reject( new OO
.ui
.Error(
3022 'Cannot open window: another window is opening or open'
3027 if ( opening
.state() !== 'rejected' ) {
3028 // If a window is currently closing, wait for it to complete
3029 this.preparingToOpen
= $.when( this.closing
);
3030 // Ensure handlers get called after preparingToOpen is set
3031 this.preparingToOpen
.done( function () {
3032 if ( manager
.modal
) {
3033 manager
.toggleGlobalEvents( true );
3034 manager
.toggleAriaIsolation( true );
3036 manager
.currentWindow
= win
;
3037 manager
.opening
= opening
;
3038 manager
.preparingToOpen
= null;
3039 manager
.emit( 'opening', win
, opening
, data
);
3040 setTimeout( function () {
3041 win
.setup( data
).then( function () {
3042 manager
.updateWindowSize( win
);
3043 manager
.opening
.notify( { state
: 'setup' } );
3044 setTimeout( function () {
3045 win
.ready( data
).then( function () {
3046 manager
.opening
.notify( { state
: 'ready' } );
3047 manager
.opening
= null;
3048 manager
.opened
= $.Deferred();
3049 opening
.resolve( manager
.opened
.promise(), data
);
3051 }, manager
.getReadyDelay() );
3053 }, manager
.getSetupDelay() );
3057 return opening
.promise();
3063 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3064 * @param {Object} [data] Window closing data
3065 * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
3066 * See {@link #event-closing 'closing' event} for more information about closing promises.
3067 * @throws {Error} An error is thrown if the window is not managed by the window manager.
3070 OO
.ui
.WindowManager
.prototype.closeWindow = function ( win
, data
) {
3072 closing
= $.Deferred(),
3075 // Argument handling
3076 if ( typeof win
=== 'string' ) {
3077 win
= this.windows
[ win
];
3078 } else if ( !this.hasWindow( win
) ) {
3084 closing
.reject( new OO
.ui
.Error(
3085 'Cannot close window: window is not attached to manager'
3087 } else if ( win
!== this.currentWindow
) {
3088 closing
.reject( new OO
.ui
.Error(
3089 'Cannot close window: window already closed with different data'
3091 } else if ( this.preparingToClose
|| this.closing
) {
3092 closing
.reject( new OO
.ui
.Error(
3093 'Cannot close window: window already closing with different data'
3098 if ( closing
.state() !== 'rejected' ) {
3099 // If the window is currently opening, close it when it's done
3100 this.preparingToClose
= $.when( this.opening
);
3101 // Ensure handlers get called after preparingToClose is set
3102 this.preparingToClose
.done( function () {
3103 manager
.closing
= closing
;
3104 manager
.preparingToClose
= null;
3105 manager
.emit( 'closing', win
, closing
, data
);
3106 opened
= manager
.opened
;
3107 manager
.opened
= null;
3108 opened
.resolve( closing
.promise(), data
);
3109 setTimeout( function () {
3110 win
.hold( data
).then( function () {
3111 closing
.notify( { state
: 'hold' } );
3112 setTimeout( function () {
3113 win
.teardown( data
).then( function () {
3114 closing
.notify( { state
: 'teardown' } );
3115 if ( manager
.modal
) {
3116 manager
.toggleGlobalEvents( false );
3117 manager
.toggleAriaIsolation( false );
3119 manager
.closing
= null;
3120 manager
.currentWindow
= null;
3121 closing
.resolve( data
);
3123 }, manager
.getTeardownDelay() );
3125 }, manager
.getHoldDelay() );
3129 return closing
.promise();
3133 * Add windows to the window manager.
3135 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
3136 * See the [OOjs ui documentation on MediaWiki] [2] for examples.
3137 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3139 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
3140 * by reference, symbolic name, or explicitly defined symbolic names.
3141 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
3142 * explicit nor a statically configured symbolic name.
3144 OO
.ui
.WindowManager
.prototype.addWindows = function ( windows
) {
3145 var i
, len
, win
, name
, list
;
3147 if ( Array
.isArray( windows
) ) {
3148 // Convert to map of windows by looking up symbolic names from static configuration
3150 for ( i
= 0, len
= windows
.length
; i
< len
; i
++ ) {
3151 name
= windows
[ i
].constructor.static.name
;
3152 if ( typeof name
!== 'string' ) {
3153 throw new Error( 'Cannot add window' );
3155 list
[ name
] = windows
[ i
];
3157 } else if ( OO
.isPlainObject( windows
) ) {
3162 for ( name
in list
) {
3164 this.windows
[ name
] = win
.toggle( false );
3165 this.$element
.append( win
.$element
);
3166 win
.setManager( this );
3171 * Remove the specified windows from the windows manager.
3173 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
3174 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
3175 * longer listens to events, use the #destroy method.
3177 * @param {string[]} names Symbolic names of windows to remove
3178 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3179 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
3181 OO
.ui
.WindowManager
.prototype.removeWindows = function ( names
) {
3182 var i
, len
, win
, name
, cleanupWindow
,
3185 cleanup = function ( name
, win
) {
3186 delete manager
.windows
[ name
];
3187 win
.$element
.detach();
3190 for ( i
= 0, len
= names
.length
; i
< len
; i
++ ) {
3192 win
= this.windows
[ name
];
3194 throw new Error( 'Cannot remove window' );
3196 cleanupWindow
= cleanup
.bind( null, name
, win
);
3197 promises
.push( this.closeWindow( name
).then( cleanupWindow
, cleanupWindow
) );
3200 return $.when
.apply( $, promises
);
3204 * Remove all windows from the window manager.
3206 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
3207 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
3208 * To remove just a subset of windows, use the #removeWindows method.
3210 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3212 OO
.ui
.WindowManager
.prototype.clearWindows = function () {
3213 return this.removeWindows( Object
.keys( this.windows
) );
3217 * Set dialog size. In general, this method should not be called directly.
3219 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3223 OO
.ui
.WindowManager
.prototype.updateWindowSize = function ( win
) {
3224 // Bypass for non-current, and thus invisible, windows
3225 if ( win
!== this.currentWindow
) {
3229 var viewport
= OO
.ui
.Element
.static.getDimensions( win
.getElementWindow() ),
3230 sizes
= this.constructor.static.sizes
,
3231 size
= win
.getSize();
3233 if ( !sizes
[ size
] ) {
3234 size
= this.constructor.static.defaultSize
;
3236 if ( size
!== 'full' && viewport
.rect
.right
- viewport
.rect
.left
< sizes
[ size
].width
) {
3240 this.$element
.toggleClass( 'oo-ui-windowManager-fullscreen', size
=== 'full' );
3241 this.$element
.toggleClass( 'oo-ui-windowManager-floating', size
!== 'full' );
3242 win
.setDimensions( sizes
[ size
] );
3244 this.emit( 'resize', win
);
3250 * Bind or unbind global events for scrolling.
3253 * @param {boolean} [on] Bind global events
3256 OO
.ui
.WindowManager
.prototype.toggleGlobalEvents = function ( on
) {
3257 on
= on
=== undefined ? !!this.globalEvents
: !!on
;
3259 var scrollWidth
, bodyMargin
,
3260 $body
= $( this.getElementDocument().body
),
3261 // We could have multiple window managers open so only modify
3262 // the body css at the bottom of the stack
3263 stackDepth
= $body
.data( 'windowManagerGlobalEvents' ) || 0 ;
3266 if ( !this.globalEvents
) {
3267 $( this.getElementWindow() ).on( {
3268 // Start listening for top-level window dimension changes
3269 'orientationchange resize': this.onWindowResizeHandler
3271 if ( stackDepth
=== 0 ) {
3272 scrollWidth
= window
.innerWidth
- document
.documentElement
.clientWidth
;
3273 bodyMargin
= parseFloat( $body
.css( 'margin-right' ) ) || 0;
3276 'margin-right': bodyMargin
+ scrollWidth
3280 this.globalEvents
= true;
3282 } else if ( this.globalEvents
) {
3283 $( this.getElementWindow() ).off( {
3284 // Stop listening for top-level window dimension changes
3285 'orientationchange resize': this.onWindowResizeHandler
3288 if ( stackDepth
=== 0 ) {
3294 this.globalEvents
= false;
3296 $body
.data( 'windowManagerGlobalEvents', stackDepth
);
3302 * Toggle screen reader visibility of content other than the window manager.
3305 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3308 OO
.ui
.WindowManager
.prototype.toggleAriaIsolation = function ( isolate
) {
3309 isolate
= isolate
=== undefined ? !this.$ariaHidden
: !!isolate
;
3312 if ( !this.$ariaHidden
) {
3313 // Hide everything other than the window manager from screen readers
3314 this.$ariaHidden
= $( 'body' )
3316 .not( this.$element
.parentsUntil( 'body' ).last() )
3317 .attr( 'aria-hidden', '' );
3319 } else if ( this.$ariaHidden
) {
3320 // Restore screen reader visibility
3321 this.$ariaHidden
.removeAttr( 'aria-hidden' );
3322 this.$ariaHidden
= null;
3329 * Destroy the window manager.
3331 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
3332 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
3335 OO
.ui
.WindowManager
.prototype.destroy = function () {
3336 this.toggleGlobalEvents( false );
3337 this.toggleAriaIsolation( false );
3338 this.clearWindows();
3339 this.$element
.remove();
3346 * @param {string|jQuery} message Description of error
3347 * @param {Object} [config] Configuration options
3348 * @cfg {boolean} [recoverable=true] Error is recoverable
3349 * @cfg {boolean} [warning=false] Whether this error is a warning or not.
3351 OO
.ui
.Error
= function OoUiError( message
, config
) {
3352 // Allow passing positional parameters inside the config object
3353 if ( OO
.isPlainObject( message
) && config
=== undefined ) {
3355 message
= config
.message
;
3358 // Configuration initialization
3359 config
= config
|| {};
3362 this.message
= message
instanceof jQuery
? message
: String( message
);
3363 this.recoverable
= config
.recoverable
=== undefined || !!config
.recoverable
;
3364 this.warning
= !!config
.warning
;
3369 OO
.initClass( OO
.ui
.Error
);
3374 * Check if error can be recovered from.
3376 * @return {boolean} Error is recoverable
3378 OO
.ui
.Error
.prototype.isRecoverable = function () {
3379 return this.recoverable
;
3383 * Check if the error is a warning
3385 * @return {boolean} Error is warning
3387 OO
.ui
.Error
.prototype.isWarning = function () {
3388 return this.warning
;
3392 * Get error message as DOM nodes.
3394 * @return {jQuery} Error message in DOM nodes
3396 OO
.ui
.Error
.prototype.getMessage = function () {
3397 return this.message
instanceof jQuery
?
3398 this.message
.clone() :
3399 $( '<div>' ).text( this.message
).contents();
3403 * Get error message as text.
3405 * @return {string} Error message
3407 OO
.ui
.Error
.prototype.getMessageText = function () {
3408 return this.message
instanceof jQuery
? this.message
.text() : this.message
;
3412 * Wraps an HTML snippet for use with configuration values which default
3413 * to strings. This bypasses the default html-escaping done to string
3419 * @param {string} [content] HTML content
3421 OO
.ui
.HtmlSnippet
= function OoUiHtmlSnippet( content
) {
3423 this.content
= content
;
3428 OO
.initClass( OO
.ui
.HtmlSnippet
);
3435 * @return {string} Unchanged HTML snippet.
3437 OO
.ui
.HtmlSnippet
.prototype.toString = function () {
3438 return this.content
;
3442 * A list of functions, called in sequence.
3444 * If a function added to a process returns boolean false the process will stop; if it returns an
3445 * object with a `promise` method the process will use the promise to either continue to the next
3446 * step when the promise is resolved or stop when the promise is rejected.
3451 * @param {number|jQuery.Promise|Function} step Time to wait, promise to wait for or function to
3452 * call, see #createStep for more information
3453 * @param {Object} [context=null] Context to call the step function in, ignored if step is a number
3455 * @return {Object} Step object, with `callback` and `context` properties
3457 OO
.ui
.Process = function ( step
, context
) {
3462 if ( step
!== undefined ) {
3463 this.next( step
, context
);
3469 OO
.initClass( OO
.ui
.Process
);
3474 * Start the process.
3476 * @return {jQuery.Promise} Promise that is resolved when all steps have completed or rejected when
3477 * any of the steps return boolean false or a promise which gets rejected; upon stopping the
3478 * process, the remaining steps will not be taken
3480 OO
.ui
.Process
.prototype.execute = function () {
3481 var i
, len
, promise
;
3484 * Continue execution.
3487 * @param {Array} step A function and the context it should be called in
3488 * @return {Function} Function that continues the process
3490 function proceed( step
) {
3491 return function () {
3492 // Execute step in the correct context
3494 result
= step
.callback
.call( step
.context
);
3496 if ( result
=== false ) {
3497 // Use rejected promise for boolean false results
3498 return $.Deferred().reject( [] ).promise();
3500 if ( typeof result
=== 'number' ) {
3502 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3504 // Use a delayed promise for numbers, expecting them to be in milliseconds
3505 deferred
= $.Deferred();
3506 setTimeout( deferred
.resolve
, result
);
3507 return deferred
.promise();
3509 if ( result
instanceof OO
.ui
.Error
) {
3510 // Use rejected promise for error
3511 return $.Deferred().reject( [ result
] ).promise();
3513 if ( Array
.isArray( result
) && result
.length
&& result
[ 0 ] instanceof OO
.ui
.Error
) {
3514 // Use rejected promise for list of errors
3515 return $.Deferred().reject( result
).promise();
3517 // Duck-type the object to see if it can produce a promise
3518 if ( result
&& $.isFunction( result
.promise
) ) {
3519 // Use a promise generated from the result
3520 return result
.promise();
3522 // Use resolved promise for other results
3523 return $.Deferred().resolve().promise();
3527 if ( this.steps
.length
) {
3528 // Generate a chain reaction of promises
3529 promise
= proceed( this.steps
[ 0 ] )();
3530 for ( i
= 1, len
= this.steps
.length
; i
< len
; i
++ ) {
3531 promise
= promise
.then( proceed( this.steps
[ i
] ) );
3534 promise
= $.Deferred().resolve().promise();
3541 * Create a process step.
3544 * @param {number|jQuery.Promise|Function} step
3546 * - Number of milliseconds to wait; or
3547 * - Promise to wait to be resolved; or
3548 * - Function to execute
3549 * - If it returns boolean false the process will stop
3550 * - If it returns an object with a `promise` method the process will use the promise to either
3551 * continue to the next step when the promise is resolved or stop when the promise is rejected
3552 * - If it returns a number, the process will wait for that number of milliseconds before
3554 * @param {Object} [context=null] Context to call the step function in, ignored if step is a number
3556 * @return {Object} Step object, with `callback` and `context` properties
3558 OO
.ui
.Process
.prototype.createStep = function ( step
, context
) {
3559 if ( typeof step
=== 'number' || $.isFunction( step
.promise
) ) {
3561 callback: function () {
3567 if ( $.isFunction( step
) ) {
3573 throw new Error( 'Cannot create process step: number, promise or function expected' );
3577 * Add step to the beginning of the process.
3579 * @inheritdoc #createStep
3580 * @return {OO.ui.Process} this
3583 OO
.ui
.Process
.prototype.first = function ( step
, context
) {
3584 this.steps
.unshift( this.createStep( step
, context
) );
3589 * Add step to the end of the process.
3591 * @inheritdoc #createStep
3592 * @return {OO.ui.Process} this
3595 OO
.ui
.Process
.prototype.next = function ( step
, context
) {
3596 this.steps
.push( this.createStep( step
, context
) );
3601 * Factory for tools.
3604 * @extends OO.Factory
3607 OO
.ui
.ToolFactory
= function OoUiToolFactory() {
3608 // Parent constructor
3609 OO
.ui
.ToolFactory
.super.call( this );
3614 OO
.inheritClass( OO
.ui
.ToolFactory
, OO
.Factory
);
3619 * Get tools from the factory
3621 * @param {Array} include Included tools
3622 * @param {Array} exclude Excluded tools
3623 * @param {Array} promote Promoted tools
3624 * @param {Array} demote Demoted tools
3625 * @return {string[]} List of tools
3627 OO
.ui
.ToolFactory
.prototype.getTools = function ( include
, exclude
, promote
, demote
) {
3628 var i
, len
, included
, promoted
, demoted
,
3632 // Collect included and not excluded tools
3633 included
= OO
.simpleArrayDifference( this.extract( include
), this.extract( exclude
) );
3636 promoted
= this.extract( promote
, used
);
3637 demoted
= this.extract( demote
, used
);
3640 for ( i
= 0, len
= included
.length
; i
< len
; i
++ ) {
3641 if ( !used
[ included
[ i
] ] ) {
3642 auto
.push( included
[ i
] );
3646 return promoted
.concat( auto
).concat( demoted
);
3650 * Get a flat list of names from a list of names or groups.
3652 * Tools can be specified in the following ways:
3654 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
3655 * - All tools in a group: `{ group: 'group-name' }`
3656 * - All tools: `'*'`
3659 * @param {Array|string} collection List of tools
3660 * @param {Object} [used] Object with names that should be skipped as properties; extracted
3661 * names will be added as properties
3662 * @return {string[]} List of extracted names
3664 OO
.ui
.ToolFactory
.prototype.extract = function ( collection
, used
) {
3665 var i
, len
, item
, name
, tool
,
3668 if ( collection
=== '*' ) {
3669 for ( name
in this.registry
) {
3670 tool
= this.registry
[ name
];
3672 // Only add tools by group name when auto-add is enabled
3673 tool
.static.autoAddToCatchall
&&
3674 // Exclude already used tools
3675 ( !used
|| !used
[ name
] )
3679 used
[ name
] = true;
3683 } else if ( Array
.isArray( collection
) ) {
3684 for ( i
= 0, len
= collection
.length
; i
< len
; i
++ ) {
3685 item
= collection
[ i
];
3686 // Allow plain strings as shorthand for named tools
3687 if ( typeof item
=== 'string' ) {
3688 item
= { name
: item
};
3690 if ( OO
.isPlainObject( item
) ) {
3692 for ( name
in this.registry
) {
3693 tool
= this.registry
[ name
];
3695 // Include tools with matching group
3696 tool
.static.group
=== item
.group
&&
3697 // Only add tools by group name when auto-add is enabled
3698 tool
.static.autoAddToGroup
&&
3699 // Exclude already used tools
3700 ( !used
|| !used
[ name
] )
3704 used
[ name
] = true;
3708 // Include tools with matching name and exclude already used tools
3709 } else if ( item
.name
&& ( !used
|| !used
[ item
.name
] ) ) {
3710 names
.push( item
.name
);
3712 used
[ item
.name
] = true;
3722 * Factory for tool groups.
3725 * @extends OO.Factory
3728 OO
.ui
.ToolGroupFactory
= function OoUiToolGroupFactory() {
3729 // Parent constructor
3730 OO
.Factory
.call( this );
3733 defaultClasses
= this.constructor.static.getDefaultClasses();
3735 // Register default toolgroups
3736 for ( i
= 0, l
= defaultClasses
.length
; i
< l
; i
++ ) {
3737 this.register( defaultClasses
[ i
] );
3743 OO
.inheritClass( OO
.ui
.ToolGroupFactory
, OO
.Factory
);
3745 /* Static Methods */
3748 * Get a default set of classes to be registered on construction
3750 * @return {Function[]} Default classes
3752 OO
.ui
.ToolGroupFactory
.static.getDefaultClasses = function () {
3755 OO
.ui
.ListToolGroup
,
3767 * @param {Object} [config] Configuration options
3769 OO
.ui
.Theme
= function OoUiTheme( config
) {
3770 // Configuration initialization
3771 config
= config
|| {};
3776 OO
.initClass( OO
.ui
.Theme
);
3781 * Get a list of classes to be applied to a widget.
3783 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
3784 * otherwise state transitions will not work properly.
3786 * @param {OO.ui.Element} element Element for which to get classes
3787 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
3789 OO
.ui
.Theme
.prototype.getElementClasses = function ( /* element */ ) {
3790 return { on
: [], off
: [] };
3794 * Update CSS classes provided by the theme.
3796 * For elements with theme logic hooks, this should be called any time there's a state change.
3798 * @param {OO.ui.Element} element Element for which to update classes
3799 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
3801 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
3802 var classes
= this.getElementClasses( element
);
3805 .removeClass( classes
.off
.join( ' ' ) )
3806 .addClass( classes
.on
.join( ' ' ) );
3810 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
3811 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
3812 * order in which users will navigate through the focusable elements via the "tab" key.
3815 * // TabIndexedElement is mixed into the ButtonWidget class
3816 * // to provide a tabIndex property.
3817 * var button1 = new OO.ui.ButtonWidget( {
3821 * var button2 = new OO.ui.ButtonWidget( {
3825 * var button3 = new OO.ui.ButtonWidget( {
3829 * var button4 = new OO.ui.ButtonWidget( {
3833 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
3839 * @param {Object} [config] Configuration options
3840 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
3841 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
3842 * functionality will be applied to it instead.
3843 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
3844 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
3845 * to remove the element from the tab-navigation flow.
3847 OO
.ui
.TabIndexedElement
= function OoUiTabIndexedElement( config
) {
3848 // Configuration initialization
3849 config
= $.extend( { tabIndex
: 0 }, config
);
3852 this.$tabIndexed
= null;
3853 this.tabIndex
= null;
3856 this.connect( this, { disable
: 'onDisable' } );
3859 this.setTabIndex( config
.tabIndex
);
3860 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
3865 OO
.initClass( OO
.ui
.TabIndexedElement
);
3870 * Set the element that should use the tabindex functionality.
3872 * This method is used to retarget a tabindex mixin so that its functionality applies
3873 * to the specified element. If an element is currently using the functionality, the mixin’s
3874 * effect on that element is removed before the new element is set up.
3876 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
3879 OO
.ui
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
3880 var tabIndex
= this.tabIndex
;
3881 // Remove attributes from old $tabIndexed
3882 this.setTabIndex( null );
3883 // Force update of new $tabIndexed
3884 this.$tabIndexed
= $tabIndexed
;
3885 this.tabIndex
= tabIndex
;
3886 return this.updateTabIndex();
3890 * Set the value of the tabindex.
3892 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
3895 OO
.ui
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
3896 tabIndex
= typeof tabIndex
=== 'number' ? tabIndex
: null;
3898 if ( this.tabIndex
!== tabIndex
) {
3899 this.tabIndex
= tabIndex
;
3900 this.updateTabIndex();
3907 * Update the `tabindex` attribute, in case of changes to tab index or
3913 OO
.ui
.TabIndexedElement
.prototype.updateTabIndex = function () {
3914 if ( this.$tabIndexed
) {
3915 if ( this.tabIndex
!== null ) {
3916 // Do not index over disabled elements
3917 this.$tabIndexed
.attr( {
3918 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
3919 // ChromeVox and NVDA do not seem to inherit this from parent elements
3920 'aria-disabled': this.isDisabled().toString()
3923 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
3930 * Handle disable events.
3933 * @param {boolean} disabled Element is disabled
3935 OO
.ui
.TabIndexedElement
.prototype.onDisable = function () {
3936 this.updateTabIndex();
3940 * Get the value of the tabindex.
3942 * @return {number|null} Tabindex value
3944 OO
.ui
.TabIndexedElement
.prototype.getTabIndex = function () {
3945 return this.tabIndex
;
3949 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
3950 * interface element that can be configured with access keys for accessibility.
3951 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
3953 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
3958 * @param {Object} [config] Configuration options
3959 * @cfg {jQuery} [$button] The button element created by the class.
3960 * If this configuration is omitted, the button element will use a generated `<a>`.
3961 * @cfg {boolean} [framed=true] Render the button with a frame
3962 * @cfg {string} [accessKey] Button's access key
3964 OO
.ui
.ButtonElement
= function OoUiButtonElement( config
) {
3965 // Configuration initialization
3966 config
= config
|| {};
3969 this.$button
= null;
3971 this.accessKey
= null;
3972 this.active
= false;
3973 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
3974 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
3975 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
3976 this.onKeyUpHandler
= this.onKeyUp
.bind( this );
3977 this.onClickHandler
= this.onClick
.bind( this );
3978 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
3981 this.$element
.addClass( 'oo-ui-buttonElement' );
3982 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
3983 this.setAccessKey( config
.accessKey
);
3984 this.setButtonElement( config
.$button
|| $( '<a>' ) );
3989 OO
.initClass( OO
.ui
.ButtonElement
);
3991 /* Static Properties */
3994 * Cancel mouse down events.
3996 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
3997 * Classes such as {@link OO.ui.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
3998 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
4003 * @property {boolean}
4005 OO
.ui
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
4010 * A 'click' event is emitted when the button element is clicked.
4018 * Set the button element.
4020 * This method is used to retarget a button mixin so that its functionality applies to
4021 * the specified button element instead of the one created by the class. If a button element
4022 * is already set, the method will remove the mixin’s effect on that element.
4024 * @param {jQuery} $button Element to use as button
4026 OO
.ui
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
4027 if ( this.$button
) {
4029 .removeClass( 'oo-ui-buttonElement-button' )
4030 .removeAttr( 'role accesskey' )
4032 mousedown
: this.onMouseDownHandler
,
4033 keydown
: this.onKeyDownHandler
,
4034 click
: this.onClickHandler
,
4035 keypress
: this.onKeyPressHandler
4039 this.$button
= $button
4040 .addClass( 'oo-ui-buttonElement-button' )
4041 .attr( { role
: 'button', accesskey
: this.accessKey
} )
4043 mousedown
: this.onMouseDownHandler
,
4044 keydown
: this.onKeyDownHandler
,
4045 click
: this.onClickHandler
,
4046 keypress
: this.onKeyPressHandler
4051 * Handles mouse down events.
4054 * @param {jQuery.Event} e Mouse down event
4056 OO
.ui
.ButtonElement
.prototype.onMouseDown = function ( e
) {
4057 if ( this.isDisabled() || e
.which
!== 1 ) {
4060 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
4061 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4062 // reliably remove the pressed class
4063 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
4064 // Prevent change of focus unless specifically configured otherwise
4065 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
4071 * Handles mouse up events.
4074 * @param {jQuery.Event} e Mouse up event
4076 OO
.ui
.ButtonElement
.prototype.onMouseUp = function ( e
) {
4077 if ( this.isDisabled() || e
.which
!== 1 ) {
4080 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
4081 // Stop listening for mouseup, since we only needed this once
4082 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
4086 * Handles mouse click events.
4089 * @param {jQuery.Event} e Mouse click event
4092 OO
.ui
.ButtonElement
.prototype.onClick = function ( e
) {
4093 if ( !this.isDisabled() && e
.which
=== 1 ) {
4094 this.emit( 'click' );
4100 * Handles key down events.
4103 * @param {jQuery.Event} e Key down event
4105 OO
.ui
.ButtonElement
.prototype.onKeyDown = function ( e
) {
4106 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
4109 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
4110 // Run the keyup handler no matter where the key is when the button is let go, so we can
4111 // reliably remove the pressed class
4112 this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler
, true );
4116 * Handles key up events.
4119 * @param {jQuery.Event} e Key up event
4121 OO
.ui
.ButtonElement
.prototype.onKeyUp = function ( e
) {
4122 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
4125 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
4126 // Stop listening for keyup, since we only needed this once
4127 this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler
, true );
4131 * Handles key press events.
4134 * @param {jQuery.Event} e Key press event
4137 OO
.ui
.ButtonElement
.prototype.onKeyPress = function ( e
) {
4138 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
4139 this.emit( 'click' );
4145 * Check if button has a frame.
4147 * @return {boolean} Button is framed
4149 OO
.ui
.ButtonElement
.prototype.isFramed = function () {
4154 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
4156 * @param {boolean} [framed] Make button framed, omit to toggle
4159 OO
.ui
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
4160 framed
= framed
=== undefined ? !this.framed
: !!framed
;
4161 if ( framed
!== this.framed
) {
4162 this.framed
= framed
;
4164 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
4165 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
4166 this.updateThemeClasses();
4173 * Set the button's access key.
4175 * @param {string} accessKey Button's access key, use empty string to remove
4178 OO
.ui
.ButtonElement
.prototype.setAccessKey = function ( accessKey
) {
4179 accessKey
= typeof accessKey
=== 'string' && accessKey
.length
? accessKey
: null;
4181 if ( this.accessKey
!== accessKey
) {
4182 if ( this.$button
) {
4183 if ( accessKey
!== null ) {
4184 this.$button
.attr( 'accesskey', accessKey
);
4186 this.$button
.removeAttr( 'accesskey' );
4189 this.accessKey
= accessKey
;
4196 * Set the button to its 'active' state.
4198 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
4199 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
4200 * for other button types.
4202 * @param {boolean} [value] Make button active
4205 OO
.ui
.ButtonElement
.prototype.setActive = function ( value
) {
4206 this.$element
.toggleClass( 'oo-ui-buttonElement-active', !!value
);
4211 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4212 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4213 * items from the group is done through the interface the class provides.
4214 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4216 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4222 * @param {Object} [config] Configuration options
4223 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4224 * is omitted, the group element will use a generated `<div>`.
4226 OO
.ui
.GroupElement
= function OoUiGroupElement( config
) {
4227 // Configuration initialization
4228 config
= config
|| {};
4233 this.aggregateItemEvents
= {};
4236 this.setGroupElement( config
.$group
|| $( '<div>' ) );
4242 * Set the group element.
4244 * If an element is already set, items will be moved to the new element.
4246 * @param {jQuery} $group Element to use as group
4248 OO
.ui
.GroupElement
.prototype.setGroupElement = function ( $group
) {
4251 this.$group
= $group
;
4252 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4253 this.$group
.append( this.items
[ i
].$element
);
4258 * Check if a group contains no items.
4260 * @return {boolean} Group is empty
4262 OO
.ui
.GroupElement
.prototype.isEmpty = function () {
4263 return !this.items
.length
;
4267 * Get all items in the group.
4269 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4270 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4273 * @return {OO.ui.Element[]} An array of items.
4275 OO
.ui
.GroupElement
.prototype.getItems = function () {
4276 return this.items
.slice( 0 );
4280 * Get an item by its data.
4282 * Only the first item with matching data will be returned. To return all matching items,
4283 * use the #getItemsFromData method.
4285 * @param {Object} data Item data to search for
4286 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4288 OO
.ui
.GroupElement
.prototype.getItemFromData = function ( data
) {
4290 hash
= OO
.getHash( data
);
4292 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4293 item
= this.items
[ i
];
4294 if ( hash
=== OO
.getHash( item
.getData() ) ) {
4303 * Get items by their data.
4305 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4307 * @param {Object} data Item data to search for
4308 * @return {OO.ui.Element[]} Items with equivalent data
4310 OO
.ui
.GroupElement
.prototype.getItemsFromData = function ( data
) {
4312 hash
= OO
.getHash( data
),
4315 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4316 item
= this.items
[ i
];
4317 if ( hash
=== OO
.getHash( item
.getData() ) ) {
4326 * Aggregate the events emitted by the group.
4328 * When events are aggregated, the group will listen to all contained items for the event,
4329 * and then emit the event under a new name. The new event will contain an additional leading
4330 * parameter containing the item that emitted the original event. Other arguments emitted from
4331 * the original event are passed through.
4333 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
4334 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
4335 * A `null` value will remove aggregated events.
4337 * @throws {Error} An error is thrown if aggregation already exists.
4339 OO
.ui
.GroupElement
.prototype.aggregate = function ( events
) {
4340 var i
, len
, item
, add
, remove
, itemEvent
, groupEvent
;
4342 for ( itemEvent
in events
) {
4343 groupEvent
= events
[ itemEvent
];
4345 // Remove existing aggregated event
4346 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4347 // Don't allow duplicate aggregations
4349 throw new Error( 'Duplicate item event aggregation for ' + itemEvent
);
4351 // Remove event aggregation from existing items
4352 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4353 item
= this.items
[ i
];
4354 if ( item
.connect
&& item
.disconnect
) {
4356 remove
[ itemEvent
] = [ 'emit', groupEvent
, item
];
4357 item
.disconnect( this, remove
);
4360 // Prevent future items from aggregating event
4361 delete this.aggregateItemEvents
[ itemEvent
];
4364 // Add new aggregate event
4366 // Make future items aggregate event
4367 this.aggregateItemEvents
[ itemEvent
] = groupEvent
;
4368 // Add event aggregation to existing items
4369 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4370 item
= this.items
[ i
];
4371 if ( item
.connect
&& item
.disconnect
) {
4373 add
[ itemEvent
] = [ 'emit', groupEvent
, item
];
4374 item
.connect( this, add
);
4382 * Add items to the group.
4384 * Items will be added to the end of the group array unless the optional `index` parameter specifies
4385 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
4387 * @param {OO.ui.Element[]} items An array of items to add to the group
4388 * @param {number} [index] Index of the insertion point
4391 OO
.ui
.GroupElement
.prototype.addItems = function ( items
, index
) {
4392 var i
, len
, item
, event
, events
, currentIndex
,
4395 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
4398 // Check if item exists then remove it first, effectively "moving" it
4399 currentIndex
= $.inArray( item
, this.items
);
4400 if ( currentIndex
>= 0 ) {
4401 this.removeItems( [ item
] );
4402 // Adjust index to compensate for removal
4403 if ( currentIndex
< index
) {
4408 if ( item
.connect
&& item
.disconnect
&& !$.isEmptyObject( this.aggregateItemEvents
) ) {
4410 for ( event
in this.aggregateItemEvents
) {
4411 events
[ event
] = [ 'emit', this.aggregateItemEvents
[ event
], item
];
4413 item
.connect( this, events
);
4415 item
.setElementGroup( this );
4416 itemElements
.push( item
.$element
.get( 0 ) );
4419 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
4420 this.$group
.append( itemElements
);
4421 this.items
.push
.apply( this.items
, items
);
4422 } else if ( index
=== 0 ) {
4423 this.$group
.prepend( itemElements
);
4424 this.items
.unshift
.apply( this.items
, items
);
4426 this.items
[ index
].$element
.before( itemElements
);
4427 this.items
.splice
.apply( this.items
, [ index
, 0 ].concat( items
) );
4434 * Remove the specified items from a group.
4436 * Removed items are detached (not removed) from the DOM so that they may be reused.
4437 * To remove all items from a group, you may wish to use the #clearItems method instead.
4439 * @param {OO.ui.Element[]} items An array of items to remove
4442 OO
.ui
.GroupElement
.prototype.removeItems = function ( items
) {
4443 var i
, len
, item
, index
, remove
, itemEvent
;
4445 // Remove specific items
4446 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
4448 index
= $.inArray( item
, this.items
);
4449 if ( index
!== -1 ) {
4451 item
.connect
&& item
.disconnect
&&
4452 !$.isEmptyObject( this.aggregateItemEvents
)
4455 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4456 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4458 item
.disconnect( this, remove
);
4460 item
.setElementGroup( null );
4461 this.items
.splice( index
, 1 );
4462 item
.$element
.detach();
4470 * Clear all items from the group.
4472 * Cleared items are detached from the DOM, not removed, so that they may be reused.
4473 * To remove only a subset of items from a group, use the #removeItems method.
4477 OO
.ui
.GroupElement
.prototype.clearItems = function () {
4478 var i
, len
, item
, remove
, itemEvent
;
4481 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4482 item
= this.items
[ i
];
4484 item
.connect
&& item
.disconnect
&&
4485 !$.isEmptyObject( this.aggregateItemEvents
)
4488 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4489 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4491 item
.disconnect( this, remove
);
4493 item
.setElementGroup( null );
4494 item
.$element
.detach();
4502 * DraggableElement is a mixin class used to create elements that can be clicked
4503 * and dragged by a mouse to a new position within a group. This class must be used
4504 * in conjunction with OO.ui.DraggableGroupElement, which provides a container for
4505 * the draggable elements.
4512 OO
.ui
.DraggableElement
= function OoUiDraggableElement() {
4516 // Initialize and events
4518 .attr( 'draggable', true )
4519 .addClass( 'oo-ui-draggableElement' )
4521 dragstart
: this.onDragStart
.bind( this ),
4522 dragover
: this.onDragOver
.bind( this ),
4523 dragend
: this.onDragEnd
.bind( this ),
4524 drop
: this.onDrop
.bind( this )
4528 OO
.initClass( OO
.ui
.DraggableElement
);
4535 * A dragstart event is emitted when the user clicks and begins dragging an item.
4536 * @param {OO.ui.DraggableElement} item The item the user has clicked and is dragging with the mouse.
4541 * A dragend event is emitted when the user drags an item and releases the mouse,
4542 * thus terminating the drag operation.
4547 * A drop event is emitted when the user drags an item and then releases the mouse button
4548 * over a valid target.
4551 /* Static Properties */
4554 * @inheritdoc OO.ui.ButtonElement
4556 OO
.ui
.DraggableElement
.static.cancelButtonMouseDownEvents
= false;
4561 * Respond to dragstart event.
4564 * @param {jQuery.Event} event jQuery event
4567 OO
.ui
.DraggableElement
.prototype.onDragStart = function ( e
) {
4568 var dataTransfer
= e
.originalEvent
.dataTransfer
;
4569 // Define drop effect
4570 dataTransfer
.dropEffect
= 'none';
4571 dataTransfer
.effectAllowed
= 'move';
4572 // We must set up a dataTransfer data property or Firefox seems to
4573 // ignore the fact the element is draggable.
4575 dataTransfer
.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
4577 // The above is only for firefox. No need to set a catch clause
4578 // if it fails, move on.
4580 // Add dragging class
4581 this.$element
.addClass( 'oo-ui-draggableElement-dragging' );
4583 this.emit( 'dragstart', this );
4588 * Respond to dragend event.
4593 OO
.ui
.DraggableElement
.prototype.onDragEnd = function () {
4594 this.$element
.removeClass( 'oo-ui-draggableElement-dragging' );
4595 this.emit( 'dragend' );
4599 * Handle drop event.
4602 * @param {jQuery.Event} event jQuery event
4605 OO
.ui
.DraggableElement
.prototype.onDrop = function ( e
) {
4607 this.emit( 'drop', e
);
4611 * In order for drag/drop to work, the dragover event must
4612 * return false and stop propogation.
4616 OO
.ui
.DraggableElement
.prototype.onDragOver = function ( e
) {
4622 * Store it in the DOM so we can access from the widget drag event
4625 * @param {number} Item index
4627 OO
.ui
.DraggableElement
.prototype.setIndex = function ( index
) {
4628 if ( this.index
!== index
) {
4630 this.$element
.data( 'index', index
);
4638 * @return {number} Item index
4640 OO
.ui
.DraggableElement
.prototype.getIndex = function () {
4645 * DraggableGroupElement is a mixin class used to create a group element to
4646 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
4647 * The class is used with OO.ui.DraggableElement.
4651 * @mixins OO.ui.GroupElement
4654 * @param {Object} [config] Configuration options
4655 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
4656 * should match the layout of the items. Items displayed in a single row
4657 * or in several rows should use horizontal orientation. The vertical orientation should only be
4658 * used when the items are displayed in a single column. Defaults to 'vertical'
4660 OO
.ui
.DraggableGroupElement
= function OoUiDraggableGroupElement( config
) {
4661 // Configuration initialization
4662 config
= config
|| {};
4664 // Parent constructor
4665 OO
.ui
.GroupElement
.call( this, config
);
4668 this.orientation
= config
.orientation
|| 'vertical';
4669 this.dragItem
= null;
4670 this.itemDragOver
= null;
4672 this.sideInsertion
= '';
4676 dragstart
: 'itemDragStart',
4677 dragend
: 'itemDragEnd',
4680 this.connect( this, {
4681 itemDragStart
: 'onItemDragStart',
4682 itemDrop
: 'onItemDrop',
4683 itemDragEnd
: 'onItemDragEnd'
4686 dragover
: $.proxy( this.onDragOver
, this ),
4687 dragleave
: $.proxy( this.onDragLeave
, this )
4691 if ( Array
.isArray( config
.items
) ) {
4692 this.addItems( config
.items
);
4694 this.$placeholder
= $( '<div>' )
4695 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
4697 .addClass( 'oo-ui-draggableGroupElement' )
4698 .append( this.$status
)
4699 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation
=== 'horizontal' )
4700 .prepend( this.$placeholder
);
4704 OO
.mixinClass( OO
.ui
.DraggableGroupElement
, OO
.ui
.GroupElement
);
4709 * A 'reorder' event is emitted when the order of items in the group changes.
4712 * @param {OO.ui.DraggableElement} item Reordered item
4713 * @param {number} [newIndex] New index for the item
4719 * Respond to item drag start event
4722 * @param {OO.ui.DraggableElement} item Dragged item
4724 OO
.ui
.DraggableGroupElement
.prototype.onItemDragStart = function ( item
) {
4727 // Map the index of each object
4728 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4729 this.items
[ i
].setIndex( i
);
4732 if ( this.orientation
=== 'horizontal' ) {
4733 // Set the height of the indicator
4734 this.$placeholder
.css( {
4735 height
: item
.$element
.outerHeight(),
4739 // Set the width of the indicator
4740 this.$placeholder
.css( {
4742 width
: item
.$element
.outerWidth()
4745 this.setDragItem( item
);
4749 * Respond to item drag end event
4753 OO
.ui
.DraggableGroupElement
.prototype.onItemDragEnd = function () {
4754 this.unsetDragItem();
4759 * Handle drop event and switch the order of the items accordingly
4762 * @param {OO.ui.DraggableElement} item Dropped item
4765 OO
.ui
.DraggableGroupElement
.prototype.onItemDrop = function ( item
) {
4766 var toIndex
= item
.getIndex();
4767 // Check if the dropped item is from the current group
4768 // TODO: Figure out a way to configure a list of legally droppable
4769 // elements even if they are not yet in the list
4770 if ( this.getDragItem() ) {
4771 // If the insertion point is 'after', the insertion index
4772 // is shifted to the right (or to the left in RTL, hence 'after')
4773 if ( this.sideInsertion
=== 'after' ) {
4776 // Emit change event
4777 this.emit( 'reorder', this.getDragItem(), toIndex
);
4779 this.unsetDragItem();
4780 // Return false to prevent propogation
4785 * Handle dragleave event.
4789 OO
.ui
.DraggableGroupElement
.prototype.onDragLeave = function () {
4790 // This means the item was dragged outside the widget
4793 .addClass( 'oo-ui-element-hidden' );
4797 * Respond to dragover event
4800 * @param {jQuery.Event} event Event details
4802 OO
.ui
.DraggableGroupElement
.prototype.onDragOver = function ( e
) {
4803 var dragOverObj
, $optionWidget
, itemOffset
, itemMidpoint
, itemBoundingRect
,
4804 itemSize
, cssOutput
, dragPosition
, itemIndex
, itemPosition
,
4805 clientX
= e
.originalEvent
.clientX
,
4806 clientY
= e
.originalEvent
.clientY
;
4808 // Get the OptionWidget item we are dragging over
4809 dragOverObj
= this.getElementDocument().elementFromPoint( clientX
, clientY
);
4810 $optionWidget
= $( dragOverObj
).closest( '.oo-ui-draggableElement' );
4811 if ( $optionWidget
[ 0 ] ) {
4812 itemOffset
= $optionWidget
.offset();
4813 itemBoundingRect
= $optionWidget
[ 0 ].getBoundingClientRect();
4814 itemPosition
= $optionWidget
.position();
4815 itemIndex
= $optionWidget
.data( 'index' );
4820 this.isDragging() &&
4821 itemIndex
!== this.getDragItem().getIndex()
4823 if ( this.orientation
=== 'horizontal' ) {
4824 // Calculate where the mouse is relative to the item width
4825 itemSize
= itemBoundingRect
.width
;
4826 itemMidpoint
= itemBoundingRect
.left
+ itemSize
/ 2;
4827 dragPosition
= clientX
;
4828 // Which side of the item we hover over will dictate
4829 // where the placeholder will appear, on the left or
4832 left
: dragPosition
< itemMidpoint
? itemPosition
.left
: itemPosition
.left
+ itemSize
,
4833 top
: itemPosition
.top
4836 // Calculate where the mouse is relative to the item height
4837 itemSize
= itemBoundingRect
.height
;
4838 itemMidpoint
= itemBoundingRect
.top
+ itemSize
/ 2;
4839 dragPosition
= clientY
;
4840 // Which side of the item we hover over will dictate
4841 // where the placeholder will appear, on the top or
4844 top
: dragPosition
< itemMidpoint
? itemPosition
.top
: itemPosition
.top
+ itemSize
,
4845 left
: itemPosition
.left
4848 // Store whether we are before or after an item to rearrange
4849 // For horizontal layout, we need to account for RTL, as this is flipped
4850 if ( this.orientation
=== 'horizontal' && this.$element
.css( 'direction' ) === 'rtl' ) {
4851 this.sideInsertion
= dragPosition
< itemMidpoint
? 'after' : 'before';
4853 this.sideInsertion
= dragPosition
< itemMidpoint
? 'before' : 'after';
4855 // Add drop indicator between objects
4858 .removeClass( 'oo-ui-element-hidden' );
4860 // This means the item was dragged outside the widget
4863 .addClass( 'oo-ui-element-hidden' );
4870 * Set a dragged item
4872 * @param {OO.ui.DraggableElement} item Dragged item
4874 OO
.ui
.DraggableGroupElement
.prototype.setDragItem = function ( item
) {
4875 this.dragItem
= item
;
4879 * Unset the current dragged item
4881 OO
.ui
.DraggableGroupElement
.prototype.unsetDragItem = function () {
4882 this.dragItem
= null;
4883 this.itemDragOver
= null;
4884 this.$placeholder
.addClass( 'oo-ui-element-hidden' );
4885 this.sideInsertion
= '';
4889 * Get the item that is currently being dragged.
4891 * @return {OO.ui.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
4893 OO
.ui
.DraggableGroupElement
.prototype.getDragItem = function () {
4894 return this.dragItem
;
4898 * Check if an item in the group is currently being dragged.
4900 * @return {Boolean} Item is being dragged
4902 OO
.ui
.DraggableGroupElement
.prototype.isDragging = function () {
4903 return this.getDragItem() !== null;
4907 * IconElement is often mixed into other classes to generate an icon.
4908 * Icons are graphics, about the size of normal text. They are used to aid the user
4909 * in locating a control or to convey information in a space-efficient way. See the
4910 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
4911 * included in the library.
4913 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
4919 * @param {Object} [config] Configuration options
4920 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
4921 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
4922 * the icon element be set to an existing icon instead of the one generated by this class, set a
4923 * value using a jQuery selection. For example:
4925 * // Use a <div> tag instead of a <span>
4927 * // Use an existing icon element instead of the one generated by the class
4928 * $icon: this.$element
4929 * // Use an icon element from a child widget
4930 * $icon: this.childwidget.$element
4931 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
4932 * symbolic names. A map is used for i18n purposes and contains a `default` icon
4933 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
4934 * by the user's language.
4936 * Example of an i18n map:
4938 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
4939 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
4940 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
4941 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
4942 * text. The icon title is displayed when users move the mouse over the icon.
4944 OO
.ui
.IconElement
= function OoUiIconElement( config
) {
4945 // Configuration initialization
4946 config
= config
|| {};
4951 this.iconTitle
= null;
4954 this.setIcon( config
.icon
|| this.constructor.static.icon
);
4955 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
4956 this.setIconElement( config
.$icon
|| $( '<span>' ) );
4961 OO
.initClass( OO
.ui
.IconElement
);
4963 /* Static Properties */
4966 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
4967 * for i18n purposes and contains a `default` icon name and additional names keyed by
4968 * language code. The `default` name is used when no icon is keyed by the user's language.
4970 * Example of an i18n map:
4972 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
4974 * Note: the static property will be overridden if the #icon configuration is used.
4978 * @property {Object|string}
4980 OO
.ui
.IconElement
.static.icon
= null;
4983 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
4984 * function that returns title text, or `null` for no title.
4986 * The static property will be overridden if the #iconTitle configuration is used.
4990 * @property {string|Function|null}
4992 OO
.ui
.IconElement
.static.iconTitle
= null;
4997 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
4998 * applies to the specified icon element instead of the one created by the class. If an icon
4999 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
5000 * and mixin methods will no longer affect the element.
5002 * @param {jQuery} $icon Element to use as icon
5004 OO
.ui
.IconElement
.prototype.setIconElement = function ( $icon
) {
5007 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
5008 .removeAttr( 'title' );
5012 .addClass( 'oo-ui-iconElement-icon' )
5013 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
5014 if ( this.iconTitle
!== null ) {
5015 this.$icon
.attr( 'title', this.iconTitle
);
5020 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
5021 * The icon parameter can also be set to a map of icon names. See the #icon config setting
5024 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
5025 * by language code, or `null` to remove the icon.
5028 OO
.ui
.IconElement
.prototype.setIcon = function ( icon
) {
5029 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
5030 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
5032 if ( this.icon
!== icon
) {
5034 if ( this.icon
!== null ) {
5035 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
5037 if ( icon
!== null ) {
5038 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
5044 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
5045 this.updateThemeClasses();
5051 * Set the icon title. Use `null` to remove the title.
5053 * @param {string|Function|null} iconTitle A text string used as the icon title,
5054 * a function that returns title text, or `null` for no title.
5057 OO
.ui
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
5058 iconTitle
= typeof iconTitle
=== 'function' ||
5059 ( typeof iconTitle
=== 'string' && iconTitle
.length
) ?
5060 OO
.ui
.resolveMsg( iconTitle
) : null;
5062 if ( this.iconTitle
!== iconTitle
) {
5063 this.iconTitle
= iconTitle
;
5065 if ( this.iconTitle
!== null ) {
5066 this.$icon
.attr( 'title', iconTitle
);
5068 this.$icon
.removeAttr( 'title' );
5077 * Get the symbolic name of the icon.
5079 * @return {string} Icon name
5081 OO
.ui
.IconElement
.prototype.getIcon = function () {
5086 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5088 * @return {string} Icon title text
5090 OO
.ui
.IconElement
.prototype.getIconTitle = function () {
5091 return this.iconTitle
;
5095 * IndicatorElement is often mixed into other classes to generate an indicator.
5096 * Indicators are small graphics that are generally used in two ways:
5098 * - To draw attention to the status of an item. For example, an indicator might be
5099 * used to show that an item in a list has errors that need to be resolved.
5100 * - To clarify the function of a control that acts in an exceptional way (a button
5101 * that opens a menu instead of performing an action directly, for example).
5103 * For a list of indicators included in the library, please see the
5104 * [OOjs UI documentation on MediaWiki] [1].
5106 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5112 * @param {Object} [config] Configuration options
5113 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5114 * configuration is omitted, the indicator element will use a generated `<span>`.
5115 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5116 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5118 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5119 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5120 * or a function that returns title text. The indicator title is displayed when users move
5121 * the mouse over the indicator.
5123 OO
.ui
.IndicatorElement
= function OoUiIndicatorElement( config
) {
5124 // Configuration initialization
5125 config
= config
|| {};
5128 this.$indicator
= null;
5129 this.indicator
= null;
5130 this.indicatorTitle
= null;
5133 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
5134 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
5135 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
5140 OO
.initClass( OO
.ui
.IndicatorElement
);
5142 /* Static Properties */
5145 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5146 * The static property will be overridden if the #indicator configuration is used.
5150 * @property {string|null}
5152 OO
.ui
.IndicatorElement
.static.indicator
= null;
5155 * A text string used as the indicator title, a function that returns title text, or `null`
5156 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5160 * @property {string|Function|null}
5162 OO
.ui
.IndicatorElement
.static.indicatorTitle
= null;
5167 * Set the indicator element.
5169 * If an element is already set, it will be cleaned up before setting up the new element.
5171 * @param {jQuery} $indicator Element to use as indicator
5173 OO
.ui
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
5174 if ( this.$indicator
) {
5176 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
5177 .removeAttr( 'title' );
5180 this.$indicator
= $indicator
5181 .addClass( 'oo-ui-indicatorElement-indicator' )
5182 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
5183 if ( this.indicatorTitle
!== null ) {
5184 this.$indicator
.attr( 'title', this.indicatorTitle
);
5189 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5191 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5194 OO
.ui
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
5195 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
5197 if ( this.indicator
!== indicator
) {
5198 if ( this.$indicator
) {
5199 if ( this.indicator
!== null ) {
5200 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
5202 if ( indicator
!== null ) {
5203 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
5206 this.indicator
= indicator
;
5209 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
5210 this.updateThemeClasses();
5216 * Set the indicator title.
5218 * The title is displayed when a user moves the mouse over the indicator.
5220 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5221 * `null` for no indicator title
5224 OO
.ui
.IndicatorElement
.prototype.setIndicatorTitle = function ( indicatorTitle
) {
5225 indicatorTitle
= typeof indicatorTitle
=== 'function' ||
5226 ( typeof indicatorTitle
=== 'string' && indicatorTitle
.length
) ?
5227 OO
.ui
.resolveMsg( indicatorTitle
) : null;
5229 if ( this.indicatorTitle
!== indicatorTitle
) {
5230 this.indicatorTitle
= indicatorTitle
;
5231 if ( this.$indicator
) {
5232 if ( this.indicatorTitle
!== null ) {
5233 this.$indicator
.attr( 'title', indicatorTitle
);
5235 this.$indicator
.removeAttr( 'title' );
5244 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5246 * @return {string} Symbolic name of indicator
5248 OO
.ui
.IndicatorElement
.prototype.getIndicator = function () {
5249 return this.indicator
;
5253 * Get the indicator title.
5255 * The title is displayed when a user moves the mouse over the indicator.
5257 * @return {string} Indicator title text
5259 OO
.ui
.IndicatorElement
.prototype.getIndicatorTitle = function () {
5260 return this.indicatorTitle
;
5264 * LabelElement is often mixed into other classes to generate a label, which
5265 * helps identify the function of an interface element.
5266 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5268 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5274 * @param {Object} [config] Configuration options
5275 * @cfg {jQuery} [$label] The label element created by the class. If this
5276 * configuration is omitted, the label element will use a generated `<span>`.
5277 * @cfg {jQuery|string|Function} [label] The label text. The label can be specified as a plaintext string,
5278 * a jQuery selection of elements, or a function that will produce a string in the future. See the
5279 * [OOjs UI documentation on MediaWiki] [2] for examples.
5280 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5281 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5282 * The label will be truncated to fit if necessary.
5284 OO
.ui
.LabelElement
= function OoUiLabelElement( config
) {
5285 // Configuration initialization
5286 config
= config
|| {};
5291 this.autoFitLabel
= config
.autoFitLabel
=== undefined || !!config
.autoFitLabel
;
5294 this.setLabel( config
.label
|| this.constructor.static.label
);
5295 this.setLabelElement( config
.$label
|| $( '<span>' ) );
5300 OO
.initClass( OO
.ui
.LabelElement
);
5305 * @event labelChange
5306 * @param {string} value
5309 /* Static Properties */
5312 * The label text. The label can be specified as a plaintext string, a function that will
5313 * produce a string in the future, or `null` for no label. The static value will
5314 * be overridden if a label is specified with the #label config option.
5318 * @property {string|Function|null}
5320 OO
.ui
.LabelElement
.static.label
= null;
5325 * Set the label element.
5327 * If an element is already set, it will be cleaned up before setting up the new element.
5329 * @param {jQuery} $label Element to use as label
5331 OO
.ui
.LabelElement
.prototype.setLabelElement = function ( $label
) {
5332 if ( this.$label
) {
5333 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
5336 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
5337 this.setLabelContent( this.label
);
5343 * An empty string will result in the label being hidden. A string containing only whitespace will
5344 * be converted to a single ` `.
5346 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
5347 * text; or null for no label
5350 OO
.ui
.LabelElement
.prototype.setLabel = function ( label
) {
5351 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
5352 label
= ( ( typeof label
=== 'string' && label
.length
) || label
instanceof jQuery
|| label
instanceof OO
.ui
.HtmlSnippet
) ? label
: null;
5354 this.$element
.toggleClass( 'oo-ui-labelElement', !!label
);
5356 if ( this.label
!== label
) {
5357 if ( this.$label
) {
5358 this.setLabelContent( label
);
5361 this.emit( 'labelChange' );
5370 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
5371 * text; or null for no label
5373 OO
.ui
.LabelElement
.prototype.getLabel = function () {
5382 OO
.ui
.LabelElement
.prototype.fitLabel = function () {
5383 if ( this.$label
&& this.$label
.autoEllipsis
&& this.autoFitLabel
) {
5384 this.$label
.autoEllipsis( { hasSpan
: false, tooltip
: true } );
5391 * Set the content of the label.
5393 * Do not call this method until after the label element has been set by #setLabelElement.
5396 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5397 * text; or null for no label
5399 OO
.ui
.LabelElement
.prototype.setLabelContent = function ( label
) {
5400 if ( typeof label
=== 'string' ) {
5401 if ( label
.match( /^\s*$/ ) ) {
5402 // Convert whitespace only string to a single non-breaking space
5403 this.$label
.html( ' ' );
5405 this.$label
.text( label
);
5407 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
5408 this.$label
.html( label
.toString() );
5409 } else if ( label
instanceof jQuery
) {
5410 this.$label
.empty().append( label
);
5412 this.$label
.empty();
5417 * LookupElement is a mixin that creates a {@link OO.ui.TextInputMenuSelectWidget menu} of suggested values for
5418 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
5419 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
5420 * from the lookup menu, that value becomes the value of the input field.
5422 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
5423 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
5424 * re-enable lookups.
5426 * See the [OOjs UI demos][1] for an example.
5428 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
5434 * @param {Object} [config] Configuration options
5435 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
5436 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
5437 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
5438 * By default, the lookup menu is not generated and displayed until the user begins to type.
5440 OO
.ui
.LookupElement
= function OoUiLookupElement( config
) {
5441 // Configuration initialization
5442 config
= config
|| {};
5445 this.$overlay
= config
.$overlay
|| this.$element
;
5446 this.lookupMenu
= new OO
.ui
.TextInputMenuSelectWidget( this, {
5449 $container
: config
.$container
5452 this.allowSuggestionsWhenEmpty
= config
.allowSuggestionsWhenEmpty
|| false;
5454 this.lookupCache
= {};
5455 this.lookupQuery
= null;
5456 this.lookupRequest
= null;
5457 this.lookupsDisabled
= false;
5458 this.lookupInputFocused
= false;
5462 focus
: this.onLookupInputFocus
.bind( this ),
5463 blur
: this.onLookupInputBlur
.bind( this ),
5464 mousedown
: this.onLookupInputMouseDown
.bind( this )
5466 this.connect( this, { change
: 'onLookupInputChange' } );
5467 this.lookupMenu
.connect( this, {
5468 toggle
: 'onLookupMenuToggle',
5469 choose
: 'onLookupMenuItemChoose'
5473 this.$element
.addClass( 'oo-ui-lookupElement' );
5474 this.lookupMenu
.$element
.addClass( 'oo-ui-lookupElement-menu' );
5475 this.$overlay
.append( this.lookupMenu
.$element
);
5481 * Handle input focus event.
5484 * @param {jQuery.Event} e Input focus event
5486 OO
.ui
.LookupElement
.prototype.onLookupInputFocus = function () {
5487 this.lookupInputFocused
= true;
5488 this.populateLookupMenu();
5492 * Handle input blur event.
5495 * @param {jQuery.Event} e Input blur event
5497 OO
.ui
.LookupElement
.prototype.onLookupInputBlur = function () {
5498 this.closeLookupMenu();
5499 this.lookupInputFocused
= false;
5503 * Handle input mouse down event.
5506 * @param {jQuery.Event} e Input mouse down event
5508 OO
.ui
.LookupElement
.prototype.onLookupInputMouseDown = function () {
5509 // Only open the menu if the input was already focused.
5510 // This way we allow the user to open the menu again after closing it with Esc
5511 // by clicking in the input. Opening (and populating) the menu when initially
5512 // clicking into the input is handled by the focus handler.
5513 if ( this.lookupInputFocused
&& !this.lookupMenu
.isVisible() ) {
5514 this.populateLookupMenu();
5519 * Handle input change event.
5522 * @param {string} value New input value
5524 OO
.ui
.LookupElement
.prototype.onLookupInputChange = function () {
5525 if ( this.lookupInputFocused
) {
5526 this.populateLookupMenu();
5531 * Handle the lookup menu being shown/hidden.
5534 * @param {boolean} visible Whether the lookup menu is now visible.
5536 OO
.ui
.LookupElement
.prototype.onLookupMenuToggle = function ( visible
) {
5538 // When the menu is hidden, abort any active request and clear the menu.
5539 // This has to be done here in addition to closeLookupMenu(), because
5540 // MenuSelectWidget will close itself when the user presses Esc.
5541 this.abortLookupRequest();
5542 this.lookupMenu
.clearItems();
5547 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
5550 * @param {OO.ui.MenuOptionWidget|null} item Selected item
5552 OO
.ui
.LookupElement
.prototype.onLookupMenuItemChoose = function ( item
) {
5554 this.setValue( item
.getData() );
5562 * @return {OO.ui.TextInputMenuSelectWidget}
5564 OO
.ui
.LookupElement
.prototype.getLookupMenu = function () {
5565 return this.lookupMenu
;
5569 * Disable or re-enable lookups.
5571 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
5573 * @param {boolean} disabled Disable lookups
5575 OO
.ui
.LookupElement
.prototype.setLookupsDisabled = function ( disabled
) {
5576 this.lookupsDisabled
= !!disabled
;
5580 * Open the menu. If there are no entries in the menu, this does nothing.
5585 OO
.ui
.LookupElement
.prototype.openLookupMenu = function () {
5586 if ( !this.lookupMenu
.isEmpty() ) {
5587 this.lookupMenu
.toggle( true );
5593 * Close the menu, empty it, and abort any pending request.
5598 OO
.ui
.LookupElement
.prototype.closeLookupMenu = function () {
5599 this.lookupMenu
.toggle( false );
5600 this.abortLookupRequest();
5601 this.lookupMenu
.clearItems();
5606 * Request menu items based on the input's current value, and when they arrive,
5607 * populate the menu with these items and show the menu.
5609 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
5614 OO
.ui
.LookupElement
.prototype.populateLookupMenu = function () {
5616 value
= this.getValue();
5618 if ( this.lookupsDisabled
) {
5622 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
5623 if ( !this.allowSuggestionsWhenEmpty
&& value
=== '' ) {
5624 this.closeLookupMenu();
5625 // Skip population if there is already a request pending for the current value
5626 } else if ( value
!== this.lookupQuery
) {
5627 this.getLookupMenuItems()
5628 .done( function ( items
) {
5629 widget
.lookupMenu
.clearItems();
5630 if ( items
.length
) {
5634 widget
.initializeLookupMenuSelection();
5636 widget
.lookupMenu
.toggle( false );
5639 .fail( function () {
5640 widget
.lookupMenu
.clearItems();
5648 * Select and highlight the first selectable item in the menu.
5653 OO
.ui
.LookupElement
.prototype.initializeLookupMenuSelection = function () {
5654 if ( !this.lookupMenu
.getSelectedItem() ) {
5655 this.lookupMenu
.selectItem( this.lookupMenu
.getFirstSelectableItem() );
5657 this.lookupMenu
.highlightItem( this.lookupMenu
.getSelectedItem() );
5661 * Get lookup menu items for the current query.
5664 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
5665 * the done event. If the request was aborted to make way for a subsequent request, this promise
5666 * will not be rejected: it will remain pending forever.
5668 OO
.ui
.LookupElement
.prototype.getLookupMenuItems = function () {
5670 value
= this.getValue(),
5671 deferred
= $.Deferred(),
5674 this.abortLookupRequest();
5675 if ( Object
.prototype.hasOwnProperty
.call( this.lookupCache
, value
) ) {
5676 deferred
.resolve( this.getLookupMenuOptionsFromData( this.lookupCache
[ value
] ) );
5679 this.lookupQuery
= value
;
5680 ourRequest
= this.lookupRequest
= this.getLookupRequest();
5682 .always( function () {
5683 // We need to pop pending even if this is an old request, otherwise
5684 // the widget will remain pending forever.
5685 // TODO: this assumes that an aborted request will fail or succeed soon after
5686 // being aborted, or at least eventually. It would be nice if we could popPending()
5687 // at abort time, but only if we knew that we hadn't already called popPending()
5688 // for that request.
5689 widget
.popPending();
5691 .done( function ( response
) {
5692 // If this is an old request (and aborting it somehow caused it to still succeed),
5693 // ignore its success completely
5694 if ( ourRequest
=== widget
.lookupRequest
) {
5695 widget
.lookupQuery
= null;
5696 widget
.lookupRequest
= null;
5697 widget
.lookupCache
[ value
] = widget
.getLookupCacheDataFromResponse( response
);
5698 deferred
.resolve( widget
.getLookupMenuOptionsFromData( widget
.lookupCache
[ value
] ) );
5701 .fail( function () {
5702 // If this is an old request (or a request failing because it's being aborted),
5703 // ignore its failure completely
5704 if ( ourRequest
=== widget
.lookupRequest
) {
5705 widget
.lookupQuery
= null;
5706 widget
.lookupRequest
= null;
5711 return deferred
.promise();
5715 * Abort the currently pending lookup request, if any.
5719 OO
.ui
.LookupElement
.prototype.abortLookupRequest = function () {
5720 var oldRequest
= this.lookupRequest
;
5722 // First unset this.lookupRequest to the fail handler will notice
5723 // that the request is no longer current
5724 this.lookupRequest
= null;
5725 this.lookupQuery
= null;
5731 * Get a new request object of the current lookup query value.
5735 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
5737 OO
.ui
.LookupElement
.prototype.getLookupRequest = function () {
5738 // Stub, implemented in subclass
5743 * Pre-process data returned by the request from #getLookupRequest.
5745 * The return value of this function will be cached, and any further queries for the given value
5746 * will use the cache rather than doing API requests.
5750 * @param {Mixed} response Response from server
5751 * @return {Mixed} Cached result data
5753 OO
.ui
.LookupElement
.prototype.getLookupCacheDataFromResponse = function () {
5754 // Stub, implemented in subclass
5759 * Get a list of menu option widgets from the (possibly cached) data returned by
5760 * #getLookupCacheDataFromResponse.
5764 * @param {Mixed} data Cached result data, usually an array
5765 * @return {OO.ui.MenuOptionWidget[]} Menu items
5767 OO
.ui
.LookupElement
.prototype.getLookupMenuOptionsFromData = function () {
5768 // Stub, implemented in subclass
5773 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5774 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5775 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5776 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5782 * @param {Object} [config] Configuration options
5783 * @cfg {Object} [popup] Configuration to pass to popup
5784 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5786 OO
.ui
.PopupElement
= function OoUiPopupElement( config
) {
5787 // Configuration initialization
5788 config
= config
|| {};
5791 this.popup
= new OO
.ui
.PopupWidget( $.extend(
5792 { autoClose
: true },
5794 { $autoCloseIgnore
: this.$element
}
5803 * @return {OO.ui.PopupWidget} Popup widget
5805 OO
.ui
.PopupElement
.prototype.getPopup = function () {
5810 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
5811 * additional functionality to an element created by another class. The class provides
5812 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
5813 * which are used to customize the look and feel of a widget to better describe its
5814 * importance and functionality.
5816 * The library currently contains the following styling flags for general use:
5818 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
5819 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
5820 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
5822 * The flags affect the appearance of the buttons:
5825 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
5826 * var button1 = new OO.ui.ButtonWidget( {
5827 * label: 'Constructive',
5828 * flags: 'constructive'
5830 * var button2 = new OO.ui.ButtonWidget( {
5831 * label: 'Destructive',
5832 * flags: 'destructive'
5834 * var button3 = new OO.ui.ButtonWidget( {
5835 * label: 'Progressive',
5836 * flags: 'progressive'
5838 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
5840 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
5841 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
5843 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
5849 * @param {Object} [config] Configuration options
5850 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
5851 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
5852 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
5853 * @cfg {jQuery} [$flagged] The flagged element. By default,
5854 * the flagged functionality is applied to the element created by the class ($element).
5855 * If a different element is specified, the flagged functionality will be applied to it instead.
5857 OO
.ui
.FlaggedElement
= function OoUiFlaggedElement( config
) {
5858 // Configuration initialization
5859 config
= config
|| {};
5863 this.$flagged
= null;
5866 this.setFlags( config
.flags
);
5867 this.setFlaggedElement( config
.$flagged
|| this.$element
);
5874 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
5875 * parameter contains the name of each modified flag and indicates whether it was
5878 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
5879 * that the flag was added, `false` that the flag was removed.
5885 * Set the flagged element.
5887 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
5888 * If an element is already set, the method will remove the mixin’s effect on that element.
5890 * @param {jQuery} $flagged Element that should be flagged
5892 OO
.ui
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
5893 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
5894 return 'oo-ui-flaggedElement-' + flag
;
5897 if ( this.$flagged
) {
5898 this.$flagged
.removeClass( classNames
);
5901 this.$flagged
= $flagged
.addClass( classNames
);
5905 * Check if the specified flag is set.
5907 * @param {string} flag Name of flag
5908 * @return {boolean} The flag is set
5910 OO
.ui
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
5911 return flag
in this.flags
;
5915 * Get the names of all flags set.
5917 * @return {string[]} Flag names
5919 OO
.ui
.FlaggedElement
.prototype.getFlags = function () {
5920 return Object
.keys( this.flags
);
5929 OO
.ui
.FlaggedElement
.prototype.clearFlags = function () {
5930 var flag
, className
,
5933 classPrefix
= 'oo-ui-flaggedElement-';
5935 for ( flag
in this.flags
) {
5936 className
= classPrefix
+ flag
;
5937 changes
[ flag
] = false;
5938 delete this.flags
[ flag
];
5939 remove
.push( className
);
5942 if ( this.$flagged
) {
5943 this.$flagged
.removeClass( remove
.join( ' ' ) );
5946 this.updateThemeClasses();
5947 this.emit( 'flag', changes
);
5953 * Add one or more flags.
5955 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
5956 * or an object keyed by flag name with a boolean value that indicates whether the flag should
5957 * be added (`true`) or removed (`false`).
5961 OO
.ui
.FlaggedElement
.prototype.setFlags = function ( flags
) {
5962 var i
, len
, flag
, className
,
5966 classPrefix
= 'oo-ui-flaggedElement-';
5968 if ( typeof flags
=== 'string' ) {
5969 className
= classPrefix
+ flags
;
5971 if ( !this.flags
[ flags
] ) {
5972 this.flags
[ flags
] = true;
5973 add
.push( className
);
5975 } else if ( Array
.isArray( flags
) ) {
5976 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
5978 className
= classPrefix
+ flag
;
5980 if ( !this.flags
[ flag
] ) {
5981 changes
[ flag
] = true;
5982 this.flags
[ flag
] = true;
5983 add
.push( className
);
5986 } else if ( OO
.isPlainObject( flags
) ) {
5987 for ( flag
in flags
) {
5988 className
= classPrefix
+ flag
;
5989 if ( flags
[ flag
] ) {
5991 if ( !this.flags
[ flag
] ) {
5992 changes
[ flag
] = true;
5993 this.flags
[ flag
] = true;
5994 add
.push( className
);
5998 if ( this.flags
[ flag
] ) {
5999 changes
[ flag
] = false;
6000 delete this.flags
[ flag
];
6001 remove
.push( className
);
6007 if ( this.$flagged
) {
6009 .addClass( add
.join( ' ' ) )
6010 .removeClass( remove
.join( ' ' ) );
6013 this.updateThemeClasses();
6014 this.emit( 'flag', changes
);
6020 * TitledElement is mixed into other classes to provide a `title` attribute.
6021 * Titles are rendered by the browser and are made visible when the user moves
6022 * the mouse over the element. Titles are not visible on touch devices.
6025 * // TitledElement provides a 'title' attribute to the
6026 * // ButtonWidget class
6027 * var button = new OO.ui.ButtonWidget( {
6028 * label: 'Button with Title',
6029 * title: 'I am a button'
6031 * $( 'body' ).append( button.$element );
6037 * @param {Object} [config] Configuration options
6038 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
6039 * If this config is omitted, the title functionality is applied to $element, the
6040 * element created by the class.
6041 * @cfg {string|Function} [title] The title text or a function that returns text. If
6042 * this config is omitted, the value of the {@link #static-title static title} property is used.
6044 OO
.ui
.TitledElement
= function OoUiTitledElement( config
) {
6045 // Configuration initialization
6046 config
= config
|| {};
6049 this.$titled
= null;
6053 this.setTitle( config
.title
|| this.constructor.static.title
);
6054 this.setTitledElement( config
.$titled
|| this.$element
);
6059 OO
.initClass( OO
.ui
.TitledElement
);
6061 /* Static Properties */
6064 * The title text, a function that returns text, or `null` for no title. The value of the static property
6065 * is overridden if the #title config option is used.
6069 * @property {string|Function|null}
6071 OO
.ui
.TitledElement
.static.title
= null;
6076 * Set the titled element.
6078 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6079 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6081 * @param {jQuery} $titled Element that should use the 'titled' functionality
6083 OO
.ui
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
6084 if ( this.$titled
) {
6085 this.$titled
.removeAttr( 'title' );
6088 this.$titled
= $titled
;
6090 this.$titled
.attr( 'title', this.title
);
6097 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6100 OO
.ui
.TitledElement
.prototype.setTitle = function ( title
) {
6101 title
= typeof title
=== 'string' ? OO
.ui
.resolveMsg( title
) : null;
6103 if ( this.title
!== title
) {
6104 if ( this.$titled
) {
6105 if ( title
!== null ) {
6106 this.$titled
.attr( 'title', title
);
6108 this.$titled
.removeAttr( 'title' );
6120 * @return {string} Title string
6122 OO
.ui
.TitledElement
.prototype.getTitle = function () {
6127 * Element that can be automatically clipped to visible boundaries.
6129 * Whenever the element's natural height changes, you have to call
6130 * #clip to make sure it's still clipping correctly.
6136 * @param {Object} [config] Configuration options
6137 * @cfg {jQuery} [$clippable] Nodes to clip, assigned to #$clippable, omit to use #$element
6139 OO
.ui
.ClippableElement
= function OoUiClippableElement( config
) {
6140 // Configuration initialization
6141 config
= config
|| {};
6144 this.$clippable
= null;
6145 this.clipping
= false;
6146 this.clippedHorizontally
= false;
6147 this.clippedVertically
= false;
6148 this.$clippableContainer
= null;
6149 this.$clippableScroller
= null;
6150 this.$clippableWindow
= null;
6151 this.idealWidth
= null;
6152 this.idealHeight
= null;
6153 this.onClippableContainerScrollHandler
= this.clip
.bind( this );
6154 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
6157 this.setClippableElement( config
.$clippable
|| this.$element
);
6163 * Set clippable element.
6165 * If an element is already set, it will be cleaned up before setting up the new element.
6167 * @param {jQuery} $clippable Element to make clippable
6169 OO
.ui
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
6170 if ( this.$clippable
) {
6171 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
6172 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
6173 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6176 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
6183 * Do not turn clipping on until after the element is attached to the DOM and visible.
6185 * @param {boolean} [clipping] Enable clipping, omit to toggle
6188 OO
.ui
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
6189 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
6191 if ( this.clipping
!== clipping
) {
6192 this.clipping
= clipping
;
6194 this.$clippableContainer
= $( this.getClosestScrollableElementContainer() );
6195 // If the clippable container is the root, we have to listen to scroll events and check
6196 // jQuery.scrollTop on the window because of browser inconsistencies
6197 this.$clippableScroller
= this.$clippableContainer
.is( 'html, body' ) ?
6198 $( OO
.ui
.Element
.static.getWindow( this.$clippableContainer
) ) :
6199 this.$clippableContainer
;
6200 this.$clippableScroller
.on( 'scroll', this.onClippableContainerScrollHandler
);
6201 this.$clippableWindow
= $( this.getElementWindow() )
6202 .on( 'resize', this.onClippableWindowResizeHandler
);
6203 // Initial clip after visible
6206 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
6207 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6209 this.$clippableContainer
= null;
6210 this.$clippableScroller
.off( 'scroll', this.onClippableContainerScrollHandler
);
6211 this.$clippableScroller
= null;
6212 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
6213 this.$clippableWindow
= null;
6221 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6223 * @return {boolean} Element will be clipped to the visible area
6225 OO
.ui
.ClippableElement
.prototype.isClipping = function () {
6226 return this.clipping
;
6230 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6232 * @return {boolean} Part of the element is being clipped
6234 OO
.ui
.ClippableElement
.prototype.isClipped = function () {
6235 return this.clippedHorizontally
|| this.clippedVertically
;
6239 * Check if the right of the element is being clipped by the nearest scrollable container.
6241 * @return {boolean} Part of the element is being clipped
6243 OO
.ui
.ClippableElement
.prototype.isClippedHorizontally = function () {
6244 return this.clippedHorizontally
;
6248 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6250 * @return {boolean} Part of the element is being clipped
6252 OO
.ui
.ClippableElement
.prototype.isClippedVertically = function () {
6253 return this.clippedVertically
;
6257 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6259 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6260 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6262 OO
.ui
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
6263 this.idealWidth
= width
;
6264 this.idealHeight
= height
;
6266 if ( !this.clipping
) {
6267 // Update dimensions
6268 this.$clippable
.css( { width
: width
, height
: height
} );
6270 // While clipping, idealWidth and idealHeight are not considered
6274 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6275 * the element's natural height changes.
6277 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6278 * overlapped by, the visible area of the nearest scrollable container.
6282 OO
.ui
.ClippableElement
.prototype.clip = function () {
6283 if ( !this.clipping
) {
6284 // this.$clippableContainer and this.$clippableWindow are null, so the below will fail
6288 var buffer
= 7, // Chosen by fair dice roll
6289 cOffset
= this.$clippable
.offset(),
6290 $container
= this.$clippableContainer
.is( 'html, body' ) ?
6291 this.$clippableWindow
: this.$clippableContainer
,
6292 ccOffset
= $container
.offset() || { top
: 0, left
: 0 },
6293 ccHeight
= $container
.innerHeight() - buffer
,
6294 ccWidth
= $container
.innerWidth() - buffer
,
6295 cHeight
= this.$clippable
.outerHeight() + buffer
,
6296 cWidth
= this.$clippable
.outerWidth() + buffer
,
6297 scrollTop
= this.$clippableScroller
.scrollTop(),
6298 scrollLeft
= this.$clippableScroller
.scrollLeft(),
6299 desiredWidth
= cOffset
.left
< 0 ?
6300 cWidth
+ cOffset
.left
:
6301 ( ccOffset
.left
+ scrollLeft
+ ccWidth
) - cOffset
.left
,
6302 desiredHeight
= cOffset
.top
< 0 ?
6303 cHeight
+ cOffset
.top
:
6304 ( ccOffset
.top
+ scrollTop
+ ccHeight
) - cOffset
.top
,
6305 naturalWidth
= this.$clippable
.prop( 'scrollWidth' ),
6306 naturalHeight
= this.$clippable
.prop( 'scrollHeight' ),
6307 clipWidth
= desiredWidth
< naturalWidth
,
6308 clipHeight
= desiredHeight
< naturalHeight
;
6311 this.$clippable
.css( { overflowX
: 'scroll', width
: desiredWidth
} );
6313 this.$clippable
.css( { width
: this.idealWidth
|| '', overflowX
: '' } );
6316 this.$clippable
.css( { overflowY
: 'scroll', height
: desiredHeight
} );
6318 this.$clippable
.css( { height
: this.idealHeight
|| '', overflowY
: '' } );
6321 // If we stopped clipping in at least one of the dimensions
6322 if ( !clipWidth
|| !clipHeight
) {
6323 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6326 this.clippedHorizontally
= clipWidth
;
6327 this.clippedVertically
= clipHeight
;
6333 * Generic toolbar tool.
6337 * @extends OO.ui.Widget
6338 * @mixins OO.ui.IconElement
6339 * @mixins OO.ui.FlaggedElement
6342 * @param {OO.ui.ToolGroup} toolGroup
6343 * @param {Object} [config] Configuration options
6344 * @cfg {string|Function} [title] Title text or a function that returns text
6346 OO
.ui
.Tool
= function OoUiTool( toolGroup
, config
) {
6347 // Allow passing positional parameters inside the config object
6348 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
6350 toolGroup
= config
.toolGroup
;
6353 // Configuration initialization
6354 config
= config
|| {};
6356 // Parent constructor
6357 OO
.ui
.Tool
.super.call( this, config
);
6359 // Mixin constructors
6360 OO
.ui
.IconElement
.call( this, config
);
6361 OO
.ui
.FlaggedElement
.call( this, config
);
6364 this.toolGroup
= toolGroup
;
6365 this.toolbar
= this.toolGroup
.getToolbar();
6366 this.active
= false;
6367 this.$title
= $( '<span>' );
6368 this.$accel
= $( '<span>' );
6369 this.$link
= $( '<a>' );
6373 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
6376 this.$title
.addClass( 'oo-ui-tool-title' );
6378 .addClass( 'oo-ui-tool-accel' )
6380 // This may need to be changed if the key names are ever localized,
6381 // but for now they are essentially written in English
6386 .addClass( 'oo-ui-tool-link' )
6387 .append( this.$icon
, this.$title
, this.$accel
)
6388 .prop( 'tabIndex', 0 )
6389 .attr( 'role', 'button' );
6391 .data( 'oo-ui-tool', this )
6393 'oo-ui-tool ' + 'oo-ui-tool-name-' +
6394 this.constructor.static.name
.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
6396 .append( this.$link
);
6397 this.setTitle( config
.title
|| this.constructor.static.title
);
6402 OO
.inheritClass( OO
.ui
.Tool
, OO
.ui
.Widget
);
6403 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.IconElement
);
6404 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.FlaggedElement
);
6412 /* Static Properties */
6418 OO
.ui
.Tool
.static.tagName
= 'span';
6421 * Symbolic name of tool.
6426 * @property {string}
6428 OO
.ui
.Tool
.static.name
= '';
6436 * @property {string}
6438 OO
.ui
.Tool
.static.group
= '';
6443 * Title is used as a tooltip when the tool is part of a bar tool group, or a label when the tool
6444 * is part of a list or menu tool group. If a trigger is associated with an action by the same name
6445 * as the tool, a description of its keyboard shortcut for the appropriate platform will be
6446 * appended to the title if the tool is part of a bar tool group.
6451 * @property {string|Function} Title text or a function that returns text
6453 OO
.ui
.Tool
.static.title
= '';
6456 * Tool can be automatically added to catch-all groups.
6460 * @property {boolean}
6462 OO
.ui
.Tool
.static.autoAddToCatchall
= true;
6465 * Tool can be automatically added to named groups.
6468 * @property {boolean}
6471 OO
.ui
.Tool
.static.autoAddToGroup
= true;
6474 * Check if this tool is compatible with given data.
6478 * @param {Mixed} data Data to check
6479 * @return {boolean} Tool can be used with data
6481 OO
.ui
.Tool
.static.isCompatibleWith = function () {
6488 * Handle the toolbar state being updated.
6490 * This is an abstract method that must be overridden in a concrete subclass.
6494 OO
.ui
.Tool
.prototype.onUpdateState = function () {
6496 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
6501 * Handle the tool being selected.
6503 * This is an abstract method that must be overridden in a concrete subclass.
6507 OO
.ui
.Tool
.prototype.onSelect = function () {
6509 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
6514 * Check if the button is active.
6516 * @return {boolean} Button is active
6518 OO
.ui
.Tool
.prototype.isActive = function () {
6523 * Make the button appear active or inactive.
6525 * @param {boolean} state Make button appear active
6527 OO
.ui
.Tool
.prototype.setActive = function ( state
) {
6528 this.active
= !!state
;
6529 if ( this.active
) {
6530 this.$element
.addClass( 'oo-ui-tool-active' );
6532 this.$element
.removeClass( 'oo-ui-tool-active' );
6537 * Get the tool title.
6539 * @param {string|Function} title Title text or a function that returns text
6542 OO
.ui
.Tool
.prototype.setTitle = function ( title
) {
6543 this.title
= OO
.ui
.resolveMsg( title
);
6549 * Get the tool title.
6551 * @return {string} Title text
6553 OO
.ui
.Tool
.prototype.getTitle = function () {
6558 * Get the tool's symbolic name.
6560 * @return {string} Symbolic name of tool
6562 OO
.ui
.Tool
.prototype.getName = function () {
6563 return this.constructor.static.name
;
6569 OO
.ui
.Tool
.prototype.updateTitle = function () {
6570 var titleTooltips
= this.toolGroup
.constructor.static.titleTooltips
,
6571 accelTooltips
= this.toolGroup
.constructor.static.accelTooltips
,
6572 accel
= this.toolbar
.getToolAccelerator( this.constructor.static.name
),
6575 this.$title
.text( this.title
);
6576 this.$accel
.text( accel
);
6578 if ( titleTooltips
&& typeof this.title
=== 'string' && this.title
.length
) {
6579 tooltipParts
.push( this.title
);
6581 if ( accelTooltips
&& typeof accel
=== 'string' && accel
.length
) {
6582 tooltipParts
.push( accel
);
6584 if ( tooltipParts
.length
) {
6585 this.$link
.attr( 'title', tooltipParts
.join( ' ' ) );
6587 this.$link
.removeAttr( 'title' );
6594 OO
.ui
.Tool
.prototype.destroy = function () {
6595 this.toolbar
.disconnect( this );
6596 this.$element
.remove();
6600 * Collection of tool groups.
6603 * @extends OO.ui.Element
6604 * @mixins OO.EventEmitter
6605 * @mixins OO.ui.GroupElement
6608 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
6609 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating tool groups
6610 * @param {Object} [config] Configuration options
6611 * @cfg {boolean} [actions] Add an actions section opposite to the tools
6612 * @cfg {boolean} [shadow] Add a shadow below the toolbar
6614 OO
.ui
.Toolbar
= function OoUiToolbar( toolFactory
, toolGroupFactory
, config
) {
6615 // Allow passing positional parameters inside the config object
6616 if ( OO
.isPlainObject( toolFactory
) && config
=== undefined ) {
6617 config
= toolFactory
;
6618 toolFactory
= config
.toolFactory
;
6619 toolGroupFactory
= config
.toolGroupFactory
;
6622 // Configuration initialization
6623 config
= config
|| {};
6625 // Parent constructor
6626 OO
.ui
.Toolbar
.super.call( this, config
);
6628 // Mixin constructors
6629 OO
.EventEmitter
.call( this );
6630 OO
.ui
.GroupElement
.call( this, config
);
6633 this.toolFactory
= toolFactory
;
6634 this.toolGroupFactory
= toolGroupFactory
;
6637 this.$bar
= $( '<div>' );
6638 this.$actions
= $( '<div>' );
6639 this.initialized
= false;
6640 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
6644 .add( this.$bar
).add( this.$group
).add( this.$actions
)
6645 .on( 'mousedown', this.onPointerDown
.bind( this ) );
6648 this.$group
.addClass( 'oo-ui-toolbar-tools' );
6649 if ( config
.actions
) {
6650 this.$bar
.append( this.$actions
.addClass( 'oo-ui-toolbar-actions' ) );
6653 .addClass( 'oo-ui-toolbar-bar' )
6654 .append( this.$group
, '<div style="clear:both"></div>' );
6655 if ( config
.shadow
) {
6656 this.$bar
.append( '<div class="oo-ui-toolbar-shadow"></div>' );
6658 this.$element
.addClass( 'oo-ui-toolbar' ).append( this.$bar
);
6663 OO
.inheritClass( OO
.ui
.Toolbar
, OO
.ui
.Element
);
6664 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.EventEmitter
);
6665 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.ui
.GroupElement
);
6670 * Get the tool factory.
6672 * @return {OO.ui.ToolFactory} Tool factory
6674 OO
.ui
.Toolbar
.prototype.getToolFactory = function () {
6675 return this.toolFactory
;
6679 * Get the tool group factory.
6681 * @return {OO.Factory} Tool group factory
6683 OO
.ui
.Toolbar
.prototype.getToolGroupFactory = function () {
6684 return this.toolGroupFactory
;
6688 * Handles mouse down events.
6690 * @param {jQuery.Event} e Mouse down event
6692 OO
.ui
.Toolbar
.prototype.onPointerDown = function ( e
) {
6693 var $closestWidgetToEvent
= $( e
.target
).closest( '.oo-ui-widget' ),
6694 $closestWidgetToToolbar
= this.$element
.closest( '.oo-ui-widget' );
6695 if ( !$closestWidgetToEvent
.length
|| $closestWidgetToEvent
[ 0 ] === $closestWidgetToToolbar
[ 0 ] ) {
6701 * Handle window resize event.
6704 * @param {jQuery.Event} e Window resize event
6706 OO
.ui
.Toolbar
.prototype.onWindowResize = function () {
6707 this.$element
.toggleClass(
6708 'oo-ui-toolbar-narrow',
6709 this.$bar
.width() <= this.narrowThreshold
6714 * Sets up handles and preloads required information for the toolbar to work.
6715 * This must be called after it is attached to a visible document and before doing anything else.
6717 OO
.ui
.Toolbar
.prototype.initialize = function () {
6718 this.initialized
= true;
6719 this.narrowThreshold
= this.$group
.width() + this.$actions
.width();
6720 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler
);
6721 this.onWindowResize();
6727 * Tools can be specified in the following ways:
6729 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
6730 * - All tools in a group: `{ group: 'group-name' }`
6731 * - All tools: `'*'` - Using this will make the group a list with a "More" label by default
6733 * @param {Object.<string,Array>} groups List of tool group configurations
6734 * @param {Array|string} [groups.include] Tools to include
6735 * @param {Array|string} [groups.exclude] Tools to exclude
6736 * @param {Array|string} [groups.promote] Tools to promote to the beginning
6737 * @param {Array|string} [groups.demote] Tools to demote to the end
6739 OO
.ui
.Toolbar
.prototype.setup = function ( groups
) {
6740 var i
, len
, type
, group
,
6742 defaultType
= 'bar';
6744 // Cleanup previous groups
6747 // Build out new groups
6748 for ( i
= 0, len
= groups
.length
; i
< len
; i
++ ) {
6749 group
= groups
[ i
];
6750 if ( group
.include
=== '*' ) {
6751 // Apply defaults to catch-all groups
6752 if ( group
.type
=== undefined ) {
6753 group
.type
= 'list';
6755 if ( group
.label
=== undefined ) {
6756 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
6759 // Check type has been registered
6760 type
= this.getToolGroupFactory().lookup( group
.type
) ? group
.type
: defaultType
;
6762 this.getToolGroupFactory().create( type
, this, group
)
6765 this.addItems( items
);
6769 * Remove all tools and groups from the toolbar.
6771 OO
.ui
.Toolbar
.prototype.reset = function () {
6776 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6777 this.items
[ i
].destroy();
6783 * Destroys toolbar, removing event handlers and DOM elements.
6785 * Call this whenever you are done using a toolbar.
6787 OO
.ui
.Toolbar
.prototype.destroy = function () {
6788 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler
);
6790 this.$element
.remove();
6794 * Check if tool has not been used yet.
6796 * @param {string} name Symbolic name of tool
6797 * @return {boolean} Tool is available
6799 OO
.ui
.Toolbar
.prototype.isToolAvailable = function ( name
) {
6800 return !this.tools
[ name
];
6804 * Prevent tool from being used again.
6806 * @param {OO.ui.Tool} tool Tool to reserve
6808 OO
.ui
.Toolbar
.prototype.reserveTool = function ( tool
) {
6809 this.tools
[ tool
.getName() ] = tool
;
6813 * Allow tool to be used again.
6815 * @param {OO.ui.Tool} tool Tool to release
6817 OO
.ui
.Toolbar
.prototype.releaseTool = function ( tool
) {
6818 delete this.tools
[ tool
.getName() ];
6822 * Get accelerator label for tool.
6824 * This is a stub that should be overridden to provide access to accelerator information.
6826 * @param {string} name Symbolic name of tool
6827 * @return {string|undefined} Tool accelerator label if available
6829 OO
.ui
.Toolbar
.prototype.getToolAccelerator = function () {
6834 * Collection of tools.
6836 * Tools can be specified in the following ways:
6838 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
6839 * - All tools in a group: `{ group: 'group-name' }`
6840 * - All tools: `'*'`
6844 * @extends OO.ui.Widget
6845 * @mixins OO.ui.GroupElement
6848 * @param {OO.ui.Toolbar} toolbar
6849 * @param {Object} [config] Configuration options
6850 * @cfg {Array|string} [include=[]] List of tools to include
6851 * @cfg {Array|string} [exclude=[]] List of tools to exclude
6852 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning
6853 * @cfg {Array|string} [demote=[]] List of tools to demote to the end
6855 OO
.ui
.ToolGroup
= function OoUiToolGroup( toolbar
, config
) {
6856 // Allow passing positional parameters inside the config object
6857 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
6859 toolbar
= config
.toolbar
;
6862 // Configuration initialization
6863 config
= config
|| {};
6865 // Parent constructor
6866 OO
.ui
.ToolGroup
.super.call( this, config
);
6868 // Mixin constructors
6869 OO
.ui
.GroupElement
.call( this, config
);
6872 this.toolbar
= toolbar
;
6874 this.pressed
= null;
6875 this.autoDisabled
= false;
6876 this.include
= config
.include
|| [];
6877 this.exclude
= config
.exclude
|| [];
6878 this.promote
= config
.promote
|| [];
6879 this.demote
= config
.demote
|| [];
6880 this.onCapturedMouseUpHandler
= this.onCapturedMouseUp
.bind( this );
6884 mousedown
: this.onPointerDown
.bind( this ),
6885 mouseup
: this.onPointerUp
.bind( this ),
6886 mouseover
: this.onMouseOver
.bind( this ),
6887 mouseout
: this.onMouseOut
.bind( this )
6889 this.toolbar
.getToolFactory().connect( this, { register
: 'onToolFactoryRegister' } );
6890 this.aggregate( { disable
: 'itemDisable' } );
6891 this.connect( this, { itemDisable
: 'updateDisabled' } );
6894 this.$group
.addClass( 'oo-ui-toolGroup-tools' );
6896 .addClass( 'oo-ui-toolGroup' )
6897 .append( this.$group
);
6903 OO
.inheritClass( OO
.ui
.ToolGroup
, OO
.ui
.Widget
);
6904 OO
.mixinClass( OO
.ui
.ToolGroup
, OO
.ui
.GroupElement
);
6912 /* Static Properties */
6915 * Show labels in tooltips.
6919 * @property {boolean}
6921 OO
.ui
.ToolGroup
.static.titleTooltips
= false;
6924 * Show acceleration labels in tooltips.
6928 * @property {boolean}
6930 OO
.ui
.ToolGroup
.static.accelTooltips
= false;
6933 * Automatically disable the toolgroup when all tools are disabled
6937 * @property {boolean}
6939 OO
.ui
.ToolGroup
.static.autoDisable
= true;
6946 OO
.ui
.ToolGroup
.prototype.isDisabled = function () {
6947 return this.autoDisabled
|| OO
.ui
.ToolGroup
.super.prototype.isDisabled
.apply( this, arguments
);
6953 OO
.ui
.ToolGroup
.prototype.updateDisabled = function () {
6954 var i
, item
, allDisabled
= true;
6956 if ( this.constructor.static.autoDisable
) {
6957 for ( i
= this.items
.length
- 1; i
>= 0; i
-- ) {
6958 item
= this.items
[ i
];
6959 if ( !item
.isDisabled() ) {
6960 allDisabled
= false;
6964 this.autoDisabled
= allDisabled
;
6966 OO
.ui
.ToolGroup
.super.prototype.updateDisabled
.apply( this, arguments
);
6970 * Handle mouse down events.
6972 * @param {jQuery.Event} e Mouse down event
6974 OO
.ui
.ToolGroup
.prototype.onPointerDown = function ( e
) {
6975 if ( !this.isDisabled() && e
.which
=== 1 ) {
6976 this.pressed
= this.getTargetTool( e
);
6977 if ( this.pressed
) {
6978 this.pressed
.setActive( true );
6979 this.getElementDocument().addEventListener(
6980 'mouseup', this.onCapturedMouseUpHandler
, true
6988 * Handle captured mouse up events.
6990 * @param {Event} e Mouse up event
6992 OO
.ui
.ToolGroup
.prototype.onCapturedMouseUp = function ( e
) {
6993 this.getElementDocument().removeEventListener( 'mouseup', this.onCapturedMouseUpHandler
, true );
6994 // onPointerUp may be called a second time, depending on where the mouse is when the button is
6995 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
6996 this.onPointerUp( e
);
7000 * Handle mouse up events.
7002 * @param {jQuery.Event} e Mouse up event
7004 OO
.ui
.ToolGroup
.prototype.onPointerUp = function ( e
) {
7005 var tool
= this.getTargetTool( e
);
7007 if ( !this.isDisabled() && e
.which
=== 1 && this.pressed
&& this.pressed
=== tool
) {
7008 this.pressed
.onSelect();
7011 this.pressed
= null;
7016 * Handle mouse over events.
7018 * @param {jQuery.Event} e Mouse over event
7020 OO
.ui
.ToolGroup
.prototype.onMouseOver = function ( e
) {
7021 var tool
= this.getTargetTool( e
);
7023 if ( this.pressed
&& this.pressed
=== tool
) {
7024 this.pressed
.setActive( true );
7029 * Handle mouse out events.
7031 * @param {jQuery.Event} e Mouse out event
7033 OO
.ui
.ToolGroup
.prototype.onMouseOut = function ( e
) {
7034 var tool
= this.getTargetTool( e
);
7036 if ( this.pressed
&& this.pressed
=== tool
) {
7037 this.pressed
.setActive( false );
7042 * Get the closest tool to a jQuery.Event.
7044 * Only tool links are considered, which prevents other elements in the tool such as popups from
7045 * triggering tool group interactions.
7048 * @param {jQuery.Event} e
7049 * @return {OO.ui.Tool|null} Tool, `null` if none was found
7051 OO
.ui
.ToolGroup
.prototype.getTargetTool = function ( e
) {
7053 $item
= $( e
.target
).closest( '.oo-ui-tool-link' );
7055 if ( $item
.length
) {
7056 tool
= $item
.parent().data( 'oo-ui-tool' );
7059 return tool
&& !tool
.isDisabled() ? tool
: null;
7063 * Handle tool registry register events.
7065 * If a tool is registered after the group is created, we must repopulate the list to account for:
7067 * - a tool being added that may be included
7068 * - a tool already included being overridden
7070 * @param {string} name Symbolic name of tool
7072 OO
.ui
.ToolGroup
.prototype.onToolFactoryRegister = function () {
7077 * Get the toolbar this group is in.
7079 * @return {OO.ui.Toolbar} Toolbar of group
7081 OO
.ui
.ToolGroup
.prototype.getToolbar = function () {
7082 return this.toolbar
;
7086 * Add and remove tools based on configuration.
7088 OO
.ui
.ToolGroup
.prototype.populate = function () {
7089 var i
, len
, name
, tool
,
7090 toolFactory
= this.toolbar
.getToolFactory(),
7094 list
= this.toolbar
.getToolFactory().getTools(
7095 this.include
, this.exclude
, this.promote
, this.demote
7098 // Build a list of needed tools
7099 for ( i
= 0, len
= list
.length
; i
< len
; i
++ ) {
7103 toolFactory
.lookup( name
) &&
7104 // Tool is available or is already in this group
7105 ( this.toolbar
.isToolAvailable( name
) || this.tools
[ name
] )
7107 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
7108 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
7109 this.toolbar
.tools
[ name
] = true;
7110 tool
= this.tools
[ name
];
7112 // Auto-initialize tools on first use
7113 this.tools
[ name
] = tool
= toolFactory
.create( name
, this );
7116 this.toolbar
.reserveTool( tool
);
7118 names
[ name
] = true;
7121 // Remove tools that are no longer needed
7122 for ( name
in this.tools
) {
7123 if ( !names
[ name
] ) {
7124 this.tools
[ name
].destroy();
7125 this.toolbar
.releaseTool( this.tools
[ name
] );
7126 remove
.push( this.tools
[ name
] );
7127 delete this.tools
[ name
];
7130 if ( remove
.length
) {
7131 this.removeItems( remove
);
7133 // Update emptiness state
7135 this.$element
.removeClass( 'oo-ui-toolGroup-empty' );
7137 this.$element
.addClass( 'oo-ui-toolGroup-empty' );
7139 // Re-add tools (moving existing ones to new locations)
7140 this.addItems( add
);
7141 // Disabled state may depend on items
7142 this.updateDisabled();
7146 * Destroy tool group.
7148 OO
.ui
.ToolGroup
.prototype.destroy = function () {
7152 this.toolbar
.getToolFactory().disconnect( this );
7153 for ( name
in this.tools
) {
7154 this.toolbar
.releaseTool( this.tools
[ name
] );
7155 this.tools
[ name
].disconnect( this ).destroy();
7156 delete this.tools
[ name
];
7158 this.$element
.remove();
7162 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
7163 * consists of a header that contains the dialog title, a body with the message, and a footer that
7164 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
7165 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
7167 * There are two basic types of message dialogs, confirmation and alert:
7169 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
7170 * more details about the consequences.
7171 * - **alert**: the dialog title describes which event occurred and the message provides more information
7172 * about why the event occurred.
7174 * The MessageDialog class specifies two actions: ‘accept’, the primary
7175 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
7176 * passing along the selected action.
7178 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
7181 * // Example: Creating and opening a message dialog window.
7182 * var messageDialog = new OO.ui.MessageDialog();
7184 * // Create and append a window manager.
7185 * var windowManager = new OO.ui.WindowManager();
7186 * $( 'body' ).append( windowManager.$element );
7187 * windowManager.addWindows( [ messageDialog ] );
7188 * // Open the window.
7189 * windowManager.openWindow( messageDialog, {
7190 * title: 'Basic message dialog',
7191 * message: 'This is the message'
7194 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
7197 * @extends OO.ui.Dialog
7200 * @param {Object} [config] Configuration options
7202 OO
.ui
.MessageDialog
= function OoUiMessageDialog( config
) {
7203 // Parent constructor
7204 OO
.ui
.MessageDialog
.super.call( this, config
);
7207 this.verticalActionLayout
= null;
7210 this.$element
.addClass( 'oo-ui-messageDialog' );
7215 OO
.inheritClass( OO
.ui
.MessageDialog
, OO
.ui
.Dialog
);
7217 /* Static Properties */
7219 OO
.ui
.MessageDialog
.static.name
= 'message';
7221 OO
.ui
.MessageDialog
.static.size
= 'small';
7223 OO
.ui
.MessageDialog
.static.verbose
= false;
7228 * The title of a confirmation dialog describes what a progressive action will do. The
7229 * title of an alert dialog describes which event occurred.
7233 * @property {jQuery|string|Function|null}
7235 OO
.ui
.MessageDialog
.static.title
= null;
7238 * The message displayed in the dialog body.
7240 * A confirmation message describes the consequences of a progressive action. An alert
7241 * message describes why an event occurred.
7245 * @property {jQuery|string|Function|null}
7247 OO
.ui
.MessageDialog
.static.message
= null;
7249 OO
.ui
.MessageDialog
.static.actions
= [
7250 { action
: 'accept', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-accept' ), flags
: 'primary' },
7251 { action
: 'reject', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-reject' ), flags
: 'safe' }
7259 OO
.ui
.MessageDialog
.prototype.setManager = function ( manager
) {
7260 OO
.ui
.MessageDialog
.super.prototype.setManager
.call( this, manager
);
7263 this.manager
.connect( this, {
7273 OO
.ui
.MessageDialog
.prototype.onActionResize = function ( action
) {
7275 return OO
.ui
.MessageDialog
.super.prototype.onActionResize
.call( this, action
);
7279 * Handle window resized events.
7283 OO
.ui
.MessageDialog
.prototype.onResize = function () {
7285 dialog
.fitActions();
7286 // Wait for CSS transition to finish and do it again :(
7287 setTimeout( function () {
7288 dialog
.fitActions();
7293 * Toggle action layout between vertical and horizontal.
7297 * @param {boolean} [value] Layout actions vertically, omit to toggle
7300 OO
.ui
.MessageDialog
.prototype.toggleVerticalActionLayout = function ( value
) {
7301 value
= value
=== undefined ? !this.verticalActionLayout
: !!value
;
7303 if ( value
!== this.verticalActionLayout
) {
7304 this.verticalActionLayout
= value
;
7306 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value
)
7307 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value
);
7316 OO
.ui
.MessageDialog
.prototype.getActionProcess = function ( action
) {
7318 return new OO
.ui
.Process( function () {
7319 this.close( { action
: action
} );
7322 return OO
.ui
.MessageDialog
.super.prototype.getActionProcess
.call( this, action
);
7328 * @param {Object} [data] Dialog opening data
7329 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
7330 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
7331 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
7332 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
7335 OO
.ui
.MessageDialog
.prototype.getSetupProcess = function ( data
) {
7339 return OO
.ui
.MessageDialog
.super.prototype.getSetupProcess
.call( this, data
)
7340 .next( function () {
7341 this.title
.setLabel(
7342 data
.title
!== undefined ? data
.title
: this.constructor.static.title
7344 this.message
.setLabel(
7345 data
.message
!== undefined ? data
.message
: this.constructor.static.message
7347 this.message
.$element
.toggleClass(
7348 'oo-ui-messageDialog-message-verbose',
7349 data
.verbose
!== undefined ? data
.verbose
: this.constructor.static.verbose
7357 OO
.ui
.MessageDialog
.prototype.getBodyHeight = function () {
7358 var bodyHeight
, oldOverflow
,
7359 $scrollable
= this.container
.$element
;
7361 oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
7362 $scrollable
[ 0 ].style
.overflow
= 'hidden';
7364 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
7366 bodyHeight
= this.text
.$element
.outerHeight( true );
7367 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
7375 OO
.ui
.MessageDialog
.prototype.setDimensions = function ( dim
) {
7376 var $scrollable
= this.container
.$element
;
7377 OO
.ui
.MessageDialog
.super.prototype.setDimensions
.call( this, dim
);
7379 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
7380 // Need to do it after transition completes (250ms), add 50ms just in case.
7381 setTimeout( function () {
7382 var oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
7383 $scrollable
[ 0 ].style
.overflow
= 'hidden';
7385 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
7387 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
7396 OO
.ui
.MessageDialog
.prototype.initialize = function () {
7398 OO
.ui
.MessageDialog
.super.prototype.initialize
.call( this );
7401 this.$actions
= $( '<div>' );
7402 this.container
= new OO
.ui
.PanelLayout( {
7403 scrollable
: true, classes
: [ 'oo-ui-messageDialog-container' ]
7405 this.text
= new OO
.ui
.PanelLayout( {
7406 padded
: true, expanded
: false, classes
: [ 'oo-ui-messageDialog-text' ]
7408 this.message
= new OO
.ui
.LabelWidget( {
7409 classes
: [ 'oo-ui-messageDialog-message' ]
7413 this.title
.$element
.addClass( 'oo-ui-messageDialog-title' );
7414 this.$content
.addClass( 'oo-ui-messageDialog-content' );
7415 this.container
.$element
.append( this.text
.$element
);
7416 this.text
.$element
.append( this.title
.$element
, this.message
.$element
);
7417 this.$body
.append( this.container
.$element
);
7418 this.$actions
.addClass( 'oo-ui-messageDialog-actions' );
7419 this.$foot
.append( this.$actions
);
7425 OO
.ui
.MessageDialog
.prototype.attachActions = function () {
7426 var i
, len
, other
, special
, others
;
7429 OO
.ui
.MessageDialog
.super.prototype.attachActions
.call( this );
7431 special
= this.actions
.getSpecial();
7432 others
= this.actions
.getOthers();
7433 if ( special
.safe
) {
7434 this.$actions
.append( special
.safe
.$element
);
7435 special
.safe
.toggleFramed( false );
7437 if ( others
.length
) {
7438 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
7439 other
= others
[ i
];
7440 this.$actions
.append( other
.$element
);
7441 other
.toggleFramed( false );
7444 if ( special
.primary
) {
7445 this.$actions
.append( special
.primary
.$element
);
7446 special
.primary
.toggleFramed( false );
7449 if ( !this.isOpening() ) {
7450 // If the dialog is currently opening, this will be called automatically soon.
7451 // This also calls #fitActions.
7457 * Fit action actions into columns or rows.
7459 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
7463 OO
.ui
.MessageDialog
.prototype.fitActions = function () {
7465 previous
= this.verticalActionLayout
,
7466 actions
= this.actions
.get();
7469 this.toggleVerticalActionLayout( false );
7470 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
7471 action
= actions
[ i
];
7472 if ( action
.$element
.innerWidth() < action
.$label
.outerWidth( true ) ) {
7473 this.toggleVerticalActionLayout( true );
7478 // Move the body out of the way of the foot
7479 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
7481 if ( this.verticalActionLayout
!== previous
) {
7482 // We changed the layout, window height might need to be updated.
7488 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
7489 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
7490 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
7491 * relevant. The ProcessDialog class is always extended and customized with the actions and content
7492 * required for each process.
7494 * The process dialog box consists of a header that visually represents the ‘working’ state of long
7495 * processes with an animation. The header contains the dialog title as well as
7496 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
7497 * a ‘primary’ action on the right (e.g., ‘Done’).
7499 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
7500 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
7503 * // Example: Creating and opening a process dialog window.
7504 * function MyProcessDialog( config ) {
7505 * MyProcessDialog.super.call( this, config );
7507 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
7509 * MyProcessDialog.static.title = 'Process dialog';
7510 * MyProcessDialog.static.actions = [
7511 * { action: 'save', label: 'Done', flags: 'primary' },
7512 * { label: 'Cancel', flags: 'safe' }
7515 * MyProcessDialog.prototype.initialize = function () {
7516 * MyProcessDialog.super.prototype.initialize.apply( this, arguments );
7517 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true, expanded: false } );
7518 * 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>' );
7519 * this.$body.append( this.content.$element );
7521 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
7522 * var dialog = this;
7524 * return new OO.ui.Process( function () {
7525 * dialog.close( { action: action } );
7528 * return MyProcessDialog.super.prototype.getActionProcess.call( this, action );
7531 * var windowManager = new OO.ui.WindowManager();
7532 * $( 'body' ).append( windowManager.$element );
7534 * var dialog = new MyProcessDialog();
7535 * windowManager.addWindows( [ dialog ] );
7536 * windowManager.openWindow( dialog );
7538 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
7542 * @extends OO.ui.Dialog
7545 * @param {Object} [config] Configuration options
7547 OO
.ui
.ProcessDialog
= function OoUiProcessDialog( config
) {
7548 // Parent constructor
7549 OO
.ui
.ProcessDialog
.super.call( this, config
);
7552 this.$element
.addClass( 'oo-ui-processDialog' );
7557 OO
.inheritClass( OO
.ui
.ProcessDialog
, OO
.ui
.Dialog
);
7562 * Handle dismiss button click events.
7568 OO
.ui
.ProcessDialog
.prototype.onDismissErrorButtonClick = function () {
7573 * Handle retry button click events.
7575 * Hides errors and then tries again.
7579 OO
.ui
.ProcessDialog
.prototype.onRetryButtonClick = function () {
7581 this.executeAction( this.currentAction
);
7587 OO
.ui
.ProcessDialog
.prototype.onActionResize = function ( action
) {
7588 if ( this.actions
.isSpecial( action
) ) {
7591 return OO
.ui
.ProcessDialog
.super.prototype.onActionResize
.call( this, action
);
7597 OO
.ui
.ProcessDialog
.prototype.initialize = function () {
7599 OO
.ui
.ProcessDialog
.super.prototype.initialize
.call( this );
7602 this.$navigation
= $( '<div>' );
7603 this.$location
= $( '<div>' );
7604 this.$safeActions
= $( '<div>' );
7605 this.$primaryActions
= $( '<div>' );
7606 this.$otherActions
= $( '<div>' );
7607 this.dismissButton
= new OO
.ui
.ButtonWidget( {
7608 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' )
7610 this.retryButton
= new OO
.ui
.ButtonWidget();
7611 this.$errors
= $( '<div>' );
7612 this.$errorsTitle
= $( '<div>' );
7615 this.dismissButton
.connect( this, { click
: 'onDismissErrorButtonClick' } );
7616 this.retryButton
.connect( this, { click
: 'onRetryButtonClick' } );
7619 this.title
.$element
.addClass( 'oo-ui-processDialog-title' );
7621 .append( this.title
.$element
)
7622 .addClass( 'oo-ui-processDialog-location' );
7623 this.$safeActions
.addClass( 'oo-ui-processDialog-actions-safe' );
7624 this.$primaryActions
.addClass( 'oo-ui-processDialog-actions-primary' );
7625 this.$otherActions
.addClass( 'oo-ui-processDialog-actions-other' );
7627 .addClass( 'oo-ui-processDialog-errors-title' )
7628 .text( OO
.ui
.msg( 'ooui-dialog-process-error' ) );
7630 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
7631 .append( this.$errorsTitle
, this.dismissButton
.$element
, this.retryButton
.$element
);
7633 .addClass( 'oo-ui-processDialog-content' )
7634 .append( this.$errors
);
7636 .addClass( 'oo-ui-processDialog-navigation' )
7637 .append( this.$safeActions
, this.$location
, this.$primaryActions
);
7638 this.$head
.append( this.$navigation
);
7639 this.$foot
.append( this.$otherActions
);
7645 OO
.ui
.ProcessDialog
.prototype.getActionWidgets = function ( actions
) {
7646 var i
, len
, widgets
= [];
7647 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
7649 new OO
.ui
.ActionWidget( $.extend( { framed
: true }, actions
[ i
] ) )
7658 OO
.ui
.ProcessDialog
.prototype.attachActions = function () {
7659 var i
, len
, other
, special
, others
;
7662 OO
.ui
.ProcessDialog
.super.prototype.attachActions
.call( this );
7664 special
= this.actions
.getSpecial();
7665 others
= this.actions
.getOthers();
7666 if ( special
.primary
) {
7667 this.$primaryActions
.append( special
.primary
.$element
);
7669 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
7670 other
= others
[ i
];
7671 this.$otherActions
.append( other
.$element
);
7673 if ( special
.safe
) {
7674 this.$safeActions
.append( special
.safe
.$element
);
7678 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
7684 OO
.ui
.ProcessDialog
.prototype.executeAction = function ( action
) {
7686 return OO
.ui
.ProcessDialog
.super.prototype.executeAction
.call( this, action
)
7687 .fail( function ( errors
) {
7688 process
.showErrors( errors
|| [] );
7693 * Fit label between actions.
7698 OO
.ui
.ProcessDialog
.prototype.fitLabel = function () {
7699 var width
= Math
.max(
7700 this.$safeActions
.is( ':visible' ) ? this.$safeActions
.width() : 0,
7701 this.$primaryActions
.is( ':visible' ) ? this.$primaryActions
.width() : 0
7703 this.$location
.css( { paddingLeft
: width
, paddingRight
: width
} );
7709 * Handle errors that occurred during accept or reject processes.
7712 * @param {OO.ui.Error[]} errors Errors to be handled
7714 OO
.ui
.ProcessDialog
.prototype.showErrors = function ( errors
) {
7715 var i
, len
, $item
, actions
,
7721 for ( i
= 0, len
= errors
.length
; i
< len
; i
++ ) {
7722 if ( !errors
[ i
].isRecoverable() ) {
7723 recoverable
= false;
7725 if ( errors
[ i
].isWarning() ) {
7728 $item
= $( '<div>' )
7729 .addClass( 'oo-ui-processDialog-error' )
7730 .append( errors
[ i
].getMessage() );
7731 items
.push( $item
[ 0 ] );
7733 this.$errorItems
= $( items
);
7734 if ( recoverable
) {
7735 abilities
[this.currentAction
] = true;
7736 // Copy the flags from the first matching action
7737 actions
= this.actions
.get( { actions
: this.currentAction
} );
7738 if ( actions
.length
) {
7739 this.retryButton
.clearFlags().setFlags( actions
[0].getFlags() );
7742 abilities
[this.currentAction
] = false;
7743 this.actions
.setAbilities( abilities
);
7746 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-continue' ) );
7748 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-retry' ) );
7750 this.retryButton
.toggle( recoverable
);
7751 this.$errorsTitle
.after( this.$errorItems
);
7752 this.$errors
.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
7760 OO
.ui
.ProcessDialog
.prototype.hideErrors = function () {
7761 this.$errors
.addClass( 'oo-ui-element-hidden' );
7762 if ( this.$errorItems
) {
7763 this.$errorItems
.remove();
7764 this.$errorItems
= null;
7771 OO
.ui
.ProcessDialog
.prototype.getTeardownProcess = function ( data
) {
7773 return OO
.ui
.ProcessDialog
.super.prototype.getTeardownProcess
.call( this, data
)
7774 .first( function () {
7775 // Make sure to hide errors
7781 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
7782 * which is a widget that is specified by reference before any optional configuration settings.
7784 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
7786 * - **left**: The label is placed before the field-widget and aligned with the left margin.
7787 * A left-alignment is used for forms with many fields.
7788 * - **right**: The label is placed before the field-widget and aligned to the right margin.
7789 * A right-alignment is used for long but familiar forms which users tab through,
7790 * verifying the current field with a quick glance at the label.
7791 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
7792 * that users fill out from top to bottom.
7793 * - **inline**: The label is placed after the field-widget and aligned to the left.
7794 * An inline-alignment is best used with checkboxes or radio buttons.
7796 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
7797 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
7799 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
7801 * @extends OO.ui.Layout
7802 * @mixins OO.ui.LabelElement
7805 * @param {OO.ui.Widget} fieldWidget Field widget
7806 * @param {Object} [config] Configuration options
7807 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
7808 * @cfg {string} [help] Help text. When help text is specified, a help icon will appear
7809 * in the upper-right corner of the rendered field.
7811 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
7812 // Allow passing positional parameters inside the config object
7813 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
7814 config
= fieldWidget
;
7815 fieldWidget
= config
.fieldWidget
;
7818 var hasInputWidget
= fieldWidget
instanceof OO
.ui
.InputWidget
;
7820 // Configuration initialization
7821 config
= $.extend( { align
: 'left' }, config
);
7823 // Parent constructor
7824 OO
.ui
.FieldLayout
.super.call( this, config
);
7826 // Mixin constructors
7827 OO
.ui
.LabelElement
.call( this, config
);
7830 this.fieldWidget
= fieldWidget
;
7831 this.$field
= $( '<div>' );
7832 this.$body
= $( '<' + ( hasInputWidget
? 'label' : 'div' ) + '>' );
7834 if ( config
.help
) {
7835 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
7836 classes
: [ 'oo-ui-fieldLayout-help' ],
7841 this.popupButtonWidget
.getPopup().$body
.append(
7843 .text( config
.help
)
7844 .addClass( 'oo-ui-fieldLayout-help-content' )
7846 this.$help
= this.popupButtonWidget
.$element
;
7848 this.$help
= $( [] );
7852 if ( hasInputWidget
) {
7853 this.$label
.on( 'click', this.onLabelClick
.bind( this ) );
7855 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
7859 .addClass( 'oo-ui-fieldLayout' )
7860 .append( this.$help
, this.$body
);
7861 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
7863 .addClass( 'oo-ui-fieldLayout-field' )
7864 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget
.isDisabled() )
7865 .append( this.fieldWidget
.$element
);
7867 this.setAlignment( config
.align
);
7872 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
7873 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.LabelElement
);
7878 * Handle field disable events.
7881 * @param {boolean} value Field is disabled
7883 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
7884 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
7888 * Handle label mouse click events.
7891 * @param {jQuery.Event} e Mouse click event
7893 OO
.ui
.FieldLayout
.prototype.onLabelClick = function () {
7894 this.fieldWidget
.simulateLabelClick();
7899 * Get the widget contained by the field.
7901 * @return {OO.ui.Widget} Field widget
7903 OO
.ui
.FieldLayout
.prototype.getField = function () {
7904 return this.fieldWidget
;
7908 * Set the field alignment mode.
7911 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
7914 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
7915 if ( value
!== this.align
) {
7916 // Default to 'left'
7917 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
7921 if ( value
=== 'inline' ) {
7922 this.$body
.append( this.$field
, this.$label
);
7924 this.$body
.append( this.$label
, this.$field
);
7926 // Set classes. The following classes can be used here:
7927 // * oo-ui-fieldLayout-align-left
7928 // * oo-ui-fieldLayout-align-right
7929 // * oo-ui-fieldLayout-align-top
7930 // * oo-ui-fieldLayout-align-inline
7932 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
7934 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
7942 * Layout made of a field, a button, and an optional label.
7945 * @extends OO.ui.FieldLayout
7948 * @param {OO.ui.Widget} fieldWidget Field widget
7949 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
7950 * @param {Object} [config] Configuration options
7951 * @cfg {string} [align='left'] Alignment mode, either 'left', 'right', 'top' or 'inline'
7952 * @cfg {string} [help] Explanatory text shown as a '?' icon.
7954 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
7955 // Allow passing positional parameters inside the config object
7956 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
7957 config
= fieldWidget
;
7958 fieldWidget
= config
.fieldWidget
;
7959 buttonWidget
= config
.buttonWidget
;
7962 // Configuration initialization
7963 config
= $.extend( { align
: 'left' }, config
);
7965 // Parent constructor
7966 OO
.ui
.ActionFieldLayout
.super.call( this, fieldWidget
, config
);
7969 this.fieldWidget
= fieldWidget
;
7970 this.buttonWidget
= buttonWidget
;
7971 this.$button
= $( '<div>' )
7972 .addClass( 'oo-ui-actionFieldLayout-button' )
7973 .append( this.buttonWidget
.$element
);
7974 this.$input
= $( '<div>' )
7975 .addClass( 'oo-ui-actionFieldLayout-input' )
7976 .append( this.fieldWidget
.$element
);
7978 .addClass( 'oo-ui-actionFieldLayout' )
7979 .append( this.$input
, this.$button
);
7984 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
7987 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
7988 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
7989 * configured with a label as well. For more information and examples,
7990 * please see the [OOjs UI documentation on MediaWiki][1].
7993 * // Example of a fieldset layout
7994 * var input1 = new OO.ui.TextInputWidget( {
7995 * placeholder: 'A text input field'
7998 * var input2 = new OO.ui.TextInputWidget( {
7999 * placeholder: 'A text input field'
8002 * var fieldset = new OO.ui.FieldsetLayout( {
8003 * label: 'Example of a fieldset layout'
8006 * fieldset.addItems( [
8007 * new OO.ui.FieldLayout( input1, {
8008 * label: 'Field One'
8010 * new OO.ui.FieldLayout( input2, {
8011 * label: 'Field Two'
8014 * $( 'body' ).append( fieldset.$element );
8016 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8019 * @extends OO.ui.Layout
8020 * @mixins OO.ui.IconElement
8021 * @mixins OO.ui.LabelElement
8022 * @mixins OO.ui.GroupElement
8025 * @param {Object} [config] Configuration options
8026 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
8028 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
8029 // Configuration initialization
8030 config
= config
|| {};
8032 // Parent constructor
8033 OO
.ui
.FieldsetLayout
.super.call( this, config
);
8035 // Mixin constructors
8036 OO
.ui
.IconElement
.call( this, config
);
8037 OO
.ui
.LabelElement
.call( this, config
);
8038 OO
.ui
.GroupElement
.call( this, config
);
8040 if ( config
.help
) {
8041 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
8042 classes
: [ 'oo-ui-fieldsetLayout-help' ],
8047 this.popupButtonWidget
.getPopup().$body
.append(
8049 .text( config
.help
)
8050 .addClass( 'oo-ui-fieldsetLayout-help-content' )
8052 this.$help
= this.popupButtonWidget
.$element
;
8054 this.$help
= $( [] );
8059 .addClass( 'oo-ui-fieldsetLayout' )
8060 .prepend( this.$help
, this.$icon
, this.$label
, this.$group
);
8061 if ( Array
.isArray( config
.items
) ) {
8062 this.addItems( config
.items
);
8068 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
8069 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.IconElement
);
8070 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.LabelElement
);
8071 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.GroupElement
);
8074 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
8075 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
8076 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
8079 * // Example of a form layout that wraps a fieldset layout
8080 * var input1 = new OO.ui.TextInputWidget( {
8081 * placeholder: 'Username'
8083 * var input2 = new OO.ui.TextInputWidget( {
8084 * placeholder: 'Password',
8087 * var submit = new OO.ui.ButtonInputWidget( {
8091 * var fieldset = new OO.ui.FieldsetLayout( {
8092 * label: 'A form layout'
8094 * fieldset.addItems( [
8095 * new OO.ui.FieldLayout( input1, {
8096 * label: 'Username',
8099 * new OO.ui.FieldLayout( input2, {
8100 * label: 'Password',
8103 * new OO.ui.FieldLayout( submit )
8105 * var form = new OO.ui.FormLayout( {
8106 * items: [ fieldset ],
8107 * action: '/api/formhandler',
8110 * $( 'body' ).append( form.$element );
8113 * @extends OO.ui.Layout
8114 * @mixins OO.ui.GroupElement
8117 * @param {Object} [config] Configuration options
8118 * @cfg {string} [method] HTML form `method` attribute
8119 * @cfg {string} [action] HTML form `action` attribute
8120 * @cfg {string} [enctype] HTML form `enctype` attribute
8121 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
8123 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
8124 // Configuration initialization
8125 config
= config
|| {};
8127 // Parent constructor
8128 OO
.ui
.FormLayout
.super.call( this, config
);
8130 // Mixin constructors
8131 OO
.ui
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
8134 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
8138 .addClass( 'oo-ui-formLayout' )
8140 method
: config
.method
,
8141 action
: config
.action
,
8142 enctype
: config
.enctype
8144 if ( Array
.isArray( config
.items
) ) {
8145 this.addItems( config
.items
);
8151 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
8152 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.GroupElement
);
8157 * A 'submit' event is emitted when the form is submitted.
8162 /* Static Properties */
8164 OO
.ui
.FormLayout
.static.tagName
= 'form';
8169 * Handle form submit events.
8172 * @param {jQuery.Event} e Submit event
8175 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
8176 this.emit( 'submit' );
8181 * Layout with a content and menu area.
8183 * The menu area can be positioned at the top, after, bottom or before. The content area will fill
8184 * all remaining space.
8187 * @extends OO.ui.Layout
8190 * @param {Object} [config] Configuration options
8191 * @cfg {number|string} [menuSize='18em'] Size of menu in pixels or any CSS unit
8192 * @cfg {boolean} [showMenu=true] Show menu
8193 * @cfg {string} [position='before'] Position of menu, either `top`, `after`, `bottom` or `before`
8194 * @cfg {boolean} [collapse] Collapse the menu out of view
8196 OO
.ui
.MenuLayout
= function OoUiMenuLayout( config
) {
8197 var positions
= this.constructor.static.menuPositions
;
8199 // Configuration initialization
8200 config
= config
|| {};
8202 // Parent constructor
8203 OO
.ui
.MenuLayout
.super.call( this, config
);
8206 this.showMenu
= config
.showMenu
!== false;
8207 this.menuSize
= config
.menuSize
|| '18em';
8208 this.menuPosition
= positions
[ config
.menuPosition
] || positions
.before
;
8213 * @property {jQuery}
8215 this.$menu
= $( '<div>' );
8219 * @property {jQuery}
8221 this.$content
= $( '<div>' );
8224 this.toggleMenu( this.showMenu
);
8227 .addClass( 'oo-ui-menuLayout-menu' )
8228 .css( this.menuPosition
.sizeProperty
, this.menuSize
);
8229 this.$content
.addClass( 'oo-ui-menuLayout-content' );
8231 .addClass( 'oo-ui-menuLayout ' + this.menuPosition
.className
)
8232 .append( this.$content
, this.$menu
);
8237 OO
.inheritClass( OO
.ui
.MenuLayout
, OO
.ui
.Layout
);
8239 /* Static Properties */
8241 OO
.ui
.MenuLayout
.static.menuPositions
= {
8243 sizeProperty
: 'height',
8244 className
: 'oo-ui-menuLayout-top'
8247 sizeProperty
: 'width',
8248 className
: 'oo-ui-menuLayout-after'
8251 sizeProperty
: 'height',
8252 className
: 'oo-ui-menuLayout-bottom'
8255 sizeProperty
: 'width',
8256 className
: 'oo-ui-menuLayout-before'
8265 * @param {boolean} showMenu Show menu, omit to toggle
8268 OO
.ui
.MenuLayout
.prototype.toggleMenu = function ( showMenu
) {
8269 showMenu
= showMenu
=== undefined ? !this.showMenu
: !!showMenu
;
8271 if ( this.showMenu
!== showMenu
) {
8272 this.showMenu
= showMenu
;
8280 * Check if menu is visible
8282 * @return {boolean} Menu is visible
8284 OO
.ui
.MenuLayout
.prototype.isMenuVisible = function () {
8285 return this.showMenu
;
8291 * @param {number|string} size Size of menu in pixels or any CSS unit
8294 OO
.ui
.MenuLayout
.prototype.setMenuSize = function ( size
) {
8295 this.menuSize
= size
;
8302 * Update menu and content CSS based on current menu size and visibility
8304 * This method is called internally when size or position is changed.
8306 OO
.ui
.MenuLayout
.prototype.updateSizes = function () {
8307 if ( this.showMenu
) {
8309 .css( this.menuPosition
.sizeProperty
, this.menuSize
)
8310 .css( 'overflow', '' );
8311 // Set offsets on all sides. CSS resets all but one with
8312 // 'important' rules so directionality flips are supported
8313 this.$content
.css( {
8315 right
: this.menuSize
,
8316 bottom
: this.menuSize
,
8321 .css( this.menuPosition
.sizeProperty
, 0 )
8322 .css( 'overflow', 'hidden' );
8323 this.$content
.css( {
8335 * @return {number|string} Menu size
8337 OO
.ui
.MenuLayout
.prototype.getMenuSize = function () {
8338 return this.menuSize
;
8342 * Set menu position.
8344 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
8345 * @throws {Error} If position value is not supported
8348 OO
.ui
.MenuLayout
.prototype.setMenuPosition = function ( position
) {
8349 var positions
= this.constructor.static.menuPositions
;
8351 if ( !positions
[ position
] ) {
8352 throw new Error( 'Cannot set position; unsupported position value: ' + position
);
8355 this.$menu
.css( this.menuPosition
.sizeProperty
, '' );
8356 this.$element
.removeClass( this.menuPosition
.className
);
8358 this.menuPosition
= positions
[ position
];
8361 this.$element
.addClass( this.menuPosition
.className
);
8367 * Get menu position.
8369 * @return {string} Menu position
8371 OO
.ui
.MenuLayout
.prototype.getMenuPosition = function () {
8372 return this.menuPosition
;
8376 * Layout containing a series of pages.
8379 * @extends OO.ui.MenuLayout
8382 * @param {Object} [config] Configuration options
8383 * @cfg {boolean} [continuous=false] Show all pages, one after another
8384 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when changing to a page
8385 * @cfg {boolean} [outlined=false] Show an outline
8386 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
8388 OO
.ui
.BookletLayout
= function OoUiBookletLayout( config
) {
8389 // Configuration initialization
8390 config
= config
|| {};
8392 // Parent constructor
8393 OO
.ui
.BookletLayout
.super.call( this, config
);
8396 this.currentPageName
= null;
8398 this.ignoreFocus
= false;
8399 this.stackLayout
= new OO
.ui
.StackLayout( { continuous
: !!config
.continuous
} );
8400 this.$content
.append( this.stackLayout
.$element
);
8401 this.autoFocus
= config
.autoFocus
=== undefined || !!config
.autoFocus
;
8402 this.outlineVisible
= false;
8403 this.outlined
= !!config
.outlined
;
8404 if ( this.outlined
) {
8405 this.editable
= !!config
.editable
;
8406 this.outlineControlsWidget
= null;
8407 this.outlineSelectWidget
= new OO
.ui
.OutlineSelectWidget();
8408 this.outlinePanel
= new OO
.ui
.PanelLayout( { scrollable
: true } );
8409 this.$menu
.append( this.outlinePanel
.$element
);
8410 this.outlineVisible
= true;
8411 if ( this.editable
) {
8412 this.outlineControlsWidget
= new OO
.ui
.OutlineControlsWidget(
8413 this.outlineSelectWidget
8417 this.toggleMenu( this.outlined
);
8420 this.stackLayout
.connect( this, { set: 'onStackLayoutSet' } );
8421 if ( this.outlined
) {
8422 this.outlineSelectWidget
.connect( this, { select
: 'onOutlineSelectWidgetSelect' } );
8424 if ( this.autoFocus
) {
8425 // Event 'focus' does not bubble, but 'focusin' does
8426 this.stackLayout
.$element
.on( 'focusin', this.onStackLayoutFocus
.bind( this ) );
8430 this.$element
.addClass( 'oo-ui-bookletLayout' );
8431 this.stackLayout
.$element
.addClass( 'oo-ui-bookletLayout-stackLayout' );
8432 if ( this.outlined
) {
8433 this.outlinePanel
.$element
8434 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
8435 .append( this.outlineSelectWidget
.$element
);
8436 if ( this.editable
) {
8437 this.outlinePanel
.$element
8438 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
8439 .append( this.outlineControlsWidget
.$element
);
8446 OO
.inheritClass( OO
.ui
.BookletLayout
, OO
.ui
.MenuLayout
);
8452 * @param {OO.ui.PageLayout} page Current page
8457 * @param {OO.ui.PageLayout[]} page Added pages
8458 * @param {number} index Index pages were added at
8463 * @param {OO.ui.PageLayout[]} pages Removed pages
8469 * Handle stack layout focus.
8471 * @param {jQuery.Event} e Focusin event
8473 OO
.ui
.BookletLayout
.prototype.onStackLayoutFocus = function ( e
) {
8476 // Find the page that an element was focused within
8477 $target
= $( e
.target
).closest( '.oo-ui-pageLayout' );
8478 for ( name
in this.pages
) {
8479 // Check for page match, exclude current page to find only page changes
8480 if ( this.pages
[ name
].$element
[ 0 ] === $target
[ 0 ] && name
!== this.currentPageName
) {
8481 this.setPage( name
);
8488 * Handle stack layout set events.
8490 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
8492 OO
.ui
.BookletLayout
.prototype.onStackLayoutSet = function ( page
) {
8495 page
.scrollElementIntoView( { complete: function () {
8496 if ( layout
.autoFocus
) {
8504 * Focus the first input in the current page.
8506 * If no page is selected, the first selectable page will be selected.
8507 * If the focus is already in an element on the current page, nothing will happen.
8509 OO
.ui
.BookletLayout
.prototype.focus = function () {
8510 var $input
, page
= this.stackLayout
.getCurrentItem();
8511 if ( !page
&& this.outlined
) {
8512 this.selectFirstSelectablePage();
8513 page
= this.stackLayout
.getCurrentItem();
8518 // Only change the focus if is not already in the current page
8519 if ( !page
.$element
.find( ':focus' ).length
) {
8520 $input
= page
.$element
.find( ':input:first' );
8521 if ( $input
.length
) {
8522 $input
[ 0 ].focus();
8528 * Handle outline widget select events.
8530 * @param {OO.ui.OptionWidget|null} item Selected item
8532 OO
.ui
.BookletLayout
.prototype.onOutlineSelectWidgetSelect = function ( item
) {
8534 this.setPage( item
.getData() );
8539 * Check if booklet has an outline.
8543 OO
.ui
.BookletLayout
.prototype.isOutlined = function () {
8544 return this.outlined
;
8548 * Check if booklet has editing controls.
8552 OO
.ui
.BookletLayout
.prototype.isEditable = function () {
8553 return this.editable
;
8557 * Check if booklet has a visible outline.
8561 OO
.ui
.BookletLayout
.prototype.isOutlineVisible = function () {
8562 return this.outlined
&& this.outlineVisible
;
8566 * Hide or show the outline.
8568 * @param {boolean} [show] Show outline, omit to invert current state
8571 OO
.ui
.BookletLayout
.prototype.toggleOutline = function ( show
) {
8572 if ( this.outlined
) {
8573 show
= show
=== undefined ? !this.outlineVisible
: !!show
;
8574 this.outlineVisible
= show
;
8575 this.toggleMenu( show
);
8582 * Get the outline widget.
8584 * @param {OO.ui.PageLayout} page Page to be selected
8585 * @return {OO.ui.PageLayout|null} Closest page to another
8587 OO
.ui
.BookletLayout
.prototype.getClosestPage = function ( page
) {
8588 var next
, prev
, level
,
8589 pages
= this.stackLayout
.getItems(),
8590 index
= $.inArray( page
, pages
);
8592 if ( index
!== -1 ) {
8593 next
= pages
[ index
+ 1 ];
8594 prev
= pages
[ index
- 1 ];
8595 // Prefer adjacent pages at the same level
8596 if ( this.outlined
) {
8597 level
= this.outlineSelectWidget
.getItemFromData( page
.getName() ).getLevel();
8600 level
=== this.outlineSelectWidget
.getItemFromData( prev
.getName() ).getLevel()
8606 level
=== this.outlineSelectWidget
.getItemFromData( next
.getName() ).getLevel()
8612 return prev
|| next
|| null;
8616 * Get the outline widget.
8618 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if booklet has no outline
8620 OO
.ui
.BookletLayout
.prototype.getOutline = function () {
8621 return this.outlineSelectWidget
;
8625 * Get the outline controls widget. If the outline is not editable, null is returned.
8627 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
8629 OO
.ui
.BookletLayout
.prototype.getOutlineControls = function () {
8630 return this.outlineControlsWidget
;
8634 * Get a page by name.
8636 * @param {string} name Symbolic name of page
8637 * @return {OO.ui.PageLayout|undefined} Page, if found
8639 OO
.ui
.BookletLayout
.prototype.getPage = function ( name
) {
8640 return this.pages
[ name
];
8644 * Get the current page
8646 * @return {OO.ui.PageLayout|undefined} Current page, if found
8648 OO
.ui
.BookletLayout
.prototype.getCurrentPage = function () {
8649 var name
= this.getCurrentPageName();
8650 return name
? this.getPage( name
) : undefined;
8654 * Get the current page name.
8656 * @return {string|null} Current page name
8658 OO
.ui
.BookletLayout
.prototype.getCurrentPageName = function () {
8659 return this.currentPageName
;
8663 * Add a page to the layout.
8665 * When pages are added with the same names as existing pages, the existing pages will be
8666 * automatically removed before the new pages are added.
8668 * @param {OO.ui.PageLayout[]} pages Pages to add
8669 * @param {number} index Index to insert pages after
8673 OO
.ui
.BookletLayout
.prototype.addPages = function ( pages
, index
) {
8674 var i
, len
, name
, page
, item
, currentIndex
,
8675 stackLayoutPages
= this.stackLayout
.getItems(),
8679 // Remove pages with same names
8680 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
8682 name
= page
.getName();
8684 if ( Object
.prototype.hasOwnProperty
.call( this.pages
, name
) ) {
8685 // Correct the insertion index
8686 currentIndex
= $.inArray( this.pages
[ name
], stackLayoutPages
);
8687 if ( currentIndex
!== -1 && currentIndex
+ 1 < index
) {
8690 remove
.push( this.pages
[ name
] );
8693 if ( remove
.length
) {
8694 this.removePages( remove
);
8698 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
8700 name
= page
.getName();
8701 this.pages
[ page
.getName() ] = page
;
8702 if ( this.outlined
) {
8703 item
= new OO
.ui
.OutlineOptionWidget( { data
: name
} );
8704 page
.setOutlineItem( item
);
8709 if ( this.outlined
&& items
.length
) {
8710 this.outlineSelectWidget
.addItems( items
, index
);
8711 this.selectFirstSelectablePage();
8713 this.stackLayout
.addItems( pages
, index
);
8714 this.emit( 'add', pages
, index
);
8720 * Remove a page from the layout.
8725 OO
.ui
.BookletLayout
.prototype.removePages = function ( pages
) {
8726 var i
, len
, name
, page
,
8729 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
8731 name
= page
.getName();
8732 delete this.pages
[ name
];
8733 if ( this.outlined
) {
8734 items
.push( this.outlineSelectWidget
.getItemFromData( name
) );
8735 page
.setOutlineItem( null );
8738 if ( this.outlined
&& items
.length
) {
8739 this.outlineSelectWidget
.removeItems( items
);
8740 this.selectFirstSelectablePage();
8742 this.stackLayout
.removeItems( pages
);
8743 this.emit( 'remove', pages
);
8749 * Clear all pages from the layout.
8754 OO
.ui
.BookletLayout
.prototype.clearPages = function () {
8756 pages
= this.stackLayout
.getItems();
8759 this.currentPageName
= null;
8760 if ( this.outlined
) {
8761 this.outlineSelectWidget
.clearItems();
8762 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
8763 pages
[ i
].setOutlineItem( null );
8766 this.stackLayout
.clearItems();
8768 this.emit( 'remove', pages
);
8774 * Set the current page by name.
8777 * @param {string} name Symbolic name of page
8779 OO
.ui
.BookletLayout
.prototype.setPage = function ( name
) {
8782 page
= this.pages
[ name
];
8784 if ( name
!== this.currentPageName
) {
8785 if ( this.outlined
) {
8786 selectedItem
= this.outlineSelectWidget
.getSelectedItem();
8787 if ( selectedItem
&& selectedItem
.getData() !== name
) {
8788 this.outlineSelectWidget
.selectItem( this.outlineSelectWidget
.getItemFromData( name
) );
8792 if ( this.currentPageName
&& this.pages
[ this.currentPageName
] ) {
8793 this.pages
[ this.currentPageName
].setActive( false );
8794 // Blur anything focused if the next page doesn't have anything focusable - this
8795 // is not needed if the next page has something focusable because once it is focused
8796 // this blur happens automatically
8797 if ( this.autoFocus
&& !page
.$element
.find( ':input' ).length
) {
8798 $focused
= this.pages
[ this.currentPageName
].$element
.find( ':focus' );
8799 if ( $focused
.length
) {
8800 $focused
[ 0 ].blur();
8804 this.currentPageName
= name
;
8805 this.stackLayout
.setItem( page
);
8806 page
.setActive( true );
8807 this.emit( 'set', page
);
8813 * Select the first selectable page.
8817 OO
.ui
.BookletLayout
.prototype.selectFirstSelectablePage = function () {
8818 if ( !this.outlineSelectWidget
.getSelectedItem() ) {
8819 this.outlineSelectWidget
.selectItem( this.outlineSelectWidget
.getFirstSelectableItem() );
8826 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
8827 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
8830 * // Example of a panel layout
8831 * var panel = new OO.ui.PanelLayout( {
8835 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
8837 * $( 'body' ).append( panel.$element );
8840 * @extends OO.ui.Layout
8843 * @param {Object} [config] Configuration options
8844 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
8845 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
8846 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
8847 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
8849 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
8850 // Configuration initialization
8851 config
= $.extend( {
8858 // Parent constructor
8859 OO
.ui
.PanelLayout
.super.call( this, config
);
8862 this.$element
.addClass( 'oo-ui-panelLayout' );
8863 if ( config
.scrollable
) {
8864 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
8866 if ( config
.padded
) {
8867 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
8869 if ( config
.expanded
) {
8870 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
8872 if ( config
.framed
) {
8873 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
8879 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
8882 * Page within an booklet layout.
8885 * @extends OO.ui.PanelLayout
8888 * @param {string} name Unique symbolic name of page
8889 * @param {Object} [config] Configuration options
8891 OO
.ui
.PageLayout
= function OoUiPageLayout( name
, config
) {
8892 // Allow passing positional parameters inside the config object
8893 if ( OO
.isPlainObject( name
) && config
=== undefined ) {
8898 // Configuration initialization
8899 config
= $.extend( { scrollable
: true }, config
);
8901 // Parent constructor
8902 OO
.ui
.PageLayout
.super.call( this, config
);
8906 this.outlineItem
= null;
8907 this.active
= false;
8910 this.$element
.addClass( 'oo-ui-pageLayout' );
8915 OO
.inheritClass( OO
.ui
.PageLayout
, OO
.ui
.PanelLayout
);
8921 * @param {boolean} active Page is active
8929 * @return {string} Symbolic name of page
8931 OO
.ui
.PageLayout
.prototype.getName = function () {
8936 * Check if page is active.
8938 * @return {boolean} Page is active
8940 OO
.ui
.PageLayout
.prototype.isActive = function () {
8947 * @return {OO.ui.OutlineOptionWidget|null} Outline item widget
8949 OO
.ui
.PageLayout
.prototype.getOutlineItem = function () {
8950 return this.outlineItem
;
8956 * @localdoc Subclasses should override #setupOutlineItem instead of this method to adjust the
8957 * outline item as desired; this method is called for setting (with an object) and unsetting
8958 * (with null) and overriding methods would have to check the value of `outlineItem` to avoid
8959 * operating on null instead of an OO.ui.OutlineOptionWidget object.
8961 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline item widget, null to clear
8964 OO
.ui
.PageLayout
.prototype.setOutlineItem = function ( outlineItem
) {
8965 this.outlineItem
= outlineItem
|| null;
8966 if ( outlineItem
) {
8967 this.setupOutlineItem();
8973 * Setup outline item.
8975 * @localdoc Subclasses should override this method to adjust the outline item as desired.
8977 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline item widget to setup
8980 OO
.ui
.PageLayout
.prototype.setupOutlineItem = function () {
8985 * Set page active state.
8987 * @param {boolean} Page is active
8990 OO
.ui
.PageLayout
.prototype.setActive = function ( active
) {
8993 if ( active
!== this.active
) {
8994 this.active
= active
;
8995 this.$element
.toggleClass( 'oo-ui-pageLayout-active', active
);
8996 this.emit( 'active', this.active
);
9001 * Layout containing a series of mutually exclusive pages.
9004 * @extends OO.ui.PanelLayout
9005 * @mixins OO.ui.GroupElement
9008 * @param {Object} [config] Configuration options
9009 * @cfg {boolean} [continuous=false] Show all pages, one after another
9010 * @cfg {OO.ui.Layout[]} [items] Layouts to add
9012 OO
.ui
.StackLayout
= function OoUiStackLayout( config
) {
9013 // Configuration initialization
9014 config
= $.extend( { scrollable
: true }, config
);
9016 // Parent constructor
9017 OO
.ui
.StackLayout
.super.call( this, config
);
9019 // Mixin constructors
9020 OO
.ui
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
9023 this.currentItem
= null;
9024 this.continuous
= !!config
.continuous
;
9027 this.$element
.addClass( 'oo-ui-stackLayout' );
9028 if ( this.continuous
) {
9029 this.$element
.addClass( 'oo-ui-stackLayout-continuous' );
9031 if ( Array
.isArray( config
.items
) ) {
9032 this.addItems( config
.items
);
9038 OO
.inheritClass( OO
.ui
.StackLayout
, OO
.ui
.PanelLayout
);
9039 OO
.mixinClass( OO
.ui
.StackLayout
, OO
.ui
.GroupElement
);
9045 * @param {OO.ui.Layout|null} item Current item or null if there is no longer a layout shown
9051 * Get the current item.
9053 * @return {OO.ui.Layout|null}
9055 OO
.ui
.StackLayout
.prototype.getCurrentItem = function () {
9056 return this.currentItem
;
9060 * Unset the current item.
9063 * @param {OO.ui.StackLayout} layout
9066 OO
.ui
.StackLayout
.prototype.unsetCurrentItem = function () {
9067 var prevItem
= this.currentItem
;
9068 if ( prevItem
=== null ) {
9072 this.currentItem
= null;
9073 this.emit( 'set', null );
9079 * Adding an existing item (by value) will move it.
9081 * @param {OO.ui.Layout[]} items Items to add
9082 * @param {number} [index] Index to insert items after
9085 OO
.ui
.StackLayout
.prototype.addItems = function ( items
, index
) {
9086 // Update the visibility
9087 this.updateHiddenState( items
, this.currentItem
);
9090 OO
.ui
.GroupElement
.prototype.addItems
.call( this, items
, index
);
9092 if ( !this.currentItem
&& items
.length
) {
9093 this.setItem( items
[ 0 ] );
9102 * Items will be detached, not removed, so they can be used later.
9104 * @param {OO.ui.Layout[]} items Items to remove
9108 OO
.ui
.StackLayout
.prototype.removeItems = function ( items
) {
9110 OO
.ui
.GroupElement
.prototype.removeItems
.call( this, items
);
9112 if ( $.inArray( this.currentItem
, items
) !== -1 ) {
9113 if ( this.items
.length
) {
9114 this.setItem( this.items
[ 0 ] );
9116 this.unsetCurrentItem();
9126 * Items will be detached, not removed, so they can be used later.
9131 OO
.ui
.StackLayout
.prototype.clearItems = function () {
9132 this.unsetCurrentItem();
9133 OO
.ui
.GroupElement
.prototype.clearItems
.call( this );
9141 * Any currently shown item will be hidden.
9143 * FIXME: If the passed item to show has not been added in the items list, then
9144 * this method drops it and unsets the current item.
9146 * @param {OO.ui.Layout} item Item to show
9150 OO
.ui
.StackLayout
.prototype.setItem = function ( item
) {
9151 if ( item
!== this.currentItem
) {
9152 this.updateHiddenState( this.items
, item
);
9154 if ( $.inArray( item
, this.items
) !== -1 ) {
9155 this.currentItem
= item
;
9156 this.emit( 'set', item
);
9158 this.unsetCurrentItem();
9166 * Update the visibility of all items in case of non-continuous view.
9168 * Ensure all items are hidden except for the selected one.
9169 * This method does nothing when the stack is continuous.
9171 * @param {OO.ui.Layout[]} items Item list iterate over
9172 * @param {OO.ui.Layout} [selectedItem] Selected item to show
9174 OO
.ui
.StackLayout
.prototype.updateHiddenState = function ( items
, selectedItem
) {
9177 if ( !this.continuous
) {
9178 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
9179 if ( !selectedItem
|| selectedItem
!== items
[ i
] ) {
9180 items
[ i
].$element
.addClass( 'oo-ui-element-hidden' );
9183 if ( selectedItem
) {
9184 selectedItem
.$element
.removeClass( 'oo-ui-element-hidden' );
9190 * Horizontal bar layout of tools as icon buttons.
9193 * @extends OO.ui.ToolGroup
9196 * @param {OO.ui.Toolbar} toolbar
9197 * @param {Object} [config] Configuration options
9199 OO
.ui
.BarToolGroup
= function OoUiBarToolGroup( toolbar
, config
) {
9200 // Allow passing positional parameters inside the config object
9201 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
9203 toolbar
= config
.toolbar
;
9206 // Parent constructor
9207 OO
.ui
.BarToolGroup
.super.call( this, toolbar
, config
);
9210 this.$element
.addClass( 'oo-ui-barToolGroup' );
9215 OO
.inheritClass( OO
.ui
.BarToolGroup
, OO
.ui
.ToolGroup
);
9217 /* Static Properties */
9219 OO
.ui
.BarToolGroup
.static.titleTooltips
= true;
9221 OO
.ui
.BarToolGroup
.static.accelTooltips
= true;
9223 OO
.ui
.BarToolGroup
.static.name
= 'bar';
9226 * Popup list of tools with an icon and optional label.
9230 * @extends OO.ui.ToolGroup
9231 * @mixins OO.ui.IconElement
9232 * @mixins OO.ui.IndicatorElement
9233 * @mixins OO.ui.LabelElement
9234 * @mixins OO.ui.TitledElement
9235 * @mixins OO.ui.ClippableElement
9238 * @param {OO.ui.Toolbar} toolbar
9239 * @param {Object} [config] Configuration options
9240 * @cfg {string} [header] Text to display at the top of the pop-up
9242 OO
.ui
.PopupToolGroup
= function OoUiPopupToolGroup( toolbar
, config
) {
9243 // Allow passing positional parameters inside the config object
9244 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
9246 toolbar
= config
.toolbar
;
9249 // Configuration initialization
9250 config
= config
|| {};
9252 // Parent constructor
9253 OO
.ui
.PopupToolGroup
.super.call( this, toolbar
, config
);
9255 // Mixin constructors
9256 OO
.ui
.IconElement
.call( this, config
);
9257 OO
.ui
.IndicatorElement
.call( this, config
);
9258 OO
.ui
.LabelElement
.call( this, config
);
9259 OO
.ui
.TitledElement
.call( this, config
);
9260 OO
.ui
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
9263 this.active
= false;
9264 this.dragging
= false;
9265 this.onBlurHandler
= this.onBlur
.bind( this );
9266 this.$handle
= $( '<span>' );
9270 mousedown
: this.onHandlePointerDown
.bind( this ),
9271 mouseup
: this.onHandlePointerUp
.bind( this )
9276 .addClass( 'oo-ui-popupToolGroup-handle' )
9277 .append( this.$icon
, this.$label
, this.$indicator
);
9278 // If the pop-up should have a header, add it to the top of the toolGroup.
9279 // Note: If this feature is useful for other widgets, we could abstract it into an
9280 // OO.ui.HeaderedElement mixin constructor.
9281 if ( config
.header
!== undefined ) {
9283 .prepend( $( '<span>' )
9284 .addClass( 'oo-ui-popupToolGroup-header' )
9285 .text( config
.header
)
9289 .addClass( 'oo-ui-popupToolGroup' )
9290 .prepend( this.$handle
);
9295 OO
.inheritClass( OO
.ui
.PopupToolGroup
, OO
.ui
.ToolGroup
);
9296 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.IconElement
);
9297 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.IndicatorElement
);
9298 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.LabelElement
);
9299 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.TitledElement
);
9300 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.ClippableElement
);
9302 /* Static Properties */
9309 OO
.ui
.PopupToolGroup
.prototype.setDisabled = function () {
9311 OO
.ui
.PopupToolGroup
.super.prototype.setDisabled
.apply( this, arguments
);
9313 if ( this.isDisabled() && this.isElementAttached() ) {
9314 this.setActive( false );
9319 * Handle focus being lost.
9321 * The event is actually generated from a mouseup, so it is not a normal blur event object.
9323 * @param {jQuery.Event} e Mouse up event
9325 OO
.ui
.PopupToolGroup
.prototype.onBlur = function ( e
) {
9326 // Only deactivate when clicking outside the dropdown element
9327 if ( $( e
.target
).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element
[ 0 ] ) {
9328 this.setActive( false );
9335 OO
.ui
.PopupToolGroup
.prototype.onPointerUp = function ( e
) {
9336 // Only close toolgroup when a tool was actually selected
9337 if ( !this.isDisabled() && e
.which
=== 1 && this.pressed
&& this.pressed
=== this.getTargetTool( e
) ) {
9338 this.setActive( false );
9340 return OO
.ui
.PopupToolGroup
.super.prototype.onPointerUp
.call( this, e
);
9344 * Handle mouse up events.
9346 * @param {jQuery.Event} e Mouse up event
9348 OO
.ui
.PopupToolGroup
.prototype.onHandlePointerUp = function () {
9353 * Handle mouse down events.
9355 * @param {jQuery.Event} e Mouse down event
9357 OO
.ui
.PopupToolGroup
.prototype.onHandlePointerDown = function ( e
) {
9358 if ( !this.isDisabled() && e
.which
=== 1 ) {
9359 this.setActive( !this.active
);
9365 * Switch into active mode.
9367 * When active, mouseup events anywhere in the document will trigger deactivation.
9369 OO
.ui
.PopupToolGroup
.prototype.setActive = function ( value
) {
9371 if ( this.active
!== value
) {
9372 this.active
= value
;
9374 this.getElementDocument().addEventListener( 'mouseup', this.onBlurHandler
, true );
9376 // Try anchoring the popup to the left first
9377 this.$element
.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
9378 this.toggleClipping( true );
9379 if ( this.isClippedHorizontally() ) {
9380 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
9381 this.toggleClipping( false );
9383 .removeClass( 'oo-ui-popupToolGroup-left' )
9384 .addClass( 'oo-ui-popupToolGroup-right' );
9385 this.toggleClipping( true );
9388 this.getElementDocument().removeEventListener( 'mouseup', this.onBlurHandler
, true );
9389 this.$element
.removeClass(
9390 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
9392 this.toggleClipping( false );
9398 * Drop down list layout of tools as labeled icon buttons.
9400 * This layout allows some tools to be collapsible, controlled by a "More" / "Fewer" option at the
9401 * bottom of the main list. These are not automatically positioned at the bottom of the list; you
9402 * may want to use the 'promote' and 'demote' configuration options to achieve this.
9405 * @extends OO.ui.PopupToolGroup
9408 * @param {OO.ui.Toolbar} toolbar
9409 * @param {Object} [config] Configuration options
9410 * @cfg {Array} [allowCollapse] List of tools that can be collapsed. Remaining tools will be always
9412 * @cfg {Array} [forceExpand] List of tools that *may not* be collapsed. All remaining tools will be
9413 * allowed to be collapsed.
9414 * @cfg {boolean} [expanded=false] Whether the collapsible tools are expanded by default
9416 OO
.ui
.ListToolGroup
= function OoUiListToolGroup( toolbar
, config
) {
9417 // Allow passing positional parameters inside the config object
9418 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
9420 toolbar
= config
.toolbar
;
9423 // Configuration initialization
9424 config
= config
|| {};
9426 // Properties (must be set before parent constructor, which calls #populate)
9427 this.allowCollapse
= config
.allowCollapse
;
9428 this.forceExpand
= config
.forceExpand
;
9429 this.expanded
= config
.expanded
!== undefined ? config
.expanded
: false;
9430 this.collapsibleTools
= [];
9432 // Parent constructor
9433 OO
.ui
.ListToolGroup
.super.call( this, toolbar
, config
);
9436 this.$element
.addClass( 'oo-ui-listToolGroup' );
9441 OO
.inheritClass( OO
.ui
.ListToolGroup
, OO
.ui
.PopupToolGroup
);
9443 /* Static Properties */
9445 OO
.ui
.ListToolGroup
.static.accelTooltips
= true;
9447 OO
.ui
.ListToolGroup
.static.name
= 'list';
9454 OO
.ui
.ListToolGroup
.prototype.populate = function () {
9455 var i
, len
, allowCollapse
= [];
9457 OO
.ui
.ListToolGroup
.super.prototype.populate
.call( this );
9459 // Update the list of collapsible tools
9460 if ( this.allowCollapse
!== undefined ) {
9461 allowCollapse
= this.allowCollapse
;
9462 } else if ( this.forceExpand
!== undefined ) {
9463 allowCollapse
= OO
.simpleArrayDifference( Object
.keys( this.tools
), this.forceExpand
);
9466 this.collapsibleTools
= [];
9467 for ( i
= 0, len
= allowCollapse
.length
; i
< len
; i
++ ) {
9468 if ( this.tools
[ allowCollapse
[ i
] ] !== undefined ) {
9469 this.collapsibleTools
.push( this.tools
[ allowCollapse
[ i
] ] );
9473 // Keep at the end, even when tools are added
9474 this.$group
.append( this.getExpandCollapseTool().$element
);
9476 this.getExpandCollapseTool().toggle( this.collapsibleTools
.length
!== 0 );
9477 this.updateCollapsibleState();
9480 OO
.ui
.ListToolGroup
.prototype.getExpandCollapseTool = function () {
9481 if ( this.expandCollapseTool
=== undefined ) {
9482 var ExpandCollapseTool = function () {
9483 ExpandCollapseTool
.super.apply( this, arguments
);
9486 OO
.inheritClass( ExpandCollapseTool
, OO
.ui
.Tool
);
9488 ExpandCollapseTool
.prototype.onSelect = function () {
9489 this.toolGroup
.expanded
= !this.toolGroup
.expanded
;
9490 this.toolGroup
.updateCollapsibleState();
9491 this.setActive( false );
9493 ExpandCollapseTool
.prototype.onUpdateState = function () {
9494 // Do nothing. Tool interface requires an implementation of this function.
9497 ExpandCollapseTool
.static.name
= 'more-fewer';
9499 this.expandCollapseTool
= new ExpandCollapseTool( this );
9501 return this.expandCollapseTool
;
9507 OO
.ui
.ListToolGroup
.prototype.onPointerUp = function ( e
) {
9508 var ret
= OO
.ui
.ListToolGroup
.super.prototype.onPointerUp
.call( this, e
);
9510 // Do not close the popup when the user wants to show more/fewer tools
9511 if ( $( e
.target
).closest( '.oo-ui-tool-name-more-fewer' ).length
) {
9512 // Prevent the popup list from being hidden
9513 this.setActive( true );
9519 OO
.ui
.ListToolGroup
.prototype.updateCollapsibleState = function () {
9522 this.getExpandCollapseTool()
9523 .setIcon( this.expanded
? 'collapse' : 'expand' )
9524 .setTitle( OO
.ui
.msg( this.expanded
? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
9526 for ( i
= 0, len
= this.collapsibleTools
.length
; i
< len
; i
++ ) {
9527 this.collapsibleTools
[ i
].toggle( this.expanded
);
9532 * Drop down menu layout of tools as selectable menu items.
9535 * @extends OO.ui.PopupToolGroup
9538 * @param {OO.ui.Toolbar} toolbar
9539 * @param {Object} [config] Configuration options
9541 OO
.ui
.MenuToolGroup
= function OoUiMenuToolGroup( toolbar
, config
) {
9542 // Allow passing positional parameters inside the config object
9543 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
9545 toolbar
= config
.toolbar
;
9548 // Configuration initialization
9549 config
= config
|| {};
9551 // Parent constructor
9552 OO
.ui
.MenuToolGroup
.super.call( this, toolbar
, config
);
9555 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
9558 this.$element
.addClass( 'oo-ui-menuToolGroup' );
9563 OO
.inheritClass( OO
.ui
.MenuToolGroup
, OO
.ui
.PopupToolGroup
);
9565 /* Static Properties */
9567 OO
.ui
.MenuToolGroup
.static.accelTooltips
= true;
9569 OO
.ui
.MenuToolGroup
.static.name
= 'menu';
9574 * Handle the toolbar state being updated.
9576 * When the state changes, the title of each active item in the menu will be joined together and
9577 * used as a label for the group. The label will be empty if none of the items are active.
9579 OO
.ui
.MenuToolGroup
.prototype.onUpdateState = function () {
9583 for ( name
in this.tools
) {
9584 if ( this.tools
[ name
].isActive() ) {
9585 labelTexts
.push( this.tools
[ name
].getTitle() );
9589 this.setLabel( labelTexts
.join( ', ' ) || ' ' );
9593 * Tool that shows a popup when selected.
9597 * @extends OO.ui.Tool
9598 * @mixins OO.ui.PopupElement
9601 * @param {OO.ui.ToolGroup} toolGroup
9602 * @param {Object} [config] Configuration options
9604 OO
.ui
.PopupTool
= function OoUiPopupTool( toolGroup
, config
) {
9605 // Allow passing positional parameters inside the config object
9606 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
9608 toolGroup
= config
.toolGroup
;
9611 // Parent constructor
9612 OO
.ui
.PopupTool
.super.call( this, toolGroup
, config
);
9614 // Mixin constructors
9615 OO
.ui
.PopupElement
.call( this, config
);
9619 .addClass( 'oo-ui-popupTool' )
9620 .append( this.popup
.$element
);
9625 OO
.inheritClass( OO
.ui
.PopupTool
, OO
.ui
.Tool
);
9626 OO
.mixinClass( OO
.ui
.PopupTool
, OO
.ui
.PopupElement
);
9631 * Handle the tool being selected.
9635 OO
.ui
.PopupTool
.prototype.onSelect = function () {
9636 if ( !this.isDisabled() ) {
9637 this.popup
.toggle();
9639 this.setActive( false );
9644 * Handle the toolbar state being updated.
9648 OO
.ui
.PopupTool
.prototype.onUpdateState = function () {
9649 this.setActive( false );
9653 * Tool that has a tool group inside. This is a bad workaround for the lack of proper hierarchical
9654 * menus in toolbars (T74159).
9658 * @extends OO.ui.Tool
9661 * @param {OO.ui.ToolGroup} toolGroup
9662 * @param {Object} [config] Configuration options
9664 OO
.ui
.ToolGroupTool
= function OoUiToolGroupTool( toolGroup
, config
) {
9665 // Allow passing positional parameters inside the config object
9666 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
9668 toolGroup
= config
.toolGroup
;
9671 // Parent constructor
9672 OO
.ui
.ToolGroupTool
.super.call( this, toolGroup
, config
);
9675 this.innerToolGroup
= this.createGroup( this.constructor.static.groupConfig
);
9678 this.$link
.remove();
9680 .addClass( 'oo-ui-toolGroupTool' )
9681 .append( this.innerToolGroup
.$element
);
9686 OO
.inheritClass( OO
.ui
.ToolGroupTool
, OO
.ui
.Tool
);
9688 /* Static Properties */
9691 * Tool group configuration. See OO.ui.Toolbar#setup for the accepted values.
9693 * @property {Object.<string,Array>}
9695 OO
.ui
.ToolGroupTool
.static.groupConfig
= {};
9700 * Handle the tool being selected.
9704 OO
.ui
.ToolGroupTool
.prototype.onSelect = function () {
9705 this.innerToolGroup
.setActive( !this.innerToolGroup
.active
);
9710 * Handle the toolbar state being updated.
9714 OO
.ui
.ToolGroupTool
.prototype.onUpdateState = function () {
9715 this.setActive( false );
9719 * Build a OO.ui.ToolGroup from the configuration.
9721 * @param {Object.<string,Array>} group Tool group configuration. See OO.ui.Toolbar#setup for the
9723 * @return {OO.ui.ListToolGroup}
9725 OO
.ui
.ToolGroupTool
.prototype.createGroup = function ( group
) {
9726 if ( group
.include
=== '*' ) {
9727 // Apply defaults to catch-all groups
9728 if ( group
.label
=== undefined ) {
9729 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
9733 return this.toolbar
.getToolGroupFactory().create( 'list', this.toolbar
, group
);
9737 * Mixin for OO.ui.Widget subclasses to provide OO.ui.GroupElement.
9739 * Use together with OO.ui.ItemWidget to make disabled state inheritable.
9744 * @extends OO.ui.GroupElement
9747 * @param {Object} [config] Configuration options
9749 OO
.ui
.GroupWidget
= function OoUiGroupWidget( config
) {
9750 // Parent constructor
9751 OO
.ui
.GroupWidget
.super.call( this, config
);
9756 OO
.inheritClass( OO
.ui
.GroupWidget
, OO
.ui
.GroupElement
);
9761 * Set the disabled state of the widget.
9763 * This will also update the disabled state of child widgets.
9765 * @param {boolean} disabled Disable widget
9768 OO
.ui
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
9772 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
9773 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
9775 // During construction, #setDisabled is called before the OO.ui.GroupElement constructor
9777 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
9778 this.items
[ i
].updateDisabled();
9786 * Mixin for widgets used as items in widgets that inherit OO.ui.GroupWidget.
9788 * Item widgets have a reference to a OO.ui.GroupWidget while they are attached to the group. This
9789 * allows bidirectional communication.
9791 * Use together with OO.ui.GroupWidget to make disabled state inheritable.
9799 OO
.ui
.ItemWidget
= function OoUiItemWidget() {
9806 * Check if widget is disabled.
9808 * Checks parent if present, making disabled state inheritable.
9810 * @return {boolean} Widget is disabled
9812 OO
.ui
.ItemWidget
.prototype.isDisabled = function () {
9813 return this.disabled
||
9814 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
9818 * Set group element is in.
9820 * @param {OO.ui.GroupElement|null} group Group element, null if none
9823 OO
.ui
.ItemWidget
.prototype.setElementGroup = function ( group
) {
9825 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
9826 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
9828 // Initialize item disabled states
9829 this.updateDisabled();
9835 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
9836 * Controls include moving items up and down, removing items, and adding different kinds of items.
9837 * ####Currently, this class is only used by {@link OO.ui.BookletLayout BookletLayouts}.####
9840 * @extends OO.ui.Widget
9841 * @mixins OO.ui.GroupElement
9842 * @mixins OO.ui.IconElement
9845 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
9846 * @param {Object} [config] Configuration options
9847 * @cfg {Object} [abilities] List of abilties
9848 * @cfg {boolean} [abilities.move=true] Allow moving movable items
9849 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
9851 OO
.ui
.OutlineControlsWidget
= function OoUiOutlineControlsWidget( outline
, config
) {
9852 // Allow passing positional parameters inside the config object
9853 if ( OO
.isPlainObject( outline
) && config
=== undefined ) {
9855 outline
= config
.outline
;
9858 // Configuration initialization
9859 config
= $.extend( { icon
: 'add' }, config
);
9861 // Parent constructor
9862 OO
.ui
.OutlineControlsWidget
.super.call( this, config
);
9864 // Mixin constructors
9865 OO
.ui
.GroupElement
.call( this, config
);
9866 OO
.ui
.IconElement
.call( this, config
);
9869 this.outline
= outline
;
9870 this.$movers
= $( '<div>' );
9871 this.upButton
= new OO
.ui
.ButtonWidget( {
9874 title
: OO
.ui
.msg( 'ooui-outline-control-move-up' )
9876 this.downButton
= new OO
.ui
.ButtonWidget( {
9879 title
: OO
.ui
.msg( 'ooui-outline-control-move-down' )
9881 this.removeButton
= new OO
.ui
.ButtonWidget( {
9884 title
: OO
.ui
.msg( 'ooui-outline-control-remove' )
9886 this.abilities
= { move: true, remove
: true };
9889 outline
.connect( this, {
9890 select
: 'onOutlineChange',
9891 add
: 'onOutlineChange',
9892 remove
: 'onOutlineChange'
9894 this.upButton
.connect( this, { click
: [ 'emit', 'move', -1 ] } );
9895 this.downButton
.connect( this, { click
: [ 'emit', 'move', 1 ] } );
9896 this.removeButton
.connect( this, { click
: [ 'emit', 'remove' ] } );
9899 this.$element
.addClass( 'oo-ui-outlineControlsWidget' );
9900 this.$group
.addClass( 'oo-ui-outlineControlsWidget-items' );
9902 .addClass( 'oo-ui-outlineControlsWidget-movers' )
9903 .append( this.removeButton
.$element
, this.upButton
.$element
, this.downButton
.$element
);
9904 this.$element
.append( this.$icon
, this.$group
, this.$movers
);
9905 this.setAbilities( config
.abilities
|| {} );
9910 OO
.inheritClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.Widget
);
9911 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.GroupElement
);
9912 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.IconElement
);
9918 * @param {number} places Number of places to move
9930 * @param {Object} abilities List of abilties
9931 * @param {boolean} [abilities.move] Allow moving movable items
9932 * @param {boolean} [abilities.remove] Allow removing removable items
9934 OO
.ui
.OutlineControlsWidget
.prototype.setAbilities = function ( abilities
) {
9937 for ( ability
in this.abilities
) {
9938 if ( abilities
[ability
] !== undefined ) {
9939 this.abilities
[ability
] = !!abilities
[ability
];
9943 this.onOutlineChange();
9949 * Handle outline change events.
9951 OO
.ui
.OutlineControlsWidget
.prototype.onOutlineChange = function () {
9952 var i
, len
, firstMovable
, lastMovable
,
9953 items
= this.outline
.getItems(),
9954 selectedItem
= this.outline
.getSelectedItem(),
9955 movable
= this.abilities
.move && selectedItem
&& selectedItem
.isMovable(),
9956 removable
= this.abilities
.remove
&& selectedItem
&& selectedItem
.isRemovable();
9961 while ( ++i
< len
) {
9962 if ( items
[ i
].isMovable() ) {
9963 firstMovable
= items
[ i
];
9969 if ( items
[ i
].isMovable() ) {
9970 lastMovable
= items
[ i
];
9975 this.upButton
.setDisabled( !movable
|| selectedItem
=== firstMovable
);
9976 this.downButton
.setDisabled( !movable
|| selectedItem
=== lastMovable
);
9977 this.removeButton
.setDisabled( !removable
);
9981 * ToggleWidget is mixed into other classes to create widgets with an on/off state.
9982 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
9988 * @param {Object} [config] Configuration options
9989 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
9990 * By default, the toggle is in the 'off' state.
9992 OO
.ui
.ToggleWidget
= function OoUiToggleWidget( config
) {
9993 // Configuration initialization
9994 config
= config
|| {};
10000 this.$element
.addClass( 'oo-ui-toggleWidget' );
10001 this.setValue( !!config
.value
);
10009 * A change event is emitted when the on/off state of the toggle changes.
10011 * @param {boolean} value Value representing the new state of the toggle
10017 * Get the value representing the toggle’s state.
10019 * @return {boolean} The on/off state of the toggle
10021 OO
.ui
.ToggleWidget
.prototype.getValue = function () {
10026 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
10028 * @param {boolean} value The state of the toggle
10032 OO
.ui
.ToggleWidget
.prototype.setValue = function ( value
) {
10034 if ( this.value
!== value
) {
10035 this.value
= value
;
10036 this.emit( 'change', value
);
10037 this.$element
.toggleClass( 'oo-ui-toggleWidget-on', value
);
10038 this.$element
.toggleClass( 'oo-ui-toggleWidget-off', !value
);
10039 this.$element
.attr( 'aria-checked', value
.toString() );
10045 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
10046 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
10047 * removed, and cleared from the group.
10050 * // Example: A ButtonGroupWidget with two buttons
10051 * var button1 = new OO.ui.PopupButtonWidget( {
10052 * label: 'Select a category',
10055 * $content: $( '<p>List of categories...</p>' ),
10060 * var button2 = new OO.ui.ButtonWidget( {
10061 * label: 'Add item'
10063 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
10064 * items: [button1, button2]
10066 * $( 'body' ).append( buttonGroup.$element );
10069 * @extends OO.ui.Widget
10070 * @mixins OO.ui.GroupElement
10073 * @param {Object} [config] Configuration options
10074 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
10076 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
10077 // Configuration initialization
10078 config
= config
|| {};
10080 // Parent constructor
10081 OO
.ui
.ButtonGroupWidget
.super.call( this, config
);
10083 // Mixin constructors
10084 OO
.ui
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
10087 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
10088 if ( Array
.isArray( config
.items
) ) {
10089 this.addItems( config
.items
);
10095 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
10096 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.GroupElement
);
10099 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
10100 * feels, and functionality can be customized via the class’s configuration options
10101 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
10104 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
10107 * // A button widget
10108 * var button = new OO.ui.ButtonWidget( {
10109 * label: 'Button with Icon',
10111 * iconTitle: 'Remove'
10113 * $( 'body' ).append( button.$element );
10115 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
10118 * @extends OO.ui.Widget
10119 * @mixins OO.ui.ButtonElement
10120 * @mixins OO.ui.IconElement
10121 * @mixins OO.ui.IndicatorElement
10122 * @mixins OO.ui.LabelElement
10123 * @mixins OO.ui.TitledElement
10124 * @mixins OO.ui.FlaggedElement
10125 * @mixins OO.ui.TabIndexedElement
10128 * @param {Object} [config] Configuration options
10129 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
10130 * @cfg {string} [target] The frame or window in which to open the hyperlink.
10131 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
10133 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
10134 // Configuration initialization
10135 // FIXME: The `nofollow` alias is deprecated and will be removed (T89767)
10136 config
= $.extend( { noFollow
: config
&& config
.nofollow
}, config
);
10138 // Parent constructor
10139 OO
.ui
.ButtonWidget
.super.call( this, config
);
10141 // Mixin constructors
10142 OO
.ui
.ButtonElement
.call( this, config
);
10143 OO
.ui
.IconElement
.call( this, config
);
10144 OO
.ui
.IndicatorElement
.call( this, config
);
10145 OO
.ui
.LabelElement
.call( this, config
);
10146 OO
.ui
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
10147 OO
.ui
.FlaggedElement
.call( this, config
);
10148 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
10152 this.target
= null;
10153 this.noFollow
= false;
10154 this.isHyperlink
= false;
10157 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
10159 .addClass( 'oo-ui-buttonWidget' )
10160 .append( this.$button
);
10161 this.setHref( config
.href
);
10162 this.setTarget( config
.target
);
10163 this.setNoFollow( config
.noFollow
);
10168 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
10169 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.ButtonElement
);
10170 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.IconElement
);
10171 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.IndicatorElement
);
10172 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.LabelElement
);
10173 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.TitledElement
);
10174 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.FlaggedElement
);
10175 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.TabIndexedElement
);
10182 OO
.ui
.ButtonWidget
.prototype.onMouseDown = function ( e
) {
10183 if ( !this.isDisabled() ) {
10184 // Remove the tab-index while the button is down to prevent the button from stealing focus
10185 this.$button
.removeAttr( 'tabindex' );
10188 return OO
.ui
.ButtonElement
.prototype.onMouseDown
.call( this, e
);
10194 OO
.ui
.ButtonWidget
.prototype.onMouseUp = function ( e
) {
10195 if ( !this.isDisabled() ) {
10196 // Restore the tab-index after the button is up to restore the button's accessibility
10197 this.$button
.attr( 'tabindex', this.tabIndex
);
10200 return OO
.ui
.ButtonElement
.prototype.onMouseUp
.call( this, e
);
10206 OO
.ui
.ButtonWidget
.prototype.onClick = function ( e
) {
10207 var ret
= OO
.ui
.ButtonElement
.prototype.onClick
.call( this, e
);
10208 if ( this.isHyperlink
) {
10217 OO
.ui
.ButtonWidget
.prototype.onKeyPress = function ( e
) {
10218 var ret
= OO
.ui
.ButtonElement
.prototype.onKeyPress
.call( this, e
);
10219 if ( this.isHyperlink
) {
10226 * Get hyperlink location.
10228 * @return {string} Hyperlink location
10230 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
10235 * Get hyperlink target.
10237 * @return {string} Hyperlink target
10239 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
10240 return this.target
;
10244 * Get search engine traversal hint.
10246 * @return {boolean} Whether search engines should avoid traversing this hyperlink
10248 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
10249 return this.noFollow
;
10253 * Set hyperlink location.
10255 * @param {string|null} href Hyperlink location, null to remove
10257 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
10258 href
= typeof href
=== 'string' ? href
: null;
10260 if ( href
!== this.href
) {
10262 if ( href
!== null ) {
10263 this.$button
.attr( 'href', href
);
10264 this.isHyperlink
= true;
10266 this.$button
.removeAttr( 'href' );
10267 this.isHyperlink
= false;
10275 * Set hyperlink target.
10277 * @param {string|null} target Hyperlink target, null to remove
10279 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
10280 target
= typeof target
=== 'string' ? target
: null;
10282 if ( target
!== this.target
) {
10283 this.target
= target
;
10284 if ( target
!== null ) {
10285 this.$button
.attr( 'target', target
);
10287 this.$button
.removeAttr( 'target' );
10295 * Set search engine traversal hint.
10297 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
10299 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
10300 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
10302 if ( noFollow
!== this.noFollow
) {
10303 this.noFollow
= noFollow
;
10305 this.$button
.attr( 'rel', 'nofollow' );
10307 this.$button
.removeAttr( 'rel' );
10315 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
10316 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
10319 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
10320 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
10323 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
10326 * @extends OO.ui.ButtonWidget
10327 * @mixins OO.ui.PendingElement
10330 * @param {Object} [config] Configuration options
10331 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
10332 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
10333 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
10334 * for more information about setting modes.
10335 * @cfg {boolean} [framed=false] Render the action button with a frame
10337 OO
.ui
.ActionWidget
= function OoUiActionWidget( config
) {
10338 // Configuration initialization
10339 config
= $.extend( { framed
: false }, config
);
10341 // Parent constructor
10342 OO
.ui
.ActionWidget
.super.call( this, config
);
10344 // Mixin constructors
10345 OO
.ui
.PendingElement
.call( this, config
);
10348 this.action
= config
.action
|| '';
10349 this.modes
= config
.modes
|| [];
10354 this.$element
.addClass( 'oo-ui-actionWidget' );
10359 OO
.inheritClass( OO
.ui
.ActionWidget
, OO
.ui
.ButtonWidget
);
10360 OO
.mixinClass( OO
.ui
.ActionWidget
, OO
.ui
.PendingElement
);
10365 * A resize event is emitted when the size of the widget changes.
10373 * Check if the action is configured to be available in the specified `mode`.
10375 * @param {string} mode Name of mode
10376 * @return {boolean} The action is configured with the mode
10378 OO
.ui
.ActionWidget
.prototype.hasMode = function ( mode
) {
10379 return this.modes
.indexOf( mode
) !== -1;
10383 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
10387 OO
.ui
.ActionWidget
.prototype.getAction = function () {
10388 return this.action
;
10392 * Get the symbolic name of the mode or modes for which the action is configured to be available.
10394 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
10395 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
10398 * @return {string[]}
10400 OO
.ui
.ActionWidget
.prototype.getModes = function () {
10401 return this.modes
.slice();
10405 * Emit a resize event if the size has changed.
10410 OO
.ui
.ActionWidget
.prototype.propagateResize = function () {
10413 if ( this.isElementAttached() ) {
10414 width
= this.$element
.width();
10415 height
= this.$element
.height();
10417 if ( width
!== this.width
|| height
!== this.height
) {
10418 this.width
= width
;
10419 this.height
= height
;
10420 this.emit( 'resize' );
10430 OO
.ui
.ActionWidget
.prototype.setIcon = function () {
10432 OO
.ui
.IconElement
.prototype.setIcon
.apply( this, arguments
);
10433 this.propagateResize();
10441 OO
.ui
.ActionWidget
.prototype.setLabel = function () {
10443 OO
.ui
.LabelElement
.prototype.setLabel
.apply( this, arguments
);
10444 this.propagateResize();
10452 OO
.ui
.ActionWidget
.prototype.setFlags = function () {
10454 OO
.ui
.FlaggedElement
.prototype.setFlags
.apply( this, arguments
);
10455 this.propagateResize();
10463 OO
.ui
.ActionWidget
.prototype.clearFlags = function () {
10465 OO
.ui
.FlaggedElement
.prototype.clearFlags
.apply( this, arguments
);
10466 this.propagateResize();
10472 * Toggle the visibility of the action button.
10474 * @param {boolean} [show] Show button, omit to toggle visibility
10477 OO
.ui
.ActionWidget
.prototype.toggle = function () {
10479 OO
.ui
.ActionWidget
.super.prototype.toggle
.apply( this, arguments
);
10480 this.propagateResize();
10486 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
10487 * which is used to display additional information or options.
10490 * // Example of a popup button.
10491 * var popupButton = new OO.ui.PopupButtonWidget( {
10492 * label: 'Popup button with options',
10495 * $content: $( '<p>Additional options here.</p>' ),
10500 * // Append the button to the DOM.
10501 * $( 'body' ).append( popupButton.$element );
10504 * @extends OO.ui.ButtonWidget
10505 * @mixins OO.ui.PopupElement
10508 * @param {Object} [config] Configuration options
10510 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
10511 // Parent constructor
10512 OO
.ui
.PopupButtonWidget
.super.call( this, config
);
10514 // Mixin constructors
10515 OO
.ui
.PopupElement
.call( this, config
);
10518 this.connect( this, { click
: 'onAction' } );
10522 .addClass( 'oo-ui-popupButtonWidget' )
10523 .attr( 'aria-haspopup', 'true' )
10524 .append( this.popup
.$element
);
10529 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
10530 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.PopupElement
);
10535 * Handle the button action being triggered.
10539 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
10540 this.popup
.toggle();
10544 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
10545 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
10546 * configured with {@link OO.ui.IconElement icons}, {@link OO.ui.IndicatorElement indicators},
10547 * {@link OO.ui.TitledElement titles}, {@link OO.ui.FlaggedElement styling flags},
10548 * and {@link OO.ui.LabelElement labels}. Please see
10549 * the [OOjs UI documentation][1] on MediaWiki for more information.
10552 * // Toggle buttons in the 'off' and 'on' state.
10553 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
10554 * label: 'Toggle Button off'
10556 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
10557 * label: 'Toggle Button on',
10560 * // Append the buttons to the DOM.
10561 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
10563 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
10566 * @extends OO.ui.ButtonWidget
10567 * @mixins OO.ui.ToggleWidget
10570 * @param {Object} [config] Configuration options
10571 * @cfg {boolean} [value=false] The toggle button’s initial on/off
10572 * state. By default, the button is in the 'off' state.
10574 OO
.ui
.ToggleButtonWidget
= function OoUiToggleButtonWidget( config
) {
10575 // Configuration initialization
10576 config
= config
|| {};
10578 // Parent constructor
10579 OO
.ui
.ToggleButtonWidget
.super.call( this, config
);
10581 // Mixin constructors
10582 OO
.ui
.ToggleWidget
.call( this, config
);
10585 this.connect( this, { click
: 'onAction' } );
10588 this.$element
.addClass( 'oo-ui-toggleButtonWidget' );
10593 OO
.inheritClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.ButtonWidget
);
10594 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.ToggleWidget
);
10601 * Handle the button action being triggered.
10603 OO
.ui
.ToggleButtonWidget
.prototype.onAction = function () {
10604 this.setValue( !this.value
);
10610 OO
.ui
.ToggleButtonWidget
.prototype.setValue = function ( value
) {
10612 if ( value
!== this.value
) {
10613 this.$button
.attr( 'aria-pressed', value
.toString() );
10614 this.setActive( value
);
10617 // Parent method (from mixin)
10618 OO
.ui
.ToggleWidget
.prototype.setValue
.call( this, value
);
10624 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
10625 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
10626 * users can interact with it.
10629 * // Example: A DropdownWidget with a menu that contains three options
10630 * var dropDown = new OO.ui.DropdownWidget( {
10631 * label: 'Dropdown menu: Select a menu option',
10634 * new OO.ui.MenuOptionWidget( {
10638 * new OO.ui.MenuOptionWidget( {
10642 * new OO.ui.MenuOptionWidget( {
10650 * $( 'body' ).append( dropDown.$element );
10652 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
10654 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
10657 * @extends OO.ui.Widget
10658 * @mixins OO.ui.IconElement
10659 * @mixins OO.ui.IndicatorElement
10660 * @mixins OO.ui.LabelElement
10661 * @mixins OO.ui.TitledElement
10662 * @mixins OO.ui.TabIndexedElement
10665 * @param {Object} [config] Configuration options
10666 * @cfg {Object} [menu] Configuration options to pass to menu widget
10668 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
10669 // Configuration initialization
10670 config
= $.extend( { indicator
: 'down' }, config
);
10672 // Parent constructor
10673 OO
.ui
.DropdownWidget
.super.call( this, config
);
10675 // Properties (must be set before TabIndexedElement constructor call)
10676 this.$handle
= this.$( '<span>' );
10678 // Mixin constructors
10679 OO
.ui
.IconElement
.call( this, config
);
10680 OO
.ui
.IndicatorElement
.call( this, config
);
10681 OO
.ui
.LabelElement
.call( this, config
);
10682 OO
.ui
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
10683 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
10686 this.menu
= new OO
.ui
.MenuSelectWidget( $.extend( { widget
: this }, config
.menu
) );
10690 click
: this.onClick
.bind( this ),
10691 keypress
: this.onKeyPress
.bind( this )
10693 this.menu
.connect( this, { select
: 'onMenuSelect' } );
10697 .addClass( 'oo-ui-dropdownWidget-handle' )
10698 .append( this.$icon
, this.$label
, this.$indicator
);
10700 .addClass( 'oo-ui-dropdownWidget' )
10701 .append( this.$handle
, this.menu
.$element
);
10706 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
10707 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.IconElement
);
10708 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.IndicatorElement
);
10709 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.LabelElement
);
10710 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.TitledElement
);
10711 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.TabIndexedElement
);
10718 * @return {OO.ui.MenuSelectWidget} Menu of widget
10720 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
10725 * Handles menu select events.
10728 * @param {OO.ui.MenuOptionWidget} item Selected menu item
10730 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
10737 selectedLabel
= item
.getLabel();
10739 // If the label is a DOM element, clone it, because setLabel will append() it
10740 if ( selectedLabel
instanceof jQuery
) {
10741 selectedLabel
= selectedLabel
.clone();
10744 this.setLabel( selectedLabel
);
10748 * Handle mouse click events.
10751 * @param {jQuery.Event} e Mouse click event
10753 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
10754 if ( !this.isDisabled() && e
.which
=== 1 ) {
10755 this.menu
.toggle();
10761 * Handle key press events.
10764 * @param {jQuery.Event} e Key press event
10766 OO
.ui
.DropdownWidget
.prototype.onKeyPress = function ( e
) {
10767 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
10768 this.menu
.toggle();
10774 * IconWidget is a generic widget for {@link OO.ui.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
10775 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
10776 * for a list of icons included in the library.
10779 * // An icon widget with a label
10780 * var myIcon = new OO.ui.IconWidget( {
10782 * iconTitle: 'Help'
10784 * // Create a label.
10785 * var iconLabel = new OO.ui.LabelWidget( {
10788 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
10790 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
10793 * @extends OO.ui.Widget
10794 * @mixins OO.ui.IconElement
10795 * @mixins OO.ui.TitledElement
10798 * @param {Object} [config] Configuration options
10800 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
10801 // Configuration initialization
10802 config
= config
|| {};
10804 // Parent constructor
10805 OO
.ui
.IconWidget
.super.call( this, config
);
10807 // Mixin constructors
10808 OO
.ui
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
10809 OO
.ui
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
10812 this.$element
.addClass( 'oo-ui-iconWidget' );
10817 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
10818 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.IconElement
);
10819 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.TitledElement
);
10821 /* Static Properties */
10823 OO
.ui
.IconWidget
.static.tagName
= 'span';
10826 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
10827 * attention to the status of an item or to clarify the function of a control. For a list of
10828 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
10831 * // Example of an indicator widget
10832 * var indicator1 = new OO.ui.IndicatorWidget( {
10833 * indicator: 'alert'
10836 * // Create a fieldset layout to add a label
10837 * var fieldset = new OO.ui.FieldsetLayout();
10838 * fieldset.addItems( [
10839 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
10841 * $( 'body' ).append( fieldset.$element );
10843 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
10846 * @extends OO.ui.Widget
10847 * @mixins OO.ui.IndicatorElement
10848 * @mixins OO.ui.TitledElement
10851 * @param {Object} [config] Configuration options
10853 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
10854 // Configuration initialization
10855 config
= config
|| {};
10857 // Parent constructor
10858 OO
.ui
.IndicatorWidget
.super.call( this, config
);
10860 // Mixin constructors
10861 OO
.ui
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
10862 OO
.ui
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
10865 this.$element
.addClass( 'oo-ui-indicatorWidget' );
10870 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
10871 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.IndicatorElement
);
10872 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.TitledElement
);
10874 /* Static Properties */
10876 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
10879 * InputWidget is the base class for all input widgets, which
10880 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
10881 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
10882 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
10884 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
10888 * @extends OO.ui.Widget
10889 * @mixins OO.ui.FlaggedElement
10890 * @mixins OO.ui.TabIndexedElement
10893 * @param {Object} [config] Configuration options
10894 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
10895 * @cfg {string} [value=''] The value of the input.
10896 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
10897 * before it is accepted.
10899 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
10900 // Configuration initialization
10901 config
= config
|| {};
10903 // Parent constructor
10904 OO
.ui
.InputWidget
.super.call( this, config
);
10907 this.$input
= this.getInputElement( config
);
10909 this.inputFilter
= config
.inputFilter
;
10911 // Mixin constructors
10912 OO
.ui
.FlaggedElement
.call( this, config
);
10913 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
10916 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
10920 .attr( 'name', config
.name
)
10921 .prop( 'disabled', this.isDisabled() );
10922 this.$element
.addClass( 'oo-ui-inputWidget' ).append( this.$input
, $( '<span>' ) );
10923 this.setValue( config
.value
);
10928 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
10929 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.FlaggedElement
);
10930 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.TabIndexedElement
);
10937 * A change event is emitted when the value of the input changes.
10939 * @param {string} value
10945 * Get input element.
10947 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
10948 * different circumstances. The element must have a `value` property (like form elements).
10951 * @param {Object} config Configuration options
10952 * @return {jQuery} Input element
10954 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
10955 return $( '<input>' );
10959 * Handle potentially value-changing events.
10962 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
10964 OO
.ui
.InputWidget
.prototype.onEdit = function () {
10966 if ( !this.isDisabled() ) {
10967 // Allow the stack to clear so the value will be updated
10968 setTimeout( function () {
10969 widget
.setValue( widget
.$input
.val() );
10975 * Get the value of the input.
10977 * @return {string} Input value
10979 OO
.ui
.InputWidget
.prototype.getValue = function () {
10980 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
10981 // it, and we won't know unless they're kind enough to trigger a 'change' event.
10982 var value
= this.$input
.val();
10983 if ( this.value
!== value
) {
10984 this.setValue( value
);
10990 * Set the direction of the input, either RTL (right-to-left) or LTR (left-to-right).
10992 * @param {boolean} isRTL
10993 * Direction is right-to-left
10995 OO
.ui
.InputWidget
.prototype.setRTL = function ( isRTL
) {
10996 this.$input
.prop( 'dir', isRTL
? 'rtl' : 'ltr' );
11000 * Set the value of the input.
11002 * @param {string} value New value
11006 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
11007 value
= this.cleanUpValue( value
);
11008 // Update the DOM if it has changed. Note that with cleanUpValue, it
11009 // is possible for the DOM value to change without this.value changing.
11010 if ( this.$input
.val() !== value
) {
11011 this.$input
.val( value
);
11013 if ( this.value
!== value
) {
11014 this.value
= value
;
11015 this.emit( 'change', this.value
);
11021 * Clean up incoming value.
11023 * Ensures value is a string, and converts undefined and null to empty string.
11026 * @param {string} value Original value
11027 * @return {string} Cleaned up value
11029 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
11030 if ( value
=== undefined || value
=== null ) {
11032 } else if ( this.inputFilter
) {
11033 return this.inputFilter( String( value
) );
11035 return String( value
);
11040 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
11041 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
11044 OO
.ui
.InputWidget
.prototype.simulateLabelClick = function () {
11045 if ( !this.isDisabled() ) {
11046 if ( this.$input
.is( ':checkbox, :radio' ) ) {
11047 this.$input
.click();
11049 if ( this.$input
.is( ':input' ) ) {
11050 this.$input
[ 0 ].focus();
11058 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
11059 OO
.ui
.InputWidget
.super.prototype.setDisabled
.call( this, state
);
11060 if ( this.$input
) {
11061 this.$input
.prop( 'disabled', this.isDisabled() );
11071 OO
.ui
.InputWidget
.prototype.focus = function () {
11072 this.$input
[ 0 ].focus();
11081 OO
.ui
.InputWidget
.prototype.blur = function () {
11082 this.$input
[ 0 ].blur();
11087 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
11088 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
11089 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
11090 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
11091 * [OOjs UI documentation on MediaWiki] [1] for more information.
11094 * // A ButtonInputWidget rendered as an HTML button, the default.
11095 * var button = new OO.ui.ButtonInputWidget( {
11096 * label: 'Input button',
11100 * $( 'body' ).append( button.$element );
11102 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
11105 * @extends OO.ui.InputWidget
11106 * @mixins OO.ui.ButtonElement
11107 * @mixins OO.ui.IconElement
11108 * @mixins OO.ui.IndicatorElement
11109 * @mixins OO.ui.LabelElement
11110 * @mixins OO.ui.TitledElement
11111 * @mixins OO.ui.FlaggedElement
11114 * @param {Object} [config] Configuration options
11115 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
11116 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
11117 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
11118 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
11119 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
11121 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
11122 // Configuration initialization
11123 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
11125 // Properties (must be set before parent constructor, which calls #setValue)
11126 this.useInputTag
= config
.useInputTag
;
11128 // Parent constructor
11129 OO
.ui
.ButtonInputWidget
.super.call( this, config
);
11131 // Mixin constructors
11132 OO
.ui
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
11133 OO
.ui
.IconElement
.call( this, config
);
11134 OO
.ui
.IndicatorElement
.call( this, config
);
11135 OO
.ui
.LabelElement
.call( this, config
);
11136 OO
.ui
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
11137 OO
.ui
.FlaggedElement
.call( this, config
);
11140 if ( !config
.useInputTag
) {
11141 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
11143 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
11148 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
11149 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.ButtonElement
);
11150 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.IconElement
);
11151 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.IndicatorElement
);
11152 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.LabelElement
);
11153 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.TitledElement
);
11154 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.FlaggedElement
);
11162 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
11163 var html
= '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + config
.type
+ '">';
11170 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
11172 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
11173 * text, or `null` for no label
11176 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
11177 OO
.ui
.LabelElement
.prototype.setLabel
.call( this, label
);
11179 if ( this.useInputTag
) {
11180 if ( typeof label
=== 'function' ) {
11181 label
= OO
.ui
.resolveMsg( label
);
11183 if ( label
instanceof jQuery
) {
11184 label
= label
.text();
11189 this.$input
.val( label
);
11196 * Set the value of the input.
11198 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
11199 * they do not support {@link #value values}.
11201 * @param {string} value New value
11204 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
11205 if ( !this.useInputTag
) {
11206 OO
.ui
.ButtonInputWidget
.super.prototype.setValue
.call( this, value
);
11212 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
11213 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
11214 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
11215 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
11218 * // An example of selected, unselected, and disabled checkbox inputs
11219 * var checkbox1=new OO.ui.CheckboxInputWidget( {
11223 * var checkbox2=new OO.ui.CheckboxInputWidget( {
11226 * var checkbox3=new OO.ui.CheckboxInputWidget( {
11230 * // Create a fieldset layout with fields for each checkbox.
11231 * var fieldset = new OO.ui.FieldsetLayout( {
11232 * label: 'Checkboxes'
11234 * fieldset.addItems( [
11235 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
11236 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
11237 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
11239 * $( 'body' ).append( fieldset.$element );
11241 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11244 * @extends OO.ui.InputWidget
11247 * @param {Object} [config] Configuration options
11248 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
11250 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
11251 // Configuration initialization
11252 config
= config
|| {};
11254 // Parent constructor
11255 OO
.ui
.CheckboxInputWidget
.super.call( this, config
);
11258 this.$element
.addClass( 'oo-ui-checkboxInputWidget' );
11259 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
11264 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
11272 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
11273 return $( '<input type="checkbox" />' );
11279 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
11281 if ( !this.isDisabled() ) {
11282 // Allow the stack to clear so the value will be updated
11283 setTimeout( function () {
11284 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
11290 * Set selection state of this checkbox.
11292 * @param {boolean} state `true` for selected
11295 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
11297 if ( this.selected
!== state
) {
11298 this.selected
= state
;
11299 this.$input
.prop( 'checked', this.selected
);
11300 this.emit( 'change', this.selected
);
11306 * Check if this checkbox is selected.
11308 * @return {boolean} Checkbox is selected
11310 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
11311 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
11312 // it, and we won't know unless they're kind enough to trigger a 'change' event.
11313 var selected
= this.$input
.prop( 'checked' );
11314 if ( this.selected
!== selected
) {
11315 this.setSelected( selected
);
11317 return this.selected
;
11321 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
11322 * within a {@link OO.ui.FormLayout form}. The selected value is synchronized with the value
11323 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
11324 * more information about input widgets.
11327 * // Example: A DropdownInputWidget with three options
11328 * var dropDown = new OO.ui.DropdownInputWidget( {
11329 * label: 'Dropdown menu: Select a menu option',
11331 * { data: 'a', label: 'First' } ,
11332 * { data: 'b', label: 'Second'} ,
11333 * { data: 'c', label: 'Third' }
11336 * $( 'body' ).append( dropDown.$element );
11338 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11341 * @extends OO.ui.InputWidget
11344 * @param {Object} [config] Configuration options
11345 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
11347 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
11348 // Configuration initialization
11349 config
= config
|| {};
11351 // Properties (must be done before parent constructor which calls #setDisabled)
11352 this.dropdownWidget
= new OO
.ui
.DropdownWidget();
11354 // Parent constructor
11355 OO
.ui
.DropdownInputWidget
.super.call( this, config
);
11358 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
11361 this.setOptions( config
.options
|| [] );
11363 .addClass( 'oo-ui-dropdownInputWidget' )
11364 .append( this.dropdownWidget
.$element
);
11369 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
11377 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
11378 return $( '<input type="hidden">' );
11382 * Handles menu select events.
11385 * @param {OO.ui.MenuOptionWidget} item Selected menu item
11387 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
11388 this.setValue( item
.getData() );
11394 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
11395 var item
= this.dropdownWidget
.getMenu().getItemFromData( value
);
11397 this.dropdownWidget
.getMenu().selectItem( item
);
11399 OO
.ui
.DropdownInputWidget
.super.prototype.setValue
.call( this, value
);
11406 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
11407 this.dropdownWidget
.setDisabled( state
);
11408 OO
.ui
.DropdownInputWidget
.super.prototype.setDisabled
.call( this, state
);
11413 * Set the options available for this input.
11415 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
11418 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
11419 var value
= this.getValue();
11421 // Rebuild the dropdown menu
11422 this.dropdownWidget
.getMenu()
11424 .addItems( options
.map( function ( opt
) {
11425 return new OO
.ui
.MenuOptionWidget( {
11427 label
: opt
.label
!== undefined ? opt
.label
: opt
.data
11431 // Restore the previous value, or reset to something sensible
11432 if ( this.dropdownWidget
.getMenu().getItemFromData( value
) ) {
11433 // Previous value is still available, ensure consistency with the dropdown
11434 this.setValue( value
);
11436 // No longer valid, reset
11437 if ( options
.length
) {
11438 this.setValue( options
[ 0 ].data
);
11448 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
11449 this.dropdownWidget
.getMenu().toggle( true );
11456 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
11457 this.dropdownWidget
.getMenu().toggle( false );
11462 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
11463 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
11464 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
11465 * please see the [OOjs UI documentation on MediaWiki][1].
11468 * // An example of selected, unselected, and disabled radio inputs
11469 * var radio1 = new OO.ui.RadioInputWidget( {
11473 * var radio2 = new OO.ui.RadioInputWidget( {
11476 * var radio3 = new OO.ui.RadioInputWidget( {
11480 * // Create a fieldset layout with fields for each radio button.
11481 * var fieldset = new OO.ui.FieldsetLayout( {
11482 * label: 'Radio inputs'
11484 * fieldset.addItems( [
11485 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
11486 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
11487 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
11489 * $( 'body' ).append( fieldset.$element );
11491 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11494 * @extends OO.ui.InputWidget
11497 * @param {Object} [config] Configuration options
11498 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
11500 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
11501 // Configuration initialization
11502 config
= config
|| {};
11504 // Parent constructor
11505 OO
.ui
.RadioInputWidget
.super.call( this, config
);
11508 this.$element
.addClass( 'oo-ui-radioInputWidget' );
11509 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
11514 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
11522 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
11523 return $( '<input type="radio" />' );
11529 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
11530 // RadioInputWidget doesn't track its state.
11534 * Set selection state of this radio button.
11536 * @param {boolean} state `true` for selected
11539 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
11540 // RadioInputWidget doesn't track its state.
11541 this.$input
.prop( 'checked', state
);
11546 * Check if this radio button is selected.
11548 * @return {boolean} Radio is selected
11550 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
11551 return this.$input
.prop( 'checked' );
11555 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
11556 * size of the field as well as its presentation. In addition, these widgets can be configured
11557 * with {@link OO.ui.IconElement icons}, {@link OO.ui.IndicatorElement indicators}, an optional
11558 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
11559 * which modifies incoming values rather than validating them.
11560 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
11563 * // Example of a text input widget
11564 * var textInput = new OO.ui.TextInputWidget( {
11565 * value: 'Text input'
11567 * $( 'body' ).append( textInput.$element );
11569 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11572 * @extends OO.ui.InputWidget
11573 * @mixins OO.ui.IconElement
11574 * @mixins OO.ui.IndicatorElement
11575 * @mixins OO.ui.PendingElement
11576 * @mixins OO.ui.LabelElement
11579 * @param {Object} [config] Configuration options
11580 * @cfg {string} [type='text'] The value of the HTML `type` attribute
11581 * @cfg {string} [placeholder] Placeholder text
11582 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
11583 * instruct the browser to focus this widget.
11584 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
11585 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
11586 * @cfg {boolean} [multiline=false] Allow multiple lines of text
11587 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
11588 * Use the #maxRows config to specify a maximum number of displayed rows.
11589 * @cfg {boolean} [maxRows=10] Maximum number of rows to display when #autosize is set to true.
11590 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
11591 * the value or placeholder text: `'before'` or `'after'`
11592 * @cfg {boolean} [required=false] Mark the field as required
11593 * @cfg {RegExp|string} [validate] Validation pattern, either a regular expression or the
11594 * symbolic name of a pattern defined by the class: 'non-empty' (the value cannot be an empty string)
11595 * or 'integer' (the value must contain only numbers).
11597 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
11598 // Configuration initialization
11599 config
= $.extend( {
11601 labelPosition
: 'after',
11605 // Parent constructor
11606 OO
.ui
.TextInputWidget
.super.call( this, config
);
11608 // Mixin constructors
11609 OO
.ui
.IconElement
.call( this, config
);
11610 OO
.ui
.IndicatorElement
.call( this, config
);
11611 OO
.ui
.PendingElement
.call( this, config
);
11612 OO
.ui
.LabelElement
.call( this, config
);
11615 this.readOnly
= false;
11616 this.multiline
= !!config
.multiline
;
11617 this.autosize
= !!config
.autosize
;
11618 this.maxRows
= config
.maxRows
;
11619 this.validate
= null;
11621 // Clone for resizing
11622 if ( this.autosize
) {
11623 this.$clone
= this.$input
11625 .insertAfter( this.$input
)
11626 .attr( 'aria-hidden', 'true' )
11627 .addClass( 'oo-ui-element-hidden' );
11630 this.setValidation( config
.validate
);
11631 this.setLabelPosition( config
.labelPosition
);
11635 keypress
: this.onKeyPress
.bind( this ),
11636 blur
: this.setValidityFlag
.bind( this )
11639 focus
: this.onElementAttach
.bind( this )
11641 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
11642 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
11643 this.on( 'labelChange', this.updatePosition
.bind( this ) );
11647 .addClass( 'oo-ui-textInputWidget' )
11648 .append( this.$icon
, this.$indicator
);
11649 this.setReadOnly( !!config
.readOnly
);
11650 if ( config
.placeholder
) {
11651 this.$input
.attr( 'placeholder', config
.placeholder
);
11653 if ( config
.maxLength
!== undefined ) {
11654 this.$input
.attr( 'maxlength', config
.maxLength
);
11656 if ( config
.autofocus
) {
11657 this.$input
.attr( 'autofocus', 'autofocus' );
11659 if ( config
.required
) {
11660 this.$input
.attr( 'required', 'true' );
11662 if ( this.label
|| config
.autosize
) {
11663 this.installParentChangeDetector();
11669 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
11670 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.IconElement
);
11671 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.IndicatorElement
);
11672 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.PendingElement
);
11673 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.LabelElement
);
11675 /* Static properties */
11677 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
11685 * An `enter` event is emitted when the user presses 'enter' inside the text box.
11687 * Not emitted if the input is multiline.
11695 * Handle icon mouse down events.
11698 * @param {jQuery.Event} e Mouse down event
11701 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
11702 if ( e
.which
=== 1 ) {
11703 this.$input
[ 0 ].focus();
11709 * Handle indicator mouse down events.
11712 * @param {jQuery.Event} e Mouse down event
11715 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
11716 if ( e
.which
=== 1 ) {
11717 this.$input
[ 0 ].focus();
11723 * Handle key press events.
11726 * @param {jQuery.Event} e Key press event
11727 * @fires enter If enter key is pressed and input is not multiline
11729 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
11730 if ( e
.which
=== OO
.ui
.Keys
.ENTER
&& !this.multiline
) {
11731 this.emit( 'enter', e
);
11736 * Handle element attach events.
11739 * @param {jQuery.Event} e Element attach event
11741 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
11742 // Any previously calculated size is now probably invalid if we reattached elsewhere
11743 this.valCache
= null;
11745 this.positionLabel();
11751 OO
.ui
.TextInputWidget
.prototype.onEdit = function () {
11755 return OO
.ui
.TextInputWidget
.super.prototype.onEdit
.call( this );
11761 OO
.ui
.TextInputWidget
.prototype.setValue = function ( value
) {
11763 OO
.ui
.TextInputWidget
.super.prototype.setValue
.call( this, value
);
11765 this.setValidityFlag();
11771 * Check if the input is {@link #readOnly read-only}.
11773 * @return {boolean}
11775 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
11776 return this.readOnly
;
11780 * Set the {@link #readOnly read-only} state of the input.
11782 * @param {boolean} state Make input read-only
11785 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
11786 this.readOnly
= !!state
;
11787 this.$input
.prop( 'readOnly', this.readOnly
);
11792 * Support function for making #onElementAttach work across browsers.
11794 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
11795 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
11797 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
11798 * first time that the element gets attached to the documented.
11800 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
11801 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
11802 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
11805 if ( MutationObserver
) {
11806 // The new way. If only it wasn't so ugly.
11808 if ( this.$element
.closest( 'html' ).length
) {
11809 // Widget is attached already, do nothing. This breaks the functionality of this function when
11810 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
11811 // would require observation of the whole document, which would hurt performance of other,
11812 // more important code.
11816 // Find topmost node in the tree
11817 topmostNode
= this.$element
[0];
11818 while ( topmostNode
.parentNode
) {
11819 topmostNode
= topmostNode
.parentNode
;
11822 // We have no way to detect the $element being attached somewhere without observing the entire
11823 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
11824 // parent node of $element, and instead detect when $element is removed from it (and thus
11825 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
11826 // doesn't get attached, we end up back here and create the parent.
11828 mutationObserver
= new MutationObserver( function ( mutations
) {
11829 var i
, j
, removedNodes
;
11830 for ( i
= 0; i
< mutations
.length
; i
++ ) {
11831 removedNodes
= mutations
[ i
].removedNodes
;
11832 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
11833 if ( removedNodes
[ j
] === topmostNode
) {
11834 setTimeout( onRemove
, 0 );
11841 onRemove = function () {
11842 // If the node was attached somewhere else, report it
11843 if ( widget
.$element
.closest( 'html' ).length
) {
11844 widget
.onElementAttach();
11846 mutationObserver
.disconnect();
11847 widget
.installParentChangeDetector();
11850 // Create a fake parent and observe it
11851 fakeParentNode
= $( '<div>' ).append( this.$element
)[0];
11852 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
11854 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
11855 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
11856 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
11861 * Automatically adjust the size of the text input.
11863 * This only affects #multiline inputs that are {@link #autosize autosized}.
11867 OO
.ui
.TextInputWidget
.prototype.adjustSize = function () {
11868 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
, idealHeight
;
11870 if ( this.multiline
&& this.autosize
&& this.$input
.val() !== this.valCache
) {
11872 .val( this.$input
.val() )
11873 .attr( 'rows', '' )
11874 // Set inline height property to 0 to measure scroll height
11875 .css( 'height', 0 );
11877 this.$clone
.removeClass( 'oo-ui-element-hidden' );
11879 this.valCache
= this.$input
.val();
11881 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
11883 // Remove inline height property to measure natural heights
11884 this.$clone
.css( 'height', '' );
11885 innerHeight
= this.$clone
.innerHeight();
11886 outerHeight
= this.$clone
.outerHeight();
11888 // Measure max rows height
11890 .attr( 'rows', this.maxRows
)
11891 .css( 'height', 'auto' )
11893 maxInnerHeight
= this.$clone
.innerHeight();
11895 // Difference between reported innerHeight and scrollHeight with no scrollbars present
11896 // Equals 1 on Blink-based browsers and 0 everywhere else
11897 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
11898 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
11900 this.$clone
.addClass( 'oo-ui-element-hidden' );
11902 // Only apply inline height when expansion beyond natural height is needed
11903 if ( idealHeight
> innerHeight
) {
11904 // Use the difference between the inner and outer height as a buffer
11905 this.$input
.css( 'height', idealHeight
+ ( outerHeight
- innerHeight
) );
11907 this.$input
.css( 'height', '' );
11917 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
11918 return config
.multiline
? $( '<textarea>' ) : $( '<input type="' + config
.type
+ '" />' );
11922 * Check if the input supports multiple lines.
11924 * @return {boolean}
11926 OO
.ui
.TextInputWidget
.prototype.isMultiline = function () {
11927 return !!this.multiline
;
11931 * Check if the input automatically adjusts its size.
11933 * @return {boolean}
11935 OO
.ui
.TextInputWidget
.prototype.isAutosizing = function () {
11936 return !!this.autosize
;
11940 * Select the entire text of the input.
11944 OO
.ui
.TextInputWidget
.prototype.select = function () {
11945 this.$input
.select();
11950 * Set the validation pattern.
11952 * The validation pattern is either a regular expression or the symbolic name of a pattern
11953 * defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
11954 * value must contain only numbers).
11956 * @param {RegExp|string|null} validate Regular expression or the symbolic name of a
11957 * pattern (either ‘integer’ or ‘non-empty’) defined by the class.
11959 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
11960 if ( validate
instanceof RegExp
) {
11961 this.validate
= validate
;
11963 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
11968 * Sets the 'invalid' flag appropriately.
11970 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function () {
11972 this.isValid().done( function ( valid
) {
11973 widget
.setFlags( { invalid
: !valid
} );
11978 * Check if a value is valid.
11980 * This method returns a promise that resolves with a boolean `true` if the current value is
11981 * considered valid according to the supplied {@link #validate validation pattern}.
11983 * @return {jQuery.Deferred} A promise that resolves to a boolean `true` if the value is valid.
11985 OO
.ui
.TextInputWidget
.prototype.isValid = function () {
11986 return $.Deferred().resolve( !!this.getValue().match( this.validate
) ).promise();
11990 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
11992 * @param {string} labelPosition Label position, 'before' or 'after'
11995 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
11996 this.labelPosition
= labelPosition
;
11997 this.updatePosition();
12002 * Deprecated alias of #setLabelPosition
12004 * @deprecated Use setLabelPosition instead.
12006 OO
.ui
.TextInputWidget
.prototype.setPosition
=
12007 OO
.ui
.TextInputWidget
.prototype.setLabelPosition
;
12010 * Update the position of the inline label.
12012 * This method is called by #setLabelPosition, and can also be called on its own if
12013 * something causes the label to be mispositioned.
12018 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
12019 var after
= this.labelPosition
=== 'after';
12022 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
12023 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
12025 if ( this.label
) {
12026 this.positionLabel();
12033 * Position the label by setting the correct padding on the input.
12038 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
12039 // Clear old values
12041 // Clear old values if present
12043 'padding-right': '',
12047 if ( this.label
) {
12048 this.$element
.append( this.$label
);
12050 this.$label
.detach();
12054 var after
= this.labelPosition
=== 'after',
12055 rtl
= this.$element
.css( 'direction' ) === 'rtl',
12056 property
= after
=== rtl
? 'padding-left' : 'padding-right';
12058 this.$input
.css( property
, this.$label
.outerWidth( true ) );
12064 * ComboBoxWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
12065 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
12066 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
12068 * - by typing a value in the text input field. If the value exactly matches the value of a menu
12069 * option, that option will appear to be selected.
12070 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
12073 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
12076 * // Example: A ComboBoxWidget.
12077 * var comboBox = new OO.ui.ComboBoxWidget( {
12078 * label: 'ComboBoxWidget',
12079 * input: { value: 'Option One' },
12082 * new OO.ui.MenuOptionWidget( {
12083 * data: 'Option 1',
12084 * label: 'Option One'
12086 * new OO.ui.MenuOptionWidget( {
12087 * data: 'Option 2',
12088 * label: 'Option Two'
12090 * new OO.ui.MenuOptionWidget( {
12091 * data: 'Option 3',
12092 * label: 'Option Three'
12094 * new OO.ui.MenuOptionWidget( {
12095 * data: 'Option 4',
12096 * label: 'Option Four'
12098 * new OO.ui.MenuOptionWidget( {
12099 * data: 'Option 5',
12100 * label: 'Option Five'
12105 * $( 'body' ).append( comboBox.$element );
12107 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
12110 * @extends OO.ui.Widget
12111 * @mixins OO.ui.TabIndexedElement
12114 * @param {Object} [config] Configuration options
12115 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
12116 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
12117 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
12118 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
12119 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
12121 OO
.ui
.ComboBoxWidget
= function OoUiComboBoxWidget( config
) {
12122 // Configuration initialization
12123 config
= config
|| {};
12125 // Parent constructor
12126 OO
.ui
.ComboBoxWidget
.super.call( this, config
);
12128 // Properties (must be set before TabIndexedElement constructor call)
12129 this.$indicator
= this.$( '<span>' );
12131 // Mixin constructors
12132 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$indicator
} ) );
12135 this.$overlay
= config
.$overlay
|| this.$element
;
12136 this.input
= new OO
.ui
.TextInputWidget( $.extend(
12139 $indicator
: this.$indicator
,
12140 disabled
: this.isDisabled()
12144 this.input
.$input
.eq( 0 ).attr( {
12146 'aria-autocomplete': 'list'
12148 this.menu
= new OO
.ui
.TextInputMenuSelectWidget( this.input
, $.extend(
12152 disabled
: this.isDisabled()
12158 this.$indicator
.on( {
12159 click
: this.onClick
.bind( this ),
12160 keypress
: this.onKeyPress
.bind( this )
12162 this.input
.connect( this, {
12163 change
: 'onInputChange',
12164 enter
: 'onInputEnter'
12166 this.menu
.connect( this, {
12167 choose
: 'onMenuChoose',
12168 add
: 'onMenuItemsChange',
12169 remove
: 'onMenuItemsChange'
12173 this.$element
.addClass( 'oo-ui-comboBoxWidget' ).append( this.input
.$element
);
12174 this.$overlay
.append( this.menu
.$element
);
12175 this.onMenuItemsChange();
12180 OO
.inheritClass( OO
.ui
.ComboBoxWidget
, OO
.ui
.Widget
);
12181 OO
.mixinClass( OO
.ui
.ComboBoxWidget
, OO
.ui
.TabIndexedElement
);
12186 * Get the combobox's menu.
12187 * @return {OO.ui.TextInputMenuSelectWidget} Menu widget
12189 OO
.ui
.ComboBoxWidget
.prototype.getMenu = function () {
12194 * Handle input change events.
12197 * @param {string} value New value
12199 OO
.ui
.ComboBoxWidget
.prototype.onInputChange = function ( value
) {
12200 var match
= this.menu
.getItemFromData( value
);
12202 this.menu
.selectItem( match
);
12203 if ( this.menu
.getHighlightedItem() ) {
12204 this.menu
.highlightItem( match
);
12207 if ( !this.isDisabled() ) {
12208 this.menu
.toggle( true );
12213 * Handle mouse click events.
12217 * @param {jQuery.Event} e Mouse click event
12219 OO
.ui
.ComboBoxWidget
.prototype.onClick = function ( e
) {
12220 if ( !this.isDisabled() && e
.which
=== 1 ) {
12221 this.menu
.toggle();
12222 this.input
.$input
[ 0 ].focus();
12228 * Handle key press events.
12232 * @param {jQuery.Event} e Key press event
12234 OO
.ui
.ComboBoxWidget
.prototype.onKeyPress = function ( e
) {
12235 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
12236 this.menu
.toggle();
12237 this.input
.$input
[ 0 ].focus();
12243 * Handle input enter events.
12247 OO
.ui
.ComboBoxWidget
.prototype.onInputEnter = function () {
12248 if ( !this.isDisabled() ) {
12249 this.menu
.toggle( false );
12254 * Handle menu choose events.
12257 * @param {OO.ui.OptionWidget} item Chosen item
12259 OO
.ui
.ComboBoxWidget
.prototype.onMenuChoose = function ( item
) {
12261 this.input
.setValue( item
.getData() );
12266 * Handle menu item change events.
12270 OO
.ui
.ComboBoxWidget
.prototype.onMenuItemsChange = function () {
12271 var match
= this.menu
.getItemFromData( this.input
.getValue() );
12272 this.menu
.selectItem( match
);
12273 if ( this.menu
.getHighlightedItem() ) {
12274 this.menu
.highlightItem( match
);
12276 this.$element
.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu
.isEmpty() );
12282 OO
.ui
.ComboBoxWidget
.prototype.setDisabled = function ( disabled
) {
12284 OO
.ui
.ComboBoxWidget
.super.prototype.setDisabled
.call( this, disabled
);
12286 if ( this.input
) {
12287 this.input
.setDisabled( this.isDisabled() );
12290 this.menu
.setDisabled( this.isDisabled() );
12297 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
12298 * be configured with a `label` option that is set to a string, a label node, or a function:
12300 * - String: a plaintext string
12301 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
12302 * label that includes a link or special styling, such as a gray color or additional graphical elements.
12303 * - Function: a function that will produce a string in the future. Functions are used
12304 * in cases where the value of the label is not currently defined.
12306 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
12307 * will come into focus when the label is clicked.
12310 * // Examples of LabelWidgets
12311 * var label1 = new OO.ui.LabelWidget( {
12312 * label: 'plaintext label'
12314 * var label2 = new OO.ui.LabelWidget( {
12315 * label: $( '<a href="default.html">jQuery label</a>' )
12317 * // Create a fieldset layout with fields for each example
12318 * var fieldset = new OO.ui.FieldsetLayout();
12319 * fieldset.addItems( [
12320 * new OO.ui.FieldLayout( label1 ),
12321 * new OO.ui.FieldLayout( label2 )
12323 * $( 'body' ).append( fieldset.$element );
12327 * @extends OO.ui.Widget
12328 * @mixins OO.ui.LabelElement
12331 * @param {Object} [config] Configuration options
12332 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
12333 * Clicking the label will focus the specified input field.
12335 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
12336 // Configuration initialization
12337 config
= config
|| {};
12339 // Parent constructor
12340 OO
.ui
.LabelWidget
.super.call( this, config
);
12342 // Mixin constructors
12343 OO
.ui
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
12344 OO
.ui
.TitledElement
.call( this, config
);
12347 this.input
= config
.input
;
12350 if ( this.input
instanceof OO
.ui
.InputWidget
) {
12351 this.$element
.on( 'click', this.onClick
.bind( this ) );
12355 this.$element
.addClass( 'oo-ui-labelWidget' );
12360 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
12361 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.LabelElement
);
12362 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.TitledElement
);
12364 /* Static Properties */
12366 OO
.ui
.LabelWidget
.static.tagName
= 'span';
12371 * Handles label mouse click events.
12374 * @param {jQuery.Event} e Mouse click event
12376 OO
.ui
.LabelWidget
.prototype.onClick = function () {
12377 this.input
.simulateLabelClick();
12382 * OptionWidgets are special elements that can be selected and configured with data. The
12383 * data is often unique for each option, but it does not have to be. OptionWidgets are used
12384 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
12385 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
12387 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
12390 * @extends OO.ui.Widget
12391 * @mixins OO.ui.LabelElement
12392 * @mixins OO.ui.FlaggedElement
12395 * @param {Object} [config] Configuration options
12397 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
12398 // Configuration initialization
12399 config
= config
|| {};
12401 // Parent constructor
12402 OO
.ui
.OptionWidget
.super.call( this, config
);
12404 // Mixin constructors
12405 OO
.ui
.ItemWidget
.call( this );
12406 OO
.ui
.LabelElement
.call( this, config
);
12407 OO
.ui
.FlaggedElement
.call( this, config
);
12410 this.selected
= false;
12411 this.highlighted
= false;
12412 this.pressed
= false;
12416 .data( 'oo-ui-optionWidget', this )
12417 .attr( 'role', 'option' )
12418 .addClass( 'oo-ui-optionWidget' )
12419 .append( this.$label
);
12424 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
12425 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.ItemWidget
);
12426 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.LabelElement
);
12427 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.FlaggedElement
);
12429 /* Static Properties */
12431 OO
.ui
.OptionWidget
.static.selectable
= true;
12433 OO
.ui
.OptionWidget
.static.highlightable
= true;
12435 OO
.ui
.OptionWidget
.static.pressable
= true;
12437 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
12442 * Check if the option can be selected.
12444 * @return {boolean} Item is selectable
12446 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
12447 return this.constructor.static.selectable
&& !this.isDisabled();
12451 * Check if the option can be highlighted. A highlight indicates that the option
12452 * may be selected when a user presses enter or clicks. Disabled items cannot
12455 * @return {boolean} Item is highlightable
12457 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
12458 return this.constructor.static.highlightable
&& !this.isDisabled();
12462 * Check if the option can be pressed. The pressed state occurs when a user mouses
12463 * down on an item, but has not yet let go of the mouse.
12465 * @return {boolean} Item is pressable
12467 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
12468 return this.constructor.static.pressable
&& !this.isDisabled();
12472 * Check if the option is selected.
12474 * @return {boolean} Item is selected
12476 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
12477 return this.selected
;
12481 * Check if the option is highlighted. A highlight indicates that the
12482 * item may be selected when a user presses enter or clicks.
12484 * @return {boolean} Item is highlighted
12486 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
12487 return this.highlighted
;
12491 * Check if the option is pressed. The pressed state occurs when a user mouses
12492 * down on an item, but has not yet let go of the mouse. The item may appear
12493 * selected, but it will not be selected until the user releases the mouse.
12495 * @return {boolean} Item is pressed
12497 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
12498 return this.pressed
;
12502 * Set the option’s selected state. In general, all modifications to the selection
12503 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
12504 * method instead of this method.
12506 * @param {boolean} [state=false] Select option
12509 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
12510 if ( this.constructor.static.selectable
) {
12511 this.selected
= !!state
;
12513 .toggleClass( 'oo-ui-optionWidget-selected', state
)
12514 .attr( 'aria-selected', state
.toString() );
12515 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
12516 this.scrollElementIntoView();
12518 this.updateThemeClasses();
12524 * Set the option’s highlighted state. In general, all programmatic
12525 * modifications to the highlight should be handled by the
12526 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
12527 * method instead of this method.
12529 * @param {boolean} [state=false] Highlight option
12532 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
12533 if ( this.constructor.static.highlightable
) {
12534 this.highlighted
= !!state
;
12535 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
12536 this.updateThemeClasses();
12542 * Set the option’s pressed state. In general, all
12543 * programmatic modifications to the pressed state should be handled by the
12544 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
12545 * method instead of this method.
12547 * @param {boolean} [state=false] Press option
12550 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
12551 if ( this.constructor.static.pressable
) {
12552 this.pressed
= !!state
;
12553 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
12554 this.updateThemeClasses();
12560 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
12561 * with an {@link OO.ui.IconElement icon} and/or {@link OO.ui.IndicatorElement indicator}.
12562 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
12563 * options. For more information about options and selects, please see the
12564 * [OOjs UI documentation on MediaWiki][1].
12567 * // Decorated options in a select widget
12568 * var select = new OO.ui.SelectWidget( {
12570 * new OO.ui.DecoratedOptionWidget( {
12572 * label: 'Option with icon',
12575 * new OO.ui.DecoratedOptionWidget( {
12577 * label: 'Option with indicator',
12578 * indicator: 'next'
12582 * $( 'body' ).append( select.$element );
12584 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
12587 * @extends OO.ui.OptionWidget
12588 * @mixins OO.ui.IconElement
12589 * @mixins OO.ui.IndicatorElement
12592 * @param {Object} [config] Configuration options
12594 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
12595 // Parent constructor
12596 OO
.ui
.DecoratedOptionWidget
.super.call( this, config
);
12598 // Mixin constructors
12599 OO
.ui
.IconElement
.call( this, config
);
12600 OO
.ui
.IndicatorElement
.call( this, config
);
12604 .addClass( 'oo-ui-decoratedOptionWidget' )
12605 .prepend( this.$icon
)
12606 .append( this.$indicator
);
12611 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
12612 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.IconElement
);
12613 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.IndicatorElement
);
12616 * ButtonOptionWidget is a special type of {@link OO.ui.ButtonElement button element} that
12617 * can be selected and configured with data. The class is
12618 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
12619 * [OOjs UI documentation on MediaWiki] [1] for more information.
12621 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
12624 * @extends OO.ui.DecoratedOptionWidget
12625 * @mixins OO.ui.ButtonElement
12626 * @mixins OO.ui.TabIndexedElement
12629 * @param {Object} [config] Configuration options
12631 OO
.ui
.ButtonOptionWidget
= function OoUiButtonOptionWidget( config
) {
12632 // Configuration initialization
12633 config
= $.extend( { tabIndex
: -1 }, config
);
12635 // Parent constructor
12636 OO
.ui
.ButtonOptionWidget
.super.call( this, config
);
12638 // Mixin constructors
12639 OO
.ui
.ButtonElement
.call( this, config
);
12640 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
12643 this.$element
.addClass( 'oo-ui-buttonOptionWidget' );
12644 this.$button
.append( this.$element
.contents() );
12645 this.$element
.append( this.$button
);
12650 OO
.inheritClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
12651 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.ButtonElement
);
12652 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.TabIndexedElement
);
12654 /* Static Properties */
12656 // Allow button mouse down events to pass through so they can be handled by the parent select widget
12657 OO
.ui
.ButtonOptionWidget
.static.cancelButtonMouseDownEvents
= false;
12659 OO
.ui
.ButtonOptionWidget
.static.highlightable
= false;
12666 OO
.ui
.ButtonOptionWidget
.prototype.setSelected = function ( state
) {
12667 OO
.ui
.ButtonOptionWidget
.super.prototype.setSelected
.call( this, state
);
12669 if ( this.constructor.static.selectable
) {
12670 this.setActive( state
);
12677 * RadioOptionWidget is an option widget that looks like a radio button.
12678 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
12679 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
12681 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
12684 * @extends OO.ui.OptionWidget
12687 * @param {Object} [config] Configuration options
12689 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
12690 // Configuration initialization
12691 config
= config
|| {};
12693 // Properties (must be done before parent constructor which calls #setDisabled)
12694 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
12696 // Parent constructor
12697 OO
.ui
.RadioOptionWidget
.super.call( this, config
);
12701 .addClass( 'oo-ui-radioOptionWidget' )
12702 .prepend( this.radio
.$element
);
12707 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
12709 /* Static Properties */
12711 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
12713 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
12715 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
12717 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
12724 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
12725 OO
.ui
.RadioOptionWidget
.super.prototype.setSelected
.call( this, state
);
12727 this.radio
.setSelected( state
);
12735 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
12736 OO
.ui
.RadioOptionWidget
.super.prototype.setDisabled
.call( this, disabled
);
12738 this.radio
.setDisabled( this.isDisabled() );
12744 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
12745 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
12746 * the [OOjs UI documentation on MediaWiki] [1] for more information.
12748 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
12751 * @extends OO.ui.DecoratedOptionWidget
12754 * @param {Object} [config] Configuration options
12756 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
12757 // Configuration initialization
12758 config
= $.extend( { icon
: 'check' }, config
);
12760 // Parent constructor
12761 OO
.ui
.MenuOptionWidget
.super.call( this, config
);
12765 .attr( 'role', 'menuitem' )
12766 .addClass( 'oo-ui-menuOptionWidget' );
12771 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
12773 /* Static Properties */
12775 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
12778 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
12779 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
12782 * var myDropdown = new OO.ui.DropdownWidget( {
12785 * new OO.ui.MenuSectionOptionWidget( {
12788 * new OO.ui.MenuOptionWidget( {
12790 * label: 'Welsh Corgi'
12792 * new OO.ui.MenuOptionWidget( {
12794 * label: 'Standard Poodle'
12796 * new OO.ui.MenuSectionOptionWidget( {
12799 * new OO.ui.MenuOptionWidget( {
12806 * $( 'body' ).append( myDropdown.$element );
12810 * @extends OO.ui.DecoratedOptionWidget
12813 * @param {Object} [config] Configuration options
12815 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
12816 // Parent constructor
12817 OO
.ui
.MenuSectionOptionWidget
.super.call( this, config
);
12820 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' );
12825 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
12827 /* Static Properties */
12829 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
12831 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
12834 * Items for an OO.ui.OutlineSelectWidget.
12837 * @extends OO.ui.DecoratedOptionWidget
12840 * @param {Object} [config] Configuration options
12841 * @cfg {number} [level] Indentation level
12842 * @cfg {boolean} [movable] Allow modification from outline controls
12844 OO
.ui
.OutlineOptionWidget
= function OoUiOutlineOptionWidget( config
) {
12845 // Configuration initialization
12846 config
= config
|| {};
12848 // Parent constructor
12849 OO
.ui
.OutlineOptionWidget
.super.call( this, config
);
12853 this.movable
= !!config
.movable
;
12854 this.removable
= !!config
.removable
;
12857 this.$element
.addClass( 'oo-ui-outlineOptionWidget' );
12858 this.setLevel( config
.level
);
12863 OO
.inheritClass( OO
.ui
.OutlineOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
12865 /* Static Properties */
12867 OO
.ui
.OutlineOptionWidget
.static.highlightable
= false;
12869 OO
.ui
.OutlineOptionWidget
.static.scrollIntoViewOnSelect
= true;
12871 OO
.ui
.OutlineOptionWidget
.static.levelClass
= 'oo-ui-outlineOptionWidget-level-';
12873 OO
.ui
.OutlineOptionWidget
.static.levels
= 3;
12878 * Check if item is movable.
12880 * Movability is used by outline controls.
12882 * @return {boolean} Item is movable
12884 OO
.ui
.OutlineOptionWidget
.prototype.isMovable = function () {
12885 return this.movable
;
12889 * Check if item is removable.
12891 * Removability is used by outline controls.
12893 * @return {boolean} Item is removable
12895 OO
.ui
.OutlineOptionWidget
.prototype.isRemovable = function () {
12896 return this.removable
;
12900 * Get indentation level.
12902 * @return {number} Indentation level
12904 OO
.ui
.OutlineOptionWidget
.prototype.getLevel = function () {
12911 * Movability is used by outline controls.
12913 * @param {boolean} movable Item is movable
12916 OO
.ui
.OutlineOptionWidget
.prototype.setMovable = function ( movable
) {
12917 this.movable
= !!movable
;
12918 this.updateThemeClasses();
12923 * Set removability.
12925 * Removability is used by outline controls.
12927 * @param {boolean} movable Item is removable
12930 OO
.ui
.OutlineOptionWidget
.prototype.setRemovable = function ( removable
) {
12931 this.removable
= !!removable
;
12932 this.updateThemeClasses();
12937 * Set indentation level.
12939 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
12942 OO
.ui
.OutlineOptionWidget
.prototype.setLevel = function ( level
) {
12943 var levels
= this.constructor.static.levels
,
12944 levelClass
= this.constructor.static.levelClass
,
12947 this.level
= level
? Math
.max( 0, Math
.min( levels
- 1, level
) ) : 0;
12949 if ( this.level
=== i
) {
12950 this.$element
.addClass( levelClass
+ i
);
12952 this.$element
.removeClass( levelClass
+ i
);
12955 this.updateThemeClasses();
12961 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
12962 * By default, each popup has an anchor that points toward its origin.
12963 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
12966 * // A popup widget.
12967 * var popup = new OO.ui.PopupWidget( {
12968 * $content: $( '<p>Hi there!</p>' ),
12973 * $( 'body' ).append( popup.$element );
12974 * // To display the popup, toggle the visibility to 'true'.
12975 * popup.toggle( true );
12977 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
12980 * @extends OO.ui.Widget
12981 * @mixins OO.ui.LabelElement
12984 * @param {Object} [config] Configuration options
12985 * @cfg {number} [width=320] Width of popup in pixels
12986 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
12987 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
12988 * @cfg {string} [align='center'] Alignment of the popup: `center`, `left`, or `right`.
12989 * If the popup is right-aligned, the right edge of the popup is aligned to the anchor.
12990 * For left-aligned popups, the left edge is aligned to the anchor.
12991 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
12992 * See the [OOjs UI docs on MediaWiki][3] for an example.
12993 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
12994 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
12995 * @cfg {jQuery} [$content] Content to append to the popup's body
12996 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
12997 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
12998 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
13000 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
13001 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
13003 * @cfg {boolean} [padded] Add padding to the popup's body
13005 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
13006 // Configuration initialization
13007 config
= config
|| {};
13009 // Parent constructor
13010 OO
.ui
.PopupWidget
.super.call( this, config
);
13012 // Properties (must be set before ClippableElement constructor call)
13013 this.$body
= $( '<div>' );
13015 // Mixin constructors
13016 OO
.ui
.LabelElement
.call( this, config
);
13017 OO
.ui
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$body
} ) );
13020 this.$popup
= $( '<div>' );
13021 this.$head
= $( '<div>' );
13022 this.$anchor
= $( '<div>' );
13023 // If undefined, will be computed lazily in updateDimensions()
13024 this.$container
= config
.$container
;
13025 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
13026 this.autoClose
= !!config
.autoClose
;
13027 this.$autoCloseIgnore
= config
.$autoCloseIgnore
;
13028 this.transitionTimeout
= null;
13029 this.anchor
= null;
13030 this.width
= config
.width
!== undefined ? config
.width
: 320;
13031 this.height
= config
.height
!== undefined ? config
.height
: null;
13032 this.align
= config
.align
|| 'center';
13033 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
13034 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
13035 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
13038 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
13041 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
13042 this.$body
.addClass( 'oo-ui-popupWidget-body' );
13043 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
13045 .addClass( 'oo-ui-popupWidget-head' )
13046 .append( this.$label
, this.closeButton
.$element
);
13047 if ( !config
.head
) {
13048 this.$head
.addClass( 'oo-ui-element-hidden' );
13051 .addClass( 'oo-ui-popupWidget-popup' )
13052 .append( this.$head
, this.$body
);
13054 .addClass( 'oo-ui-popupWidget' )
13055 .append( this.$popup
, this.$anchor
);
13056 // Move content, which was added to #$element by OO.ui.Widget, to the body
13057 if ( config
.$content
instanceof jQuery
) {
13058 this.$body
.append( config
.$content
);
13060 if ( config
.padded
) {
13061 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
13064 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
13065 // that reference properties not initialized at that time of parent class construction
13066 // TODO: Find a better way to handle post-constructor setup
13067 this.visible
= false;
13068 this.$element
.addClass( 'oo-ui-element-hidden' );
13073 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
13074 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.LabelElement
);
13075 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.ClippableElement
);
13080 * Handles mouse down events.
13083 * @param {MouseEvent} e Mouse down event
13085 OO
.ui
.PopupWidget
.prototype.onMouseDown = function ( e
) {
13087 this.isVisible() &&
13088 !$.contains( this.$element
[ 0 ], e
.target
) &&
13089 ( !this.$autoCloseIgnore
|| !this.$autoCloseIgnore
.has( e
.target
).length
)
13091 this.toggle( false );
13096 * Bind mouse down listener.
13100 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
13101 // Capture clicks outside popup
13102 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler
, true );
13106 * Handles close button click events.
13110 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
13111 if ( this.isVisible() ) {
13112 this.toggle( false );
13117 * Unbind mouse down listener.
13121 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
13122 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler
, true );
13126 * Handles key down events.
13129 * @param {KeyboardEvent} e Key down event
13131 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
13133 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
13136 this.toggle( false );
13137 e
.preventDefault();
13138 e
.stopPropagation();
13143 * Bind key down listener.
13147 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
13148 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
13152 * Unbind key down listener.
13156 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
13157 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
13161 * Show, hide, or toggle the visibility of the anchor.
13163 * @param {boolean} [show] Show anchor, omit to toggle
13165 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
13166 show
= show
=== undefined ? !this.anchored
: !!show
;
13168 if ( this.anchored
!== show
) {
13170 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
13172 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
13174 this.anchored
= show
;
13179 * Check if the anchor is visible.
13181 * @return {boolean} Anchor is visible
13183 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
13184 return this.anchor
;
13190 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
13191 show
= show
=== undefined ? !this.isVisible() : !!show
;
13193 var change
= show
!== this.isVisible();
13196 OO
.ui
.PopupWidget
.super.prototype.toggle
.call( this, show
);
13200 if ( this.autoClose
) {
13201 this.bindMouseDownListener();
13202 this.bindKeyDownListener();
13204 this.updateDimensions();
13205 this.toggleClipping( true );
13207 this.toggleClipping( false );
13208 if ( this.autoClose
) {
13209 this.unbindMouseDownListener();
13210 this.unbindKeyDownListener();
13219 * Set the size of the popup.
13221 * Changing the size may also change the popup's position depending on the alignment.
13223 * @param {number} width Width in pixels
13224 * @param {number} height Height in pixels
13225 * @param {boolean} [transition=false] Use a smooth transition
13228 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
13229 this.width
= width
;
13230 this.height
= height
!== undefined ? height
: null;
13231 if ( this.isVisible() ) {
13232 this.updateDimensions( transition
);
13237 * Update the size and position.
13239 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
13240 * be called automatically.
13242 * @param {boolean} [transition=false] Use a smooth transition
13245 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
13246 var popupOffset
, originOffset
, containerLeft
, containerWidth
, containerRight
,
13247 popupLeft
, popupRight
, overlapLeft
, overlapRight
, anchorWidth
,
13250 if ( !this.$container
) {
13251 // Lazy-initialize $container if not specified in constructor
13252 this.$container
= $( this.getClosestScrollableElementContainer() );
13255 // Set height and width before measuring things, since it might cause our measurements
13256 // to change (e.g. due to scrollbars appearing or disappearing)
13259 height
: this.height
!== null ? this.height
: 'auto'
13262 // Compute initial popupOffset based on alignment
13263 popupOffset
= this.width
* ( { left
: 0, center
: -0.5, right
: -1 } )[ this.align
];
13265 // Figure out if this will cause the popup to go beyond the edge of the container
13266 originOffset
= this.$element
.offset().left
;
13267 containerLeft
= this.$container
.offset().left
;
13268 containerWidth
= this.$container
.innerWidth();
13269 containerRight
= containerLeft
+ containerWidth
;
13270 popupLeft
= popupOffset
- this.containerPadding
;
13271 popupRight
= popupOffset
+ this.containerPadding
+ this.width
+ this.containerPadding
;
13272 overlapLeft
= ( originOffset
+ popupLeft
) - containerLeft
;
13273 overlapRight
= containerRight
- ( originOffset
+ popupRight
);
13275 // Adjust offset to make the popup not go beyond the edge, if needed
13276 if ( overlapRight
< 0 ) {
13277 popupOffset
+= overlapRight
;
13278 } else if ( overlapLeft
< 0 ) {
13279 popupOffset
-= overlapLeft
;
13282 // Adjust offset to avoid anchor being rendered too close to the edge
13283 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
13284 // TODO: Find a measurement that works for CSS anchors and image anchors
13285 anchorWidth
= this.$anchor
[ 0 ].scrollWidth
* 2;
13286 if ( popupOffset
+ this.width
< anchorWidth
) {
13287 popupOffset
= anchorWidth
- this.width
;
13288 } else if ( -popupOffset
< anchorWidth
) {
13289 popupOffset
= -anchorWidth
;
13292 // Prevent transition from being interrupted
13293 clearTimeout( this.transitionTimeout
);
13294 if ( transition
) {
13295 // Enable transition
13296 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
13299 // Position body relative to anchor
13300 this.$popup
.css( 'margin-left', popupOffset
);
13302 if ( transition
) {
13303 // Prevent transitioning after transition is complete
13304 this.transitionTimeout
= setTimeout( function () {
13305 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
13308 // Prevent transitioning immediately
13309 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
13312 // Reevaluate clipping state since we've relocated and resized the popup
13319 * Progress bars visually display the status of an operation, such as a download,
13320 * and can be either determinate or indeterminate:
13322 * - **determinate** process bars show the percent of an operation that is complete.
13324 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
13325 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
13326 * not use percentages.
13328 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
13331 * // Examples of determinate and indeterminate progress bars.
13332 * var progressBar1 = new OO.ui.ProgressBarWidget( {
13335 * var progressBar2 = new OO.ui.ProgressBarWidget();
13337 * // Create a FieldsetLayout to layout progress bars
13338 * var fieldset = new OO.ui.FieldsetLayout;
13339 * fieldset.addItems( [
13340 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
13341 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
13343 * $( 'body' ).append( fieldset.$element );
13346 * @extends OO.ui.Widget
13349 * @param {Object} [config] Configuration options
13350 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
13351 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
13352 * By default, the progress bar is indeterminate.
13354 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
13355 // Configuration initialization
13356 config
= config
|| {};
13358 // Parent constructor
13359 OO
.ui
.ProgressBarWidget
.super.call( this, config
);
13362 this.$bar
= $( '<div>' );
13363 this.progress
= null;
13366 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
13367 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
13370 role
: 'progressbar',
13371 'aria-valuemin': 0,
13372 'aria-valuemax': 100
13374 .addClass( 'oo-ui-progressBarWidget' )
13375 .append( this.$bar
);
13380 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
13382 /* Static Properties */
13384 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
13389 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
13391 * @return {number|boolean} Progress percent
13393 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
13394 return this.progress
;
13398 * Set the percent of the process completed or `false` for an indeterminate process.
13400 * @param {number|boolean} progress Progress percent or `false` for indeterminate
13402 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
13403 this.progress
= progress
;
13405 if ( progress
!== false ) {
13406 this.$bar
.css( 'width', this.progress
+ '%' );
13407 this.$element
.attr( 'aria-valuenow', this.progress
);
13409 this.$bar
.css( 'width', '' );
13410 this.$element
.removeAttr( 'aria-valuenow' );
13412 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress
);
13416 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
13417 * and a {@link OO.ui.TextInputMenuSelectWidget menu} of search results, which is displayed beneath the query
13418 * field. Unlike {@link OO.ui.LookupElement lookup menus}, search result menus are always visible to the user.
13419 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
13420 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
13422 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
13423 * the [OOjs UI demos][1] for an example.
13425 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
13428 * @extends OO.ui.Widget
13431 * @param {Object} [config] Configuration options
13432 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
13433 * @cfg {string} [value] Initial query value
13435 OO
.ui
.SearchWidget
= function OoUiSearchWidget( config
) {
13436 // Configuration initialization
13437 config
= config
|| {};
13439 // Parent constructor
13440 OO
.ui
.SearchWidget
.super.call( this, config
);
13443 this.query
= new OO
.ui
.TextInputWidget( {
13445 placeholder
: config
.placeholder
,
13446 value
: config
.value
13448 this.results
= new OO
.ui
.SelectWidget();
13449 this.$query
= $( '<div>' );
13450 this.$results
= $( '<div>' );
13453 this.query
.connect( this, {
13454 change
: 'onQueryChange',
13455 enter
: 'onQueryEnter'
13457 this.results
.connect( this, {
13458 highlight
: 'onResultsHighlight',
13459 select
: 'onResultsSelect'
13461 this.query
.$input
.on( 'keydown', this.onQueryKeydown
.bind( this ) );
13465 .addClass( 'oo-ui-searchWidget-query' )
13466 .append( this.query
.$element
);
13468 .addClass( 'oo-ui-searchWidget-results' )
13469 .append( this.results
.$element
);
13471 .addClass( 'oo-ui-searchWidget' )
13472 .append( this.$results
, this.$query
);
13477 OO
.inheritClass( OO
.ui
.SearchWidget
, OO
.ui
.Widget
);
13482 * A 'highlight' event is emitted when an item is highlighted. The highlight indicates which
13483 * item will be selected. When a user mouses over a menu item, it is highlighted. If a search
13484 * string is typed into the query field instead, the first menu item that matches the query
13485 * will be highlighted.
13488 * @param {Object|null} item Item data or null if no item is highlighted
13492 * A 'select' event is emitted when an item is selected. A menu item is selected when it is clicked,
13493 * or when a user types a search query, a menu result is highlighted, and the user presses enter.
13496 * @param {Object|null} item Item data or null if no item is selected
13502 * Handle query key down events.
13505 * @param {jQuery.Event} e Key down event
13507 OO
.ui
.SearchWidget
.prototype.onQueryKeydown = function ( e
) {
13508 var highlightedItem
, nextItem
,
13509 dir
= e
.which
=== OO
.ui
.Keys
.DOWN
? 1 : ( e
.which
=== OO
.ui
.Keys
.UP
? -1 : 0 );
13512 highlightedItem
= this.results
.getHighlightedItem();
13513 if ( !highlightedItem
) {
13514 highlightedItem
= this.results
.getSelectedItem();
13516 nextItem
= this.results
.getRelativeSelectableItem( highlightedItem
, dir
);
13517 this.results
.highlightItem( nextItem
);
13518 nextItem
.scrollElementIntoView();
13523 * Handle select widget select events.
13525 * Clears existing results. Subclasses should repopulate items according to new query.
13528 * @param {string} value New value
13530 OO
.ui
.SearchWidget
.prototype.onQueryChange = function () {
13532 this.results
.clearItems();
13536 * Handle select widget enter key events.
13538 * Selects highlighted item.
13541 * @param {string} value New value
13543 OO
.ui
.SearchWidget
.prototype.onQueryEnter = function () {
13545 this.results
.selectItem( this.results
.getHighlightedItem() );
13549 * Handle select widget highlight events.
13552 * @param {OO.ui.OptionWidget} item Highlighted item
13555 OO
.ui
.SearchWidget
.prototype.onResultsHighlight = function ( item
) {
13556 this.emit( 'highlight', item
? item
.getData() : null );
13560 * Handle select widget select events.
13563 * @param {OO.ui.OptionWidget} item Selected item
13566 OO
.ui
.SearchWidget
.prototype.onResultsSelect = function ( item
) {
13567 this.emit( 'select', item
? item
.getData() : null );
13571 * Get the query input.
13573 * @return {OO.ui.TextInputWidget} Query input
13575 OO
.ui
.SearchWidget
.prototype.getQuery = function () {
13580 * Get the search results menu.
13582 * @return {OO.ui.SelectWidget} Menu of search results
13584 OO
.ui
.SearchWidget
.prototype.getResults = function () {
13585 return this.results
;
13589 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
13590 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
13591 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
13594 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
13595 * information, please see the [OOjs UI documentation on MediaWiki][1].
13598 * // Example of a select widget with three options
13599 * var select = new OO.ui.SelectWidget( {
13601 * new OO.ui.OptionWidget( {
13603 * label: 'Option One',
13605 * new OO.ui.OptionWidget( {
13607 * label: 'Option Two',
13609 * new OO.ui.OptionWidget( {
13611 * label: 'Option Three',
13615 * $( 'body' ).append( select.$element );
13617 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
13620 * @extends OO.ui.Widget
13621 * @mixins OO.ui.GroupElement
13624 * @param {Object} [config] Configuration options
13625 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
13626 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
13627 * the [OOjs UI documentation on MediaWiki] [2] for examples.
13628 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
13630 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
13631 // Configuration initialization
13632 config
= config
|| {};
13634 // Parent constructor
13635 OO
.ui
.SelectWidget
.super.call( this, config
);
13637 // Mixin constructors
13638 OO
.ui
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
13641 this.pressed
= false;
13642 this.selecting
= null;
13643 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
13644 this.onMouseMoveHandler
= this.onMouseMove
.bind( this );
13645 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
13648 this.$element
.on( {
13649 mousedown
: this.onMouseDown
.bind( this ),
13650 mouseover
: this.onMouseOver
.bind( this ),
13651 mouseleave
: this.onMouseLeave
.bind( this )
13656 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
13657 .attr( 'role', 'listbox' );
13658 if ( Array
.isArray( config
.items
) ) {
13659 this.addItems( config
.items
);
13665 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
13667 // Need to mixin base class as well
13668 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.GroupElement
);
13669 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.GroupWidget
);
13676 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
13678 * @param {OO.ui.OptionWidget|null} item Highlighted item
13684 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
13685 * pressed state of an option.
13687 * @param {OO.ui.OptionWidget|null} item Pressed item
13693 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
13695 * @param {OO.ui.OptionWidget|null} item Selected item
13700 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
13701 * @param {OO.ui.OptionWidget|null} item Chosen item
13707 * An `add` event is emitted when options are added to the select with the #addItems method.
13709 * @param {OO.ui.OptionWidget[]} items Added items
13710 * @param {number} index Index of insertion point
13716 * A `remove` event is emitted when options are removed from the select with the #clearItems
13717 * or #removeItems methods.
13719 * @param {OO.ui.OptionWidget[]} items Removed items
13725 * Handle mouse down events.
13728 * @param {jQuery.Event} e Mouse down event
13730 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
13733 if ( !this.isDisabled() && e
.which
=== 1 ) {
13734 this.togglePressed( true );
13735 item
= this.getTargetItem( e
);
13736 if ( item
&& item
.isSelectable() ) {
13737 this.pressItem( item
);
13738 this.selecting
= item
;
13739 this.getElementDocument().addEventListener(
13741 this.onMouseUpHandler
,
13744 this.getElementDocument().addEventListener(
13746 this.onMouseMoveHandler
,
13755 * Handle mouse up events.
13758 * @param {jQuery.Event} e Mouse up event
13760 OO
.ui
.SelectWidget
.prototype.onMouseUp = function ( e
) {
13763 this.togglePressed( false );
13764 if ( !this.selecting
) {
13765 item
= this.getTargetItem( e
);
13766 if ( item
&& item
.isSelectable() ) {
13767 this.selecting
= item
;
13770 if ( !this.isDisabled() && e
.which
=== 1 && this.selecting
) {
13771 this.pressItem( null );
13772 this.chooseItem( this.selecting
);
13773 this.selecting
= null;
13776 this.getElementDocument().removeEventListener(
13778 this.onMouseUpHandler
,
13781 this.getElementDocument().removeEventListener(
13783 this.onMouseMoveHandler
,
13791 * Handle mouse move events.
13794 * @param {jQuery.Event} e Mouse move event
13796 OO
.ui
.SelectWidget
.prototype.onMouseMove = function ( e
) {
13799 if ( !this.isDisabled() && this.pressed
) {
13800 item
= this.getTargetItem( e
);
13801 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
13802 this.pressItem( item
);
13803 this.selecting
= item
;
13810 * Handle mouse over events.
13813 * @param {jQuery.Event} e Mouse over event
13815 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
13818 if ( !this.isDisabled() ) {
13819 item
= this.getTargetItem( e
);
13820 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
13826 * Handle mouse leave events.
13829 * @param {jQuery.Event} e Mouse over event
13831 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
13832 if ( !this.isDisabled() ) {
13833 this.highlightItem( null );
13839 * Handle key down events.
13842 * @param {jQuery.Event} e Key down event
13844 OO
.ui
.SelectWidget
.prototype.onKeyDown = function ( e
) {
13847 currentItem
= this.getHighlightedItem() || this.getSelectedItem();
13849 if ( !this.isDisabled() && this.isVisible() ) {
13850 switch ( e
.keyCode
) {
13851 case OO
.ui
.Keys
.ENTER
:
13852 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
13853 // Was only highlighted, now let's select it. No-op if already selected.
13854 this.chooseItem( currentItem
);
13858 case OO
.ui
.Keys
.UP
:
13859 case OO
.ui
.Keys
.LEFT
:
13860 nextItem
= this.getRelativeSelectableItem( currentItem
, -1 );
13863 case OO
.ui
.Keys
.DOWN
:
13864 case OO
.ui
.Keys
.RIGHT
:
13865 nextItem
= this.getRelativeSelectableItem( currentItem
, 1 );
13868 case OO
.ui
.Keys
.ESCAPE
:
13869 case OO
.ui
.Keys
.TAB
:
13870 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
13871 currentItem
.setHighlighted( false );
13873 this.unbindKeyDownListener();
13874 // Don't prevent tabbing away / defocusing
13880 if ( nextItem
.constructor.static.highlightable
) {
13881 this.highlightItem( nextItem
);
13883 this.chooseItem( nextItem
);
13885 nextItem
.scrollElementIntoView();
13889 // Can't just return false, because e is not always a jQuery event
13890 e
.preventDefault();
13891 e
.stopPropagation();
13897 * Bind key down listener.
13901 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
13902 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler
, true );
13906 * Unbind key down listener.
13910 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
13911 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler
, true );
13915 * Get the closest item to a jQuery.Event.
13918 * @param {jQuery.Event} e
13919 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
13921 OO
.ui
.SelectWidget
.prototype.getTargetItem = function ( e
) {
13922 var $item
= $( e
.target
).closest( '.oo-ui-optionWidget' );
13923 if ( $item
.length
) {
13924 return $item
.data( 'oo-ui-optionWidget' );
13930 * Get selected item.
13932 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
13934 OO
.ui
.SelectWidget
.prototype.getSelectedItem = function () {
13937 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
13938 if ( this.items
[ i
].isSelected() ) {
13939 return this.items
[ i
];
13946 * Get highlighted item.
13948 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
13950 OO
.ui
.SelectWidget
.prototype.getHighlightedItem = function () {
13953 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
13954 if ( this.items
[ i
].isHighlighted() ) {
13955 return this.items
[ i
];
13962 * Toggle pressed state.
13964 * Press is a state that occurs when a user mouses down on an item, but
13965 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
13966 * until the user releases the mouse.
13968 * @param {boolean} pressed An option is being pressed
13970 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
13971 if ( pressed
=== undefined ) {
13972 pressed
= !this.pressed
;
13974 if ( pressed
!== this.pressed
) {
13976 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
13977 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
13978 this.pressed
= pressed
;
13983 * Highlight an option. If the `item` param is omitted, no options will be highlighted
13984 * and any existing highlight will be removed. The highlight is mutually exclusive.
13986 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
13990 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
13991 var i
, len
, highlighted
,
13994 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
13995 highlighted
= this.items
[ i
] === item
;
13996 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
13997 this.items
[ i
].setHighlighted( highlighted
);
14002 this.emit( 'highlight', item
);
14009 * Programmatically select an option by its reference. If the `item` parameter is omitted,
14010 * all options will be deselected.
14012 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
14016 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
14017 var i
, len
, selected
,
14020 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
14021 selected
= this.items
[ i
] === item
;
14022 if ( this.items
[ i
].isSelected() !== selected
) {
14023 this.items
[ i
].setSelected( selected
);
14028 this.emit( 'select', item
);
14037 * Press is a state that occurs when a user mouses down on an item, but has not
14038 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
14039 * releases the mouse.
14041 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
14045 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
14046 var i
, len
, pressed
,
14049 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
14050 pressed
= this.items
[ i
] === item
;
14051 if ( this.items
[ i
].isPressed() !== pressed
) {
14052 this.items
[ i
].setPressed( pressed
);
14057 this.emit( 'press', item
);
14066 * Note that ‘choose’ should never be modified programmatically. A user can choose
14067 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
14068 * use the #selectItem method.
14070 * This method is identical to #selectItem, but may vary in subclasses that take additional action
14071 * when users choose an item with the keyboard or mouse.
14073 * @param {OO.ui.OptionWidget} item Item to choose
14077 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
14078 this.selectItem( item
);
14079 this.emit( 'choose', item
);
14085 * Get an option by its position relative to the specified item (or to the start of the option array,
14086 * if item is `null`). The direction in which to search through the option array is specified with a
14087 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
14088 * `null` if there are no options in the array.
14090 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
14091 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
14092 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
14094 OO
.ui
.SelectWidget
.prototype.getRelativeSelectableItem = function ( item
, direction
) {
14095 var currentIndex
, nextIndex
, i
,
14096 increase
= direction
> 0 ? 1 : -1,
14097 len
= this.items
.length
;
14099 if ( item
instanceof OO
.ui
.OptionWidget
) {
14100 currentIndex
= $.inArray( item
, this.items
);
14101 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
14103 // If no item is selected and moving forward, start at the beginning.
14104 // If moving backward, start at the end.
14105 nextIndex
= direction
> 0 ? 0 : len
- 1;
14108 for ( i
= 0; i
< len
; i
++ ) {
14109 item
= this.items
[ nextIndex
];
14110 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() ) {
14113 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
14119 * Get the next selectable item or `null` if there are no selectable items.
14120 * Disabled options and menu-section markers and breaks are not selectable.
14122 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
14124 OO
.ui
.SelectWidget
.prototype.getFirstSelectableItem = function () {
14127 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
14128 item
= this.items
[ i
];
14129 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() ) {
14138 * Add an array of options to the select. Optionally, an index number can be used to
14139 * specify an insertion point.
14141 * @param {OO.ui.OptionWidget[]} items Items to add
14142 * @param {number} [index] Index to insert items after
14146 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
14148 OO
.ui
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
14150 // Always provide an index, even if it was omitted
14151 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
14157 * Remove the specified array of options from the select. Options will be detached
14158 * from the DOM, not removed, so they can be reused later. To remove all options from
14159 * the select, you may wish to use the #clearItems method instead.
14161 * @param {OO.ui.OptionWidget[]} items Items to remove
14165 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
14168 // Deselect items being removed
14169 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
14171 if ( item
.isSelected() ) {
14172 this.selectItem( null );
14177 OO
.ui
.GroupWidget
.prototype.removeItems
.call( this, items
);
14179 this.emit( 'remove', items
);
14185 * Clear all options from the select. Options will be detached from the DOM, not removed,
14186 * so that they can be reused later. To remove a subset of options from the select, use
14187 * the #removeItems method.
14192 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
14193 var items
= this.items
.slice();
14196 OO
.ui
.GroupWidget
.prototype.clearItems
.call( this );
14199 this.selectItem( null );
14201 this.emit( 'remove', items
);
14207 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
14208 * button options and is used together with
14209 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
14210 * highlighting, choosing, and selecting mutually exclusive options. Please see
14211 * the [OOjs UI documentation on MediaWiki] [1] for more information.
14214 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
14215 * var option1 = new OO.ui.ButtonOptionWidget( {
14217 * label: 'Option 1',
14218 * title: 'Button option 1'
14221 * var option2 = new OO.ui.ButtonOptionWidget( {
14223 * label: 'Option 2',
14224 * title: 'Button option 2'
14227 * var option3 = new OO.ui.ButtonOptionWidget( {
14229 * label: 'Option 3',
14230 * title: 'Button option 3'
14233 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
14234 * items: [ option1, option2, option3 ]
14236 * $( 'body' ).append( buttonSelect.$element );
14238 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14241 * @extends OO.ui.SelectWidget
14242 * @mixins OO.ui.TabIndexedElement
14245 * @param {Object} [config] Configuration options
14247 OO
.ui
.ButtonSelectWidget
= function OoUiButtonSelectWidget( config
) {
14248 // Parent constructor
14249 OO
.ui
.ButtonSelectWidget
.super.call( this, config
);
14251 // Mixin constructors
14252 OO
.ui
.TabIndexedElement
.call( this, config
);
14255 this.$element
.on( {
14256 focus
: this.bindKeyDownListener
.bind( this ),
14257 blur
: this.unbindKeyDownListener
.bind( this )
14261 this.$element
.addClass( 'oo-ui-buttonSelectWidget' );
14266 OO
.inheritClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.SelectWidget
);
14267 OO
.mixinClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.TabIndexedElement
);
14270 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
14271 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
14272 * an interface for adding, removing and selecting options.
14273 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
14276 * // A RadioSelectWidget with RadioOptions.
14277 * var option1 = new OO.ui.RadioOptionWidget( {
14279 * label: 'Selected radio option'
14282 * var option2 = new OO.ui.RadioOptionWidget( {
14284 * label: 'Unselected radio option'
14287 * var radioSelect=new OO.ui.RadioSelectWidget( {
14288 * items: [ option1, option2 ]
14291 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
14292 * radioSelect.selectItem( option1 );
14294 * $( 'body' ).append( radioSelect.$element );
14296 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14300 * @extends OO.ui.SelectWidget
14301 * @mixins OO.ui.TabIndexedElement
14304 * @param {Object} [config] Configuration options
14306 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
14307 // Parent constructor
14308 OO
.ui
.RadioSelectWidget
.super.call( this, config
);
14310 // Mixin constructors
14311 OO
.ui
.TabIndexedElement
.call( this, config
);
14314 this.$element
.on( {
14315 focus
: this.bindKeyDownListener
.bind( this ),
14316 blur
: this.unbindKeyDownListener
.bind( this )
14320 this.$element
.addClass( 'oo-ui-radioSelectWidget' );
14325 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
14326 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.TabIndexedElement
);
14329 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
14330 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
14331 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxWidget ComboBoxWidget},
14332 * and {@link OO.ui.LookupElement LookupElement} for examples of widgets that contain menus.
14333 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
14334 * and customized to be opened, closed, and displayed as needed.
14336 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
14337 * mouse outside the menu.
14339 * Menus also have support for keyboard interaction:
14341 * - Enter/Return key: choose and select a menu option
14342 * - Up-arrow key: highlight the previous menu option
14343 * - Down-arrow key: highlight the next menu option
14344 * - Esc key: hide the menu
14346 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
14347 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14350 * @extends OO.ui.SelectWidget
14351 * @mixins OO.ui.ClippableElement
14354 * @param {Object} [config] Configuration options
14355 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
14356 * the text the user types. This config is used by {@link OO.ui.ComboBoxWidget ComboBoxWidget}
14357 * and {@link OO.ui.LookupElement LookupElement}
14358 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu’s active state. If the user clicks the mouse
14359 * anywhere on the page outside of this widget, the menu is hidden.
14360 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
14362 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
14363 // Configuration initialization
14364 config
= config
|| {};
14366 // Parent constructor
14367 OO
.ui
.MenuSelectWidget
.super.call( this, config
);
14369 // Mixin constructors
14370 OO
.ui
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
14373 this.newItems
= null;
14374 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
14375 this.$input
= config
.input
? config
.input
.$input
: null;
14376 this.$widget
= config
.widget
? config
.widget
.$element
: null;
14377 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
14381 .addClass( 'oo-ui-menuSelectWidget' )
14382 .attr( 'role', 'menu' );
14384 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
14385 // that reference properties not initialized at that time of parent class construction
14386 // TODO: Find a better way to handle post-constructor setup
14387 this.visible
= false;
14388 this.$element
.addClass( 'oo-ui-element-hidden' );
14393 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
14394 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.ClippableElement
);
14399 * Handles document mouse down events.
14402 * @param {jQuery.Event} e Key down event
14404 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
14406 !OO
.ui
.contains( this.$element
[ 0 ], e
.target
, true ) &&
14407 ( !this.$widget
|| !OO
.ui
.contains( this.$widget
[ 0 ], e
.target
, true ) )
14409 this.toggle( false );
14416 OO
.ui
.MenuSelectWidget
.prototype.onKeyDown = function ( e
) {
14417 var currentItem
= this.getHighlightedItem() || this.getSelectedItem();
14419 if ( !this.isDisabled() && this.isVisible() ) {
14420 switch ( e
.keyCode
) {
14421 case OO
.ui
.Keys
.LEFT
:
14422 case OO
.ui
.Keys
.RIGHT
:
14423 // Do nothing if a text field is associated, arrow keys will be handled natively
14424 if ( !this.$input
) {
14425 OO
.ui
.MenuSelectWidget
.super.prototype.onKeyDown
.call( this, e
);
14428 case OO
.ui
.Keys
.ESCAPE
:
14429 case OO
.ui
.Keys
.TAB
:
14430 if ( currentItem
) {
14431 currentItem
.setHighlighted( false );
14433 this.toggle( false );
14434 // Don't prevent tabbing away, prevent defocusing
14435 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
14436 e
.preventDefault();
14437 e
.stopPropagation();
14441 OO
.ui
.MenuSelectWidget
.super.prototype.onKeyDown
.call( this, e
);
14450 OO
.ui
.MenuSelectWidget
.prototype.bindKeyDownListener = function () {
14451 if ( this.$input
) {
14452 this.$input
.on( 'keydown', this.onKeyDownHandler
);
14454 OO
.ui
.MenuSelectWidget
.super.prototype.bindKeyDownListener
.call( this );
14461 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyDownListener = function () {
14462 if ( this.$input
) {
14463 this.$input
.off( 'keydown', this.onKeyDownHandler
);
14465 OO
.ui
.MenuSelectWidget
.super.prototype.unbindKeyDownListener
.call( this );
14472 * When a user chooses an item, the menu is closed.
14474 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
14475 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
14476 * @param {OO.ui.OptionWidget} item Item to choose
14479 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
14480 OO
.ui
.MenuSelectWidget
.super.prototype.chooseItem
.call( this, item
);
14481 this.toggle( false );
14488 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
14492 OO
.ui
.MenuSelectWidget
.super.prototype.addItems
.call( this, items
, index
);
14495 if ( !this.newItems
) {
14496 this.newItems
= [];
14499 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
14501 if ( this.isVisible() ) {
14502 // Defer fitting label until item has been attached
14505 this.newItems
.push( item
);
14509 // Reevaluate clipping
14518 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
14520 OO
.ui
.MenuSelectWidget
.super.prototype.removeItems
.call( this, items
);
14522 // Reevaluate clipping
14531 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
14533 OO
.ui
.MenuSelectWidget
.super.prototype.clearItems
.call( this );
14535 // Reevaluate clipping
14544 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
14545 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
14548 change
= visible
!== this.isVisible();
14551 OO
.ui
.MenuSelectWidget
.super.prototype.toggle
.call( this, visible
);
14555 this.bindKeyDownListener();
14557 if ( this.newItems
&& this.newItems
.length
) {
14558 for ( i
= 0, len
= this.newItems
.length
; i
< len
; i
++ ) {
14559 this.newItems
[ i
].fitLabel();
14561 this.newItems
= null;
14563 this.toggleClipping( true );
14566 if ( this.autoHide
) {
14567 this.getElementDocument().addEventListener(
14568 'mousedown', this.onDocumentMouseDownHandler
, true
14572 this.unbindKeyDownListener();
14573 this.getElementDocument().removeEventListener(
14574 'mousedown', this.onDocumentMouseDownHandler
, true
14576 this.toggleClipping( false );
14584 * TextInputMenuSelectWidget is a menu that is specially designed to be positioned beneath
14585 * a {@link OO.ui.TextInputWidget text input} field. The menu's position is automatically
14586 * calculated and maintained when the menu is toggled or the window is resized.
14587 * See OO.ui.ComboBoxWidget for an example of a widget that uses this class.
14590 * @extends OO.ui.MenuSelectWidget
14593 * @param {OO.ui.TextInputWidget} inputWidget Text input widget to provide menu for
14594 * @param {Object} [config] Configuration options
14595 * @cfg {jQuery} [$container=input.$element] Element to render menu under
14597 OO
.ui
.TextInputMenuSelectWidget
= function OoUiTextInputMenuSelectWidget( inputWidget
, config
) {
14598 // Allow passing positional parameters inside the config object
14599 if ( OO
.isPlainObject( inputWidget
) && config
=== undefined ) {
14600 config
= inputWidget
;
14601 inputWidget
= config
.inputWidget
;
14604 // Configuration initialization
14605 config
= config
|| {};
14607 // Parent constructor
14608 OO
.ui
.TextInputMenuSelectWidget
.super.call( this, config
);
14611 this.inputWidget
= inputWidget
;
14612 this.$container
= config
.$container
|| this.inputWidget
.$element
;
14613 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
14616 this.$element
.addClass( 'oo-ui-textInputMenuSelectWidget' );
14621 OO
.inheritClass( OO
.ui
.TextInputMenuSelectWidget
, OO
.ui
.MenuSelectWidget
);
14626 * Handle window resize event.
14629 * @param {jQuery.Event} e Window resize event
14631 OO
.ui
.TextInputMenuSelectWidget
.prototype.onWindowResize = function () {
14638 OO
.ui
.TextInputMenuSelectWidget
.prototype.toggle = function ( visible
) {
14639 visible
= visible
=== undefined ? !this.isVisible() : !!visible
;
14641 var change
= visible
!== this.isVisible();
14643 if ( change
&& visible
) {
14644 // Make sure the width is set before the parent method runs.
14645 // After this we have to call this.position(); again to actually
14646 // position ourselves correctly.
14651 OO
.ui
.TextInputMenuSelectWidget
.super.prototype.toggle
.call( this, visible
);
14654 if ( this.isVisible() ) {
14656 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler
);
14658 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler
);
14666 * Position the menu.
14671 OO
.ui
.TextInputMenuSelectWidget
.prototype.position = function () {
14672 var $container
= this.$container
,
14673 pos
= OO
.ui
.Element
.static.getRelativePosition( $container
, this.$element
.offsetParent() );
14675 // Position under input
14676 pos
.top
+= $container
.height();
14677 this.$element
.css( pos
);
14680 this.setIdealSize( $container
.width() );
14681 // We updated the position, so re-evaluate the clipping state
14688 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
14689 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
14691 * ####Currently, this class is only used by {@link OO.ui.BookletLayout BookletLayouts}.####
14694 * @extends OO.ui.SelectWidget
14695 * @mixins OO.ui.TabIndexedElement
14698 * @param {Object} [config] Configuration options
14700 OO
.ui
.OutlineSelectWidget
= function OoUiOutlineSelectWidget( config
) {
14701 // Parent constructor
14702 OO
.ui
.OutlineSelectWidget
.super.call( this, config
);
14704 // Mixin constructors
14705 OO
.ui
.TabIndexedElement
.call( this, config
);
14708 this.$element
.on( {
14709 focus
: this.bindKeyDownListener
.bind( this ),
14710 blur
: this.unbindKeyDownListener
.bind( this )
14714 this.$element
.addClass( 'oo-ui-outlineSelectWidget' );
14719 OO
.inheritClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.SelectWidget
);
14720 OO
.mixinClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.TabIndexedElement
);
14723 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
14724 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
14725 * visually by a slider in the leftmost position.
14728 * // Toggle switches in the 'off' and 'on' position.
14729 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
14730 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
14734 * // Create a FieldsetLayout to layout and label switches
14735 * var fieldset = new OO.ui.FieldsetLayout( {
14736 * label: 'Toggle switches'
14738 * fieldset.addItems( [
14739 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
14740 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
14742 * $( 'body' ).append( fieldset.$element );
14745 * @extends OO.ui.Widget
14746 * @mixins OO.ui.ToggleWidget
14747 * @mixins OO.ui.TabIndexedElement
14750 * @param {Object} [config] Configuration options
14751 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
14752 * By default, the toggle switch is in the 'off' position.
14754 OO
.ui
.ToggleSwitchWidget
= function OoUiToggleSwitchWidget( config
) {
14755 // Parent constructor
14756 OO
.ui
.ToggleSwitchWidget
.super.call( this, config
);
14758 // Mixin constructors
14759 OO
.ui
.ToggleWidget
.call( this, config
);
14760 OO
.ui
.TabIndexedElement
.call( this, config
);
14763 this.dragging
= false;
14764 this.dragStart
= null;
14765 this.sliding
= false;
14766 this.$glow
= $( '<span>' );
14767 this.$grip
= $( '<span>' );
14770 this.$element
.on( {
14771 click
: this.onClick
.bind( this ),
14772 keypress
: this.onKeyPress
.bind( this )
14776 this.$glow
.addClass( 'oo-ui-toggleSwitchWidget-glow' );
14777 this.$grip
.addClass( 'oo-ui-toggleSwitchWidget-grip' );
14779 .addClass( 'oo-ui-toggleSwitchWidget' )
14780 .attr( 'role', 'checkbox' )
14781 .append( this.$glow
, this.$grip
);
14786 OO
.inheritClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.Widget
);
14787 OO
.mixinClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.ToggleWidget
);
14788 OO
.mixinClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.TabIndexedElement
);
14793 * Handle mouse click events.
14796 * @param {jQuery.Event} e Mouse click event
14798 OO
.ui
.ToggleSwitchWidget
.prototype.onClick = function ( e
) {
14799 if ( !this.isDisabled() && e
.which
=== 1 ) {
14800 this.setValue( !this.value
);
14806 * Handle key press events.
14809 * @param {jQuery.Event} e Key press event
14811 OO
.ui
.ToggleSwitchWidget
.prototype.onKeyPress = function ( e
) {
14812 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
14813 this.setValue( !this.value
);