3 * https://www.mediawiki.org/wiki/OOjs_UI
5 * Copyright 2011–2015 OOjs Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
9 * Date: 2015-04-03T21:01:28Z
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 Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
3445 * - **number**: the process will wait for the specified number of milliseconds before proceeding.
3446 * - **promise**: the process will continue to the next step when the promise is successfully resolved
3447 * or stop if the promise is rejected.
3448 * - **function**: the process will execute the function. The process will stop if the function returns
3449 * either a boolean `false` or a promise that is rejected; if the function returns a number, the process
3450 * will wait for that number of milliseconds before proceeding.
3452 * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
3453 * configured, users can dismiss the error and try the process again, or not. If a process is stopped,
3454 * its remaining steps will not be performed.
3459 * @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
3460 * that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
3461 * @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
3462 * a number or promise.
3463 * @return {Object} Step object, with `callback` and `context` properties
3465 OO
.ui
.Process = function ( step
, context
) {
3470 if ( step
!== undefined ) {
3471 this.next( step
, context
);
3477 OO
.initClass( OO
.ui
.Process
);
3482 * Start the process.
3484 * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
3485 * If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
3486 * and any remaining steps are not performed.
3488 OO
.ui
.Process
.prototype.execute = function () {
3489 var i
, len
, promise
;
3492 * Continue execution.
3495 * @param {Array} step A function and the context it should be called in
3496 * @return {Function} Function that continues the process
3498 function proceed( step
) {
3499 return function () {
3500 // Execute step in the correct context
3502 result
= step
.callback
.call( step
.context
);
3504 if ( result
=== false ) {
3505 // Use rejected promise for boolean false results
3506 return $.Deferred().reject( [] ).promise();
3508 if ( typeof result
=== 'number' ) {
3510 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3512 // Use a delayed promise for numbers, expecting them to be in milliseconds
3513 deferred
= $.Deferred();
3514 setTimeout( deferred
.resolve
, result
);
3515 return deferred
.promise();
3517 if ( result
instanceof OO
.ui
.Error
) {
3518 // Use rejected promise for error
3519 return $.Deferred().reject( [ result
] ).promise();
3521 if ( Array
.isArray( result
) && result
.length
&& result
[ 0 ] instanceof OO
.ui
.Error
) {
3522 // Use rejected promise for list of errors
3523 return $.Deferred().reject( result
).promise();
3525 // Duck-type the object to see if it can produce a promise
3526 if ( result
&& $.isFunction( result
.promise
) ) {
3527 // Use a promise generated from the result
3528 return result
.promise();
3530 // Use resolved promise for other results
3531 return $.Deferred().resolve().promise();
3535 if ( this.steps
.length
) {
3536 // Generate a chain reaction of promises
3537 promise
= proceed( this.steps
[ 0 ] )();
3538 for ( i
= 1, len
= this.steps
.length
; i
< len
; i
++ ) {
3539 promise
= promise
.then( proceed( this.steps
[ i
] ) );
3542 promise
= $.Deferred().resolve().promise();
3549 * Create a process step.
3552 * @param {number|jQuery.Promise|Function} step
3554 * - Number of milliseconds to wait before proceeding
3555 * - Promise that must be resolved before proceeding
3556 * - Function to execute
3557 * - If the function returns a boolean false the process will stop
3558 * - If the function returns a promise, the process will continue to the next
3559 * step when the promise is resolved or stop if the promise is rejected
3560 * - If the function returns a number, the process will wait for that number of
3561 * milliseconds before proceeding
3562 * @param {Object} [context=null] Execution context of the function. The context is
3563 * ignored if the step is a number or promise.
3564 * @return {Object} Step object, with `callback` and `context` properties
3566 OO
.ui
.Process
.prototype.createStep = function ( step
, context
) {
3567 if ( typeof step
=== 'number' || $.isFunction( step
.promise
) ) {
3569 callback: function () {
3575 if ( $.isFunction( step
) ) {
3581 throw new Error( 'Cannot create process step: number, promise or function expected' );
3585 * Add step to the beginning of the process.
3587 * @inheritdoc #createStep
3588 * @return {OO.ui.Process} this
3591 OO
.ui
.Process
.prototype.first = function ( step
, context
) {
3592 this.steps
.unshift( this.createStep( step
, context
) );
3597 * Add step to the end of the process.
3599 * @inheritdoc #createStep
3600 * @return {OO.ui.Process} this
3603 OO
.ui
.Process
.prototype.next = function ( step
, context
) {
3604 this.steps
.push( this.createStep( step
, context
) );
3609 * Factory for tools.
3612 * @extends OO.Factory
3615 OO
.ui
.ToolFactory
= function OoUiToolFactory() {
3616 // Parent constructor
3617 OO
.ui
.ToolFactory
.super.call( this );
3622 OO
.inheritClass( OO
.ui
.ToolFactory
, OO
.Factory
);
3627 * Get tools from the factory
3629 * @param {Array} include Included tools
3630 * @param {Array} exclude Excluded tools
3631 * @param {Array} promote Promoted tools
3632 * @param {Array} demote Demoted tools
3633 * @return {string[]} List of tools
3635 OO
.ui
.ToolFactory
.prototype.getTools = function ( include
, exclude
, promote
, demote
) {
3636 var i
, len
, included
, promoted
, demoted
,
3640 // Collect included and not excluded tools
3641 included
= OO
.simpleArrayDifference( this.extract( include
), this.extract( exclude
) );
3644 promoted
= this.extract( promote
, used
);
3645 demoted
= this.extract( demote
, used
);
3648 for ( i
= 0, len
= included
.length
; i
< len
; i
++ ) {
3649 if ( !used
[ included
[ i
] ] ) {
3650 auto
.push( included
[ i
] );
3654 return promoted
.concat( auto
).concat( demoted
);
3658 * Get a flat list of names from a list of names or groups.
3660 * Tools can be specified in the following ways:
3662 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
3663 * - All tools in a group: `{ group: 'group-name' }`
3664 * - All tools: `'*'`
3667 * @param {Array|string} collection List of tools
3668 * @param {Object} [used] Object with names that should be skipped as properties; extracted
3669 * names will be added as properties
3670 * @return {string[]} List of extracted names
3672 OO
.ui
.ToolFactory
.prototype.extract = function ( collection
, used
) {
3673 var i
, len
, item
, name
, tool
,
3676 if ( collection
=== '*' ) {
3677 for ( name
in this.registry
) {
3678 tool
= this.registry
[ name
];
3680 // Only add tools by group name when auto-add is enabled
3681 tool
.static.autoAddToCatchall
&&
3682 // Exclude already used tools
3683 ( !used
|| !used
[ name
] )
3687 used
[ name
] = true;
3691 } else if ( Array
.isArray( collection
) ) {
3692 for ( i
= 0, len
= collection
.length
; i
< len
; i
++ ) {
3693 item
= collection
[ i
];
3694 // Allow plain strings as shorthand for named tools
3695 if ( typeof item
=== 'string' ) {
3696 item
= { name
: item
};
3698 if ( OO
.isPlainObject( item
) ) {
3700 for ( name
in this.registry
) {
3701 tool
= this.registry
[ name
];
3703 // Include tools with matching group
3704 tool
.static.group
=== item
.group
&&
3705 // Only add tools by group name when auto-add is enabled
3706 tool
.static.autoAddToGroup
&&
3707 // Exclude already used tools
3708 ( !used
|| !used
[ name
] )
3712 used
[ name
] = true;
3716 // Include tools with matching name and exclude already used tools
3717 } else if ( item
.name
&& ( !used
|| !used
[ item
.name
] ) ) {
3718 names
.push( item
.name
);
3720 used
[ item
.name
] = true;
3730 * Factory for tool groups.
3733 * @extends OO.Factory
3736 OO
.ui
.ToolGroupFactory
= function OoUiToolGroupFactory() {
3737 // Parent constructor
3738 OO
.Factory
.call( this );
3741 defaultClasses
= this.constructor.static.getDefaultClasses();
3743 // Register default toolgroups
3744 for ( i
= 0, l
= defaultClasses
.length
; i
< l
; i
++ ) {
3745 this.register( defaultClasses
[ i
] );
3751 OO
.inheritClass( OO
.ui
.ToolGroupFactory
, OO
.Factory
);
3753 /* Static Methods */
3756 * Get a default set of classes to be registered on construction
3758 * @return {Function[]} Default classes
3760 OO
.ui
.ToolGroupFactory
.static.getDefaultClasses = function () {
3763 OO
.ui
.ListToolGroup
,
3775 * @param {Object} [config] Configuration options
3777 OO
.ui
.Theme
= function OoUiTheme( config
) {
3778 // Configuration initialization
3779 config
= config
|| {};
3784 OO
.initClass( OO
.ui
.Theme
);
3789 * Get a list of classes to be applied to a widget.
3791 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
3792 * otherwise state transitions will not work properly.
3794 * @param {OO.ui.Element} element Element for which to get classes
3795 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
3797 OO
.ui
.Theme
.prototype.getElementClasses = function ( /* element */ ) {
3798 return { on
: [], off
: [] };
3802 * Update CSS classes provided by the theme.
3804 * For elements with theme logic hooks, this should be called any time there's a state change.
3806 * @param {OO.ui.Element} element Element for which to update classes
3807 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
3809 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
3810 var classes
= this.getElementClasses( element
);
3813 .removeClass( classes
.off
.join( ' ' ) )
3814 .addClass( classes
.on
.join( ' ' ) );
3818 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
3819 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
3820 * order in which users will navigate through the focusable elements via the "tab" key.
3823 * // TabIndexedElement is mixed into the ButtonWidget class
3824 * // to provide a tabIndex property.
3825 * var button1 = new OO.ui.ButtonWidget( {
3829 * var button2 = new OO.ui.ButtonWidget( {
3833 * var button3 = new OO.ui.ButtonWidget( {
3837 * var button4 = new OO.ui.ButtonWidget( {
3841 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
3847 * @param {Object} [config] Configuration options
3848 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
3849 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
3850 * functionality will be applied to it instead.
3851 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
3852 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
3853 * to remove the element from the tab-navigation flow.
3855 OO
.ui
.TabIndexedElement
= function OoUiTabIndexedElement( config
) {
3856 // Configuration initialization
3857 config
= $.extend( { tabIndex
: 0 }, config
);
3860 this.$tabIndexed
= null;
3861 this.tabIndex
= null;
3864 this.connect( this, { disable
: 'onDisable' } );
3867 this.setTabIndex( config
.tabIndex
);
3868 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
3873 OO
.initClass( OO
.ui
.TabIndexedElement
);
3878 * Set the element that should use the tabindex functionality.
3880 * This method is used to retarget a tabindex mixin so that its functionality applies
3881 * to the specified element. If an element is currently using the functionality, the mixin’s
3882 * effect on that element is removed before the new element is set up.
3884 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
3887 OO
.ui
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
3888 var tabIndex
= this.tabIndex
;
3889 // Remove attributes from old $tabIndexed
3890 this.setTabIndex( null );
3891 // Force update of new $tabIndexed
3892 this.$tabIndexed
= $tabIndexed
;
3893 this.tabIndex
= tabIndex
;
3894 return this.updateTabIndex();
3898 * Set the value of the tabindex.
3900 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
3903 OO
.ui
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
3904 tabIndex
= typeof tabIndex
=== 'number' ? tabIndex
: null;
3906 if ( this.tabIndex
!== tabIndex
) {
3907 this.tabIndex
= tabIndex
;
3908 this.updateTabIndex();
3915 * Update the `tabindex` attribute, in case of changes to tab index or
3921 OO
.ui
.TabIndexedElement
.prototype.updateTabIndex = function () {
3922 if ( this.$tabIndexed
) {
3923 if ( this.tabIndex
!== null ) {
3924 // Do not index over disabled elements
3925 this.$tabIndexed
.attr( {
3926 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
3927 // ChromeVox and NVDA do not seem to inherit this from parent elements
3928 'aria-disabled': this.isDisabled().toString()
3931 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
3938 * Handle disable events.
3941 * @param {boolean} disabled Element is disabled
3943 OO
.ui
.TabIndexedElement
.prototype.onDisable = function () {
3944 this.updateTabIndex();
3948 * Get the value of the tabindex.
3950 * @return {number|null} Tabindex value
3952 OO
.ui
.TabIndexedElement
.prototype.getTabIndex = function () {
3953 return this.tabIndex
;
3957 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
3958 * interface element that can be configured with access keys for accessibility.
3959 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
3961 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
3966 * @param {Object} [config] Configuration options
3967 * @cfg {jQuery} [$button] The button element created by the class.
3968 * If this configuration is omitted, the button element will use a generated `<a>`.
3969 * @cfg {boolean} [framed=true] Render the button with a frame
3970 * @cfg {string} [accessKey] Button's access key
3972 OO
.ui
.ButtonElement
= function OoUiButtonElement( config
) {
3973 // Configuration initialization
3974 config
= config
|| {};
3977 this.$button
= null;
3979 this.accessKey
= null;
3980 this.active
= false;
3981 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
3982 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
3983 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
3984 this.onKeyUpHandler
= this.onKeyUp
.bind( this );
3985 this.onClickHandler
= this.onClick
.bind( this );
3986 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
3989 this.$element
.addClass( 'oo-ui-buttonElement' );
3990 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
3991 this.setAccessKey( config
.accessKey
);
3992 this.setButtonElement( config
.$button
|| $( '<a>' ) );
3997 OO
.initClass( OO
.ui
.ButtonElement
);
3999 /* Static Properties */
4002 * Cancel mouse down events.
4004 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
4005 * Classes such as {@link OO.ui.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
4006 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
4011 * @property {boolean}
4013 OO
.ui
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
4018 * A 'click' event is emitted when the button element is clicked.
4026 * Set the button element.
4028 * This method is used to retarget a button mixin so that its functionality applies to
4029 * the specified button element instead of the one created by the class. If a button element
4030 * is already set, the method will remove the mixin’s effect on that element.
4032 * @param {jQuery} $button Element to use as button
4034 OO
.ui
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
4035 if ( this.$button
) {
4037 .removeClass( 'oo-ui-buttonElement-button' )
4038 .removeAttr( 'role accesskey' )
4040 mousedown
: this.onMouseDownHandler
,
4041 keydown
: this.onKeyDownHandler
,
4042 click
: this.onClickHandler
,
4043 keypress
: this.onKeyPressHandler
4047 this.$button
= $button
4048 .addClass( 'oo-ui-buttonElement-button' )
4049 .attr( { role
: 'button', accesskey
: this.accessKey
} )
4051 mousedown
: this.onMouseDownHandler
,
4052 keydown
: this.onKeyDownHandler
,
4053 click
: this.onClickHandler
,
4054 keypress
: this.onKeyPressHandler
4059 * Handles mouse down events.
4062 * @param {jQuery.Event} e Mouse down event
4064 OO
.ui
.ButtonElement
.prototype.onMouseDown = function ( e
) {
4065 if ( this.isDisabled() || e
.which
!== 1 ) {
4068 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
4069 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4070 // reliably remove the pressed class
4071 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
4072 // Prevent change of focus unless specifically configured otherwise
4073 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
4079 * Handles mouse up events.
4082 * @param {jQuery.Event} e Mouse up event
4084 OO
.ui
.ButtonElement
.prototype.onMouseUp = function ( e
) {
4085 if ( this.isDisabled() || e
.which
!== 1 ) {
4088 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
4089 // Stop listening for mouseup, since we only needed this once
4090 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
4094 * Handles mouse click events.
4097 * @param {jQuery.Event} e Mouse click event
4100 OO
.ui
.ButtonElement
.prototype.onClick = function ( e
) {
4101 if ( !this.isDisabled() && e
.which
=== 1 ) {
4102 this.emit( 'click' );
4108 * Handles key down events.
4111 * @param {jQuery.Event} e Key down event
4113 OO
.ui
.ButtonElement
.prototype.onKeyDown = function ( e
) {
4114 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
4117 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
4118 // Run the keyup handler no matter where the key is when the button is let go, so we can
4119 // reliably remove the pressed class
4120 this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler
, true );
4124 * Handles key up events.
4127 * @param {jQuery.Event} e Key up event
4129 OO
.ui
.ButtonElement
.prototype.onKeyUp = function ( e
) {
4130 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
4133 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
4134 // Stop listening for keyup, since we only needed this once
4135 this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler
, true );
4139 * Handles key press events.
4142 * @param {jQuery.Event} e Key press event
4145 OO
.ui
.ButtonElement
.prototype.onKeyPress = function ( e
) {
4146 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
4147 this.emit( 'click' );
4153 * Check if button has a frame.
4155 * @return {boolean} Button is framed
4157 OO
.ui
.ButtonElement
.prototype.isFramed = function () {
4162 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
4164 * @param {boolean} [framed] Make button framed, omit to toggle
4167 OO
.ui
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
4168 framed
= framed
=== undefined ? !this.framed
: !!framed
;
4169 if ( framed
!== this.framed
) {
4170 this.framed
= framed
;
4172 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
4173 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
4174 this.updateThemeClasses();
4181 * Set the button's access key.
4183 * @param {string} accessKey Button's access key, use empty string to remove
4186 OO
.ui
.ButtonElement
.prototype.setAccessKey = function ( accessKey
) {
4187 accessKey
= typeof accessKey
=== 'string' && accessKey
.length
? accessKey
: null;
4189 if ( this.accessKey
!== accessKey
) {
4190 if ( this.$button
) {
4191 if ( accessKey
!== null ) {
4192 this.$button
.attr( 'accesskey', accessKey
);
4194 this.$button
.removeAttr( 'accesskey' );
4197 this.accessKey
= accessKey
;
4204 * Set the button to its 'active' state.
4206 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
4207 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
4208 * for other button types.
4210 * @param {boolean} [value] Make button active
4213 OO
.ui
.ButtonElement
.prototype.setActive = function ( value
) {
4214 this.$element
.toggleClass( 'oo-ui-buttonElement-active', !!value
);
4219 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4220 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4221 * items from the group is done through the interface the class provides.
4222 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4224 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4230 * @param {Object} [config] Configuration options
4231 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4232 * is omitted, the group element will use a generated `<div>`.
4234 OO
.ui
.GroupElement
= function OoUiGroupElement( config
) {
4235 // Configuration initialization
4236 config
= config
|| {};
4241 this.aggregateItemEvents
= {};
4244 this.setGroupElement( config
.$group
|| $( '<div>' ) );
4250 * Set the group element.
4252 * If an element is already set, items will be moved to the new element.
4254 * @param {jQuery} $group Element to use as group
4256 OO
.ui
.GroupElement
.prototype.setGroupElement = function ( $group
) {
4259 this.$group
= $group
;
4260 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4261 this.$group
.append( this.items
[ i
].$element
);
4266 * Check if a group contains no items.
4268 * @return {boolean} Group is empty
4270 OO
.ui
.GroupElement
.prototype.isEmpty = function () {
4271 return !this.items
.length
;
4275 * Get all items in the group.
4277 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4278 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4281 * @return {OO.ui.Element[]} An array of items.
4283 OO
.ui
.GroupElement
.prototype.getItems = function () {
4284 return this.items
.slice( 0 );
4288 * Get an item by its data.
4290 * Only the first item with matching data will be returned. To return all matching items,
4291 * use the #getItemsFromData method.
4293 * @param {Object} data Item data to search for
4294 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4296 OO
.ui
.GroupElement
.prototype.getItemFromData = function ( data
) {
4298 hash
= OO
.getHash( data
);
4300 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4301 item
= this.items
[ i
];
4302 if ( hash
=== OO
.getHash( item
.getData() ) ) {
4311 * Get items by their data.
4313 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4315 * @param {Object} data Item data to search for
4316 * @return {OO.ui.Element[]} Items with equivalent data
4318 OO
.ui
.GroupElement
.prototype.getItemsFromData = function ( data
) {
4320 hash
= OO
.getHash( data
),
4323 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4324 item
= this.items
[ i
];
4325 if ( hash
=== OO
.getHash( item
.getData() ) ) {
4334 * Aggregate the events emitted by the group.
4336 * When events are aggregated, the group will listen to all contained items for the event,
4337 * and then emit the event under a new name. The new event will contain an additional leading
4338 * parameter containing the item that emitted the original event. Other arguments emitted from
4339 * the original event are passed through.
4341 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
4342 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
4343 * A `null` value will remove aggregated events.
4345 * @throws {Error} An error is thrown if aggregation already exists.
4347 OO
.ui
.GroupElement
.prototype.aggregate = function ( events
) {
4348 var i
, len
, item
, add
, remove
, itemEvent
, groupEvent
;
4350 for ( itemEvent
in events
) {
4351 groupEvent
= events
[ itemEvent
];
4353 // Remove existing aggregated event
4354 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4355 // Don't allow duplicate aggregations
4357 throw new Error( 'Duplicate item event aggregation for ' + itemEvent
);
4359 // Remove event aggregation from existing items
4360 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4361 item
= this.items
[ i
];
4362 if ( item
.connect
&& item
.disconnect
) {
4364 remove
[ itemEvent
] = [ 'emit', groupEvent
, item
];
4365 item
.disconnect( this, remove
);
4368 // Prevent future items from aggregating event
4369 delete this.aggregateItemEvents
[ itemEvent
];
4372 // Add new aggregate event
4374 // Make future items aggregate event
4375 this.aggregateItemEvents
[ itemEvent
] = groupEvent
;
4376 // Add event aggregation to existing items
4377 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4378 item
= this.items
[ i
];
4379 if ( item
.connect
&& item
.disconnect
) {
4381 add
[ itemEvent
] = [ 'emit', groupEvent
, item
];
4382 item
.connect( this, add
);
4390 * Add items to the group.
4392 * Items will be added to the end of the group array unless the optional `index` parameter specifies
4393 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
4395 * @param {OO.ui.Element[]} items An array of items to add to the group
4396 * @param {number} [index] Index of the insertion point
4399 OO
.ui
.GroupElement
.prototype.addItems = function ( items
, index
) {
4400 var i
, len
, item
, event
, events
, currentIndex
,
4403 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
4406 // Check if item exists then remove it first, effectively "moving" it
4407 currentIndex
= $.inArray( item
, this.items
);
4408 if ( currentIndex
>= 0 ) {
4409 this.removeItems( [ item
] );
4410 // Adjust index to compensate for removal
4411 if ( currentIndex
< index
) {
4416 if ( item
.connect
&& item
.disconnect
&& !$.isEmptyObject( this.aggregateItemEvents
) ) {
4418 for ( event
in this.aggregateItemEvents
) {
4419 events
[ event
] = [ 'emit', this.aggregateItemEvents
[ event
], item
];
4421 item
.connect( this, events
);
4423 item
.setElementGroup( this );
4424 itemElements
.push( item
.$element
.get( 0 ) );
4427 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
4428 this.$group
.append( itemElements
);
4429 this.items
.push
.apply( this.items
, items
);
4430 } else if ( index
=== 0 ) {
4431 this.$group
.prepend( itemElements
);
4432 this.items
.unshift
.apply( this.items
, items
);
4434 this.items
[ index
].$element
.before( itemElements
);
4435 this.items
.splice
.apply( this.items
, [ index
, 0 ].concat( items
) );
4442 * Remove the specified items from a group.
4444 * Removed items are detached (not removed) from the DOM so that they may be reused.
4445 * To remove all items from a group, you may wish to use the #clearItems method instead.
4447 * @param {OO.ui.Element[]} items An array of items to remove
4450 OO
.ui
.GroupElement
.prototype.removeItems = function ( items
) {
4451 var i
, len
, item
, index
, remove
, itemEvent
;
4453 // Remove specific items
4454 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
4456 index
= $.inArray( item
, this.items
);
4457 if ( index
!== -1 ) {
4459 item
.connect
&& item
.disconnect
&&
4460 !$.isEmptyObject( this.aggregateItemEvents
)
4463 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4464 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4466 item
.disconnect( this, remove
);
4468 item
.setElementGroup( null );
4469 this.items
.splice( index
, 1 );
4470 item
.$element
.detach();
4478 * Clear all items from the group.
4480 * Cleared items are detached from the DOM, not removed, so that they may be reused.
4481 * To remove only a subset of items from a group, use the #removeItems method.
4485 OO
.ui
.GroupElement
.prototype.clearItems = function () {
4486 var i
, len
, item
, remove
, itemEvent
;
4489 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4490 item
= this.items
[ i
];
4492 item
.connect
&& item
.disconnect
&&
4493 !$.isEmptyObject( this.aggregateItemEvents
)
4496 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4497 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4499 item
.disconnect( this, remove
);
4501 item
.setElementGroup( null );
4502 item
.$element
.detach();
4510 * DraggableElement is a mixin class used to create elements that can be clicked
4511 * and dragged by a mouse to a new position within a group. This class must be used
4512 * in conjunction with OO.ui.DraggableGroupElement, which provides a container for
4513 * the draggable elements.
4520 OO
.ui
.DraggableElement
= function OoUiDraggableElement() {
4524 // Initialize and events
4526 .attr( 'draggable', true )
4527 .addClass( 'oo-ui-draggableElement' )
4529 dragstart
: this.onDragStart
.bind( this ),
4530 dragover
: this.onDragOver
.bind( this ),
4531 dragend
: this.onDragEnd
.bind( this ),
4532 drop
: this.onDrop
.bind( this )
4536 OO
.initClass( OO
.ui
.DraggableElement
);
4543 * A dragstart event is emitted when the user clicks and begins dragging an item.
4544 * @param {OO.ui.DraggableElement} item The item the user has clicked and is dragging with the mouse.
4549 * A dragend event is emitted when the user drags an item and releases the mouse,
4550 * thus terminating the drag operation.
4555 * A drop event is emitted when the user drags an item and then releases the mouse button
4556 * over a valid target.
4559 /* Static Properties */
4562 * @inheritdoc OO.ui.ButtonElement
4564 OO
.ui
.DraggableElement
.static.cancelButtonMouseDownEvents
= false;
4569 * Respond to dragstart event.
4572 * @param {jQuery.Event} event jQuery event
4575 OO
.ui
.DraggableElement
.prototype.onDragStart = function ( e
) {
4576 var dataTransfer
= e
.originalEvent
.dataTransfer
;
4577 // Define drop effect
4578 dataTransfer
.dropEffect
= 'none';
4579 dataTransfer
.effectAllowed
= 'move';
4580 // We must set up a dataTransfer data property or Firefox seems to
4581 // ignore the fact the element is draggable.
4583 dataTransfer
.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
4585 // The above is only for firefox. No need to set a catch clause
4586 // if it fails, move on.
4588 // Add dragging class
4589 this.$element
.addClass( 'oo-ui-draggableElement-dragging' );
4591 this.emit( 'dragstart', this );
4596 * Respond to dragend event.
4601 OO
.ui
.DraggableElement
.prototype.onDragEnd = function () {
4602 this.$element
.removeClass( 'oo-ui-draggableElement-dragging' );
4603 this.emit( 'dragend' );
4607 * Handle drop event.
4610 * @param {jQuery.Event} event jQuery event
4613 OO
.ui
.DraggableElement
.prototype.onDrop = function ( e
) {
4615 this.emit( 'drop', e
);
4619 * In order for drag/drop to work, the dragover event must
4620 * return false and stop propogation.
4624 OO
.ui
.DraggableElement
.prototype.onDragOver = function ( e
) {
4630 * Store it in the DOM so we can access from the widget drag event
4633 * @param {number} Item index
4635 OO
.ui
.DraggableElement
.prototype.setIndex = function ( index
) {
4636 if ( this.index
!== index
) {
4638 this.$element
.data( 'index', index
);
4646 * @return {number} Item index
4648 OO
.ui
.DraggableElement
.prototype.getIndex = function () {
4653 * DraggableGroupElement is a mixin class used to create a group element to
4654 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
4655 * The class is used with OO.ui.DraggableElement.
4659 * @mixins OO.ui.GroupElement
4662 * @param {Object} [config] Configuration options
4663 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
4664 * should match the layout of the items. Items displayed in a single row
4665 * or in several rows should use horizontal orientation. The vertical orientation should only be
4666 * used when the items are displayed in a single column. Defaults to 'vertical'
4668 OO
.ui
.DraggableGroupElement
= function OoUiDraggableGroupElement( config
) {
4669 // Configuration initialization
4670 config
= config
|| {};
4672 // Parent constructor
4673 OO
.ui
.GroupElement
.call( this, config
);
4676 this.orientation
= config
.orientation
|| 'vertical';
4677 this.dragItem
= null;
4678 this.itemDragOver
= null;
4680 this.sideInsertion
= '';
4684 dragstart
: 'itemDragStart',
4685 dragend
: 'itemDragEnd',
4688 this.connect( this, {
4689 itemDragStart
: 'onItemDragStart',
4690 itemDrop
: 'onItemDrop',
4691 itemDragEnd
: 'onItemDragEnd'
4694 dragover
: $.proxy( this.onDragOver
, this ),
4695 dragleave
: $.proxy( this.onDragLeave
, this )
4699 if ( Array
.isArray( config
.items
) ) {
4700 this.addItems( config
.items
);
4702 this.$placeholder
= $( '<div>' )
4703 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
4705 .addClass( 'oo-ui-draggableGroupElement' )
4706 .append( this.$status
)
4707 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation
=== 'horizontal' )
4708 .prepend( this.$placeholder
);
4712 OO
.mixinClass( OO
.ui
.DraggableGroupElement
, OO
.ui
.GroupElement
);
4717 * A 'reorder' event is emitted when the order of items in the group changes.
4720 * @param {OO.ui.DraggableElement} item Reordered item
4721 * @param {number} [newIndex] New index for the item
4727 * Respond to item drag start event
4730 * @param {OO.ui.DraggableElement} item Dragged item
4732 OO
.ui
.DraggableGroupElement
.prototype.onItemDragStart = function ( item
) {
4735 // Map the index of each object
4736 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4737 this.items
[ i
].setIndex( i
);
4740 if ( this.orientation
=== 'horizontal' ) {
4741 // Set the height of the indicator
4742 this.$placeholder
.css( {
4743 height
: item
.$element
.outerHeight(),
4747 // Set the width of the indicator
4748 this.$placeholder
.css( {
4750 width
: item
.$element
.outerWidth()
4753 this.setDragItem( item
);
4757 * Respond to item drag end event
4761 OO
.ui
.DraggableGroupElement
.prototype.onItemDragEnd = function () {
4762 this.unsetDragItem();
4767 * Handle drop event and switch the order of the items accordingly
4770 * @param {OO.ui.DraggableElement} item Dropped item
4773 OO
.ui
.DraggableGroupElement
.prototype.onItemDrop = function ( item
) {
4774 var toIndex
= item
.getIndex();
4775 // Check if the dropped item is from the current group
4776 // TODO: Figure out a way to configure a list of legally droppable
4777 // elements even if they are not yet in the list
4778 if ( this.getDragItem() ) {
4779 // If the insertion point is 'after', the insertion index
4780 // is shifted to the right (or to the left in RTL, hence 'after')
4781 if ( this.sideInsertion
=== 'after' ) {
4784 // Emit change event
4785 this.emit( 'reorder', this.getDragItem(), toIndex
);
4787 this.unsetDragItem();
4788 // Return false to prevent propogation
4793 * Handle dragleave event.
4797 OO
.ui
.DraggableGroupElement
.prototype.onDragLeave = function () {
4798 // This means the item was dragged outside the widget
4801 .addClass( 'oo-ui-element-hidden' );
4805 * Respond to dragover event
4808 * @param {jQuery.Event} event Event details
4810 OO
.ui
.DraggableGroupElement
.prototype.onDragOver = function ( e
) {
4811 var dragOverObj
, $optionWidget
, itemOffset
, itemMidpoint
, itemBoundingRect
,
4812 itemSize
, cssOutput
, dragPosition
, itemIndex
, itemPosition
,
4813 clientX
= e
.originalEvent
.clientX
,
4814 clientY
= e
.originalEvent
.clientY
;
4816 // Get the OptionWidget item we are dragging over
4817 dragOverObj
= this.getElementDocument().elementFromPoint( clientX
, clientY
);
4818 $optionWidget
= $( dragOverObj
).closest( '.oo-ui-draggableElement' );
4819 if ( $optionWidget
[ 0 ] ) {
4820 itemOffset
= $optionWidget
.offset();
4821 itemBoundingRect
= $optionWidget
[ 0 ].getBoundingClientRect();
4822 itemPosition
= $optionWidget
.position();
4823 itemIndex
= $optionWidget
.data( 'index' );
4828 this.isDragging() &&
4829 itemIndex
!== this.getDragItem().getIndex()
4831 if ( this.orientation
=== 'horizontal' ) {
4832 // Calculate where the mouse is relative to the item width
4833 itemSize
= itemBoundingRect
.width
;
4834 itemMidpoint
= itemBoundingRect
.left
+ itemSize
/ 2;
4835 dragPosition
= clientX
;
4836 // Which side of the item we hover over will dictate
4837 // where the placeholder will appear, on the left or
4840 left
: dragPosition
< itemMidpoint
? itemPosition
.left
: itemPosition
.left
+ itemSize
,
4841 top
: itemPosition
.top
4844 // Calculate where the mouse is relative to the item height
4845 itemSize
= itemBoundingRect
.height
;
4846 itemMidpoint
= itemBoundingRect
.top
+ itemSize
/ 2;
4847 dragPosition
= clientY
;
4848 // Which side of the item we hover over will dictate
4849 // where the placeholder will appear, on the top or
4852 top
: dragPosition
< itemMidpoint
? itemPosition
.top
: itemPosition
.top
+ itemSize
,
4853 left
: itemPosition
.left
4856 // Store whether we are before or after an item to rearrange
4857 // For horizontal layout, we need to account for RTL, as this is flipped
4858 if ( this.orientation
=== 'horizontal' && this.$element
.css( 'direction' ) === 'rtl' ) {
4859 this.sideInsertion
= dragPosition
< itemMidpoint
? 'after' : 'before';
4861 this.sideInsertion
= dragPosition
< itemMidpoint
? 'before' : 'after';
4863 // Add drop indicator between objects
4866 .removeClass( 'oo-ui-element-hidden' );
4868 // This means the item was dragged outside the widget
4871 .addClass( 'oo-ui-element-hidden' );
4878 * Set a dragged item
4880 * @param {OO.ui.DraggableElement} item Dragged item
4882 OO
.ui
.DraggableGroupElement
.prototype.setDragItem = function ( item
) {
4883 this.dragItem
= item
;
4887 * Unset the current dragged item
4889 OO
.ui
.DraggableGroupElement
.prototype.unsetDragItem = function () {
4890 this.dragItem
= null;
4891 this.itemDragOver
= null;
4892 this.$placeholder
.addClass( 'oo-ui-element-hidden' );
4893 this.sideInsertion
= '';
4897 * Get the item that is currently being dragged.
4899 * @return {OO.ui.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
4901 OO
.ui
.DraggableGroupElement
.prototype.getDragItem = function () {
4902 return this.dragItem
;
4906 * Check if an item in the group is currently being dragged.
4908 * @return {Boolean} Item is being dragged
4910 OO
.ui
.DraggableGroupElement
.prototype.isDragging = function () {
4911 return this.getDragItem() !== null;
4915 * IconElement is often mixed into other classes to generate an icon.
4916 * Icons are graphics, about the size of normal text. They are used to aid the user
4917 * in locating a control or to convey information in a space-efficient way. See the
4918 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
4919 * included in the library.
4921 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
4927 * @param {Object} [config] Configuration options
4928 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
4929 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
4930 * the icon element be set to an existing icon instead of the one generated by this class, set a
4931 * value using a jQuery selection. For example:
4933 * // Use a <div> tag instead of a <span>
4935 * // Use an existing icon element instead of the one generated by the class
4936 * $icon: this.$element
4937 * // Use an icon element from a child widget
4938 * $icon: this.childwidget.$element
4939 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
4940 * symbolic names. A map is used for i18n purposes and contains a `default` icon
4941 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
4942 * by the user's language.
4944 * Example of an i18n map:
4946 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
4947 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
4948 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
4949 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
4950 * text. The icon title is displayed when users move the mouse over the icon.
4952 OO
.ui
.IconElement
= function OoUiIconElement( config
) {
4953 // Configuration initialization
4954 config
= config
|| {};
4959 this.iconTitle
= null;
4962 this.setIcon( config
.icon
|| this.constructor.static.icon
);
4963 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
4964 this.setIconElement( config
.$icon
|| $( '<span>' ) );
4969 OO
.initClass( OO
.ui
.IconElement
);
4971 /* Static Properties */
4974 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
4975 * for i18n purposes and contains a `default` icon name and additional names keyed by
4976 * language code. The `default` name is used when no icon is keyed by the user's language.
4978 * Example of an i18n map:
4980 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
4982 * Note: the static property will be overridden if the #icon configuration is used.
4986 * @property {Object|string}
4988 OO
.ui
.IconElement
.static.icon
= null;
4991 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
4992 * function that returns title text, or `null` for no title.
4994 * The static property will be overridden if the #iconTitle configuration is used.
4998 * @property {string|Function|null}
5000 OO
.ui
.IconElement
.static.iconTitle
= null;
5005 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
5006 * applies to the specified icon element instead of the one created by the class. If an icon
5007 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
5008 * and mixin methods will no longer affect the element.
5010 * @param {jQuery} $icon Element to use as icon
5012 OO
.ui
.IconElement
.prototype.setIconElement = function ( $icon
) {
5015 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
5016 .removeAttr( 'title' );
5020 .addClass( 'oo-ui-iconElement-icon' )
5021 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
5022 if ( this.iconTitle
!== null ) {
5023 this.$icon
.attr( 'title', this.iconTitle
);
5028 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
5029 * The icon parameter can also be set to a map of icon names. See the #icon config setting
5032 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
5033 * by language code, or `null` to remove the icon.
5036 OO
.ui
.IconElement
.prototype.setIcon = function ( icon
) {
5037 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
5038 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
5040 if ( this.icon
!== icon
) {
5042 if ( this.icon
!== null ) {
5043 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
5045 if ( icon
!== null ) {
5046 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
5052 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
5053 this.updateThemeClasses();
5059 * Set the icon title. Use `null` to remove the title.
5061 * @param {string|Function|null} iconTitle A text string used as the icon title,
5062 * a function that returns title text, or `null` for no title.
5065 OO
.ui
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
5066 iconTitle
= typeof iconTitle
=== 'function' ||
5067 ( typeof iconTitle
=== 'string' && iconTitle
.length
) ?
5068 OO
.ui
.resolveMsg( iconTitle
) : null;
5070 if ( this.iconTitle
!== iconTitle
) {
5071 this.iconTitle
= iconTitle
;
5073 if ( this.iconTitle
!== null ) {
5074 this.$icon
.attr( 'title', iconTitle
);
5076 this.$icon
.removeAttr( 'title' );
5085 * Get the symbolic name of the icon.
5087 * @return {string} Icon name
5089 OO
.ui
.IconElement
.prototype.getIcon = function () {
5094 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5096 * @return {string} Icon title text
5098 OO
.ui
.IconElement
.prototype.getIconTitle = function () {
5099 return this.iconTitle
;
5103 * IndicatorElement is often mixed into other classes to generate an indicator.
5104 * Indicators are small graphics that are generally used in two ways:
5106 * - To draw attention to the status of an item. For example, an indicator might be
5107 * used to show that an item in a list has errors that need to be resolved.
5108 * - To clarify the function of a control that acts in an exceptional way (a button
5109 * that opens a menu instead of performing an action directly, for example).
5111 * For a list of indicators included in the library, please see the
5112 * [OOjs UI documentation on MediaWiki] [1].
5114 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5120 * @param {Object} [config] Configuration options
5121 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5122 * configuration is omitted, the indicator element will use a generated `<span>`.
5123 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5124 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5126 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5127 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5128 * or a function that returns title text. The indicator title is displayed when users move
5129 * the mouse over the indicator.
5131 OO
.ui
.IndicatorElement
= function OoUiIndicatorElement( config
) {
5132 // Configuration initialization
5133 config
= config
|| {};
5136 this.$indicator
= null;
5137 this.indicator
= null;
5138 this.indicatorTitle
= null;
5141 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
5142 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
5143 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
5148 OO
.initClass( OO
.ui
.IndicatorElement
);
5150 /* Static Properties */
5153 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5154 * The static property will be overridden if the #indicator configuration is used.
5158 * @property {string|null}
5160 OO
.ui
.IndicatorElement
.static.indicator
= null;
5163 * A text string used as the indicator title, a function that returns title text, or `null`
5164 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5168 * @property {string|Function|null}
5170 OO
.ui
.IndicatorElement
.static.indicatorTitle
= null;
5175 * Set the indicator element.
5177 * If an element is already set, it will be cleaned up before setting up the new element.
5179 * @param {jQuery} $indicator Element to use as indicator
5181 OO
.ui
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
5182 if ( this.$indicator
) {
5184 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
5185 .removeAttr( 'title' );
5188 this.$indicator
= $indicator
5189 .addClass( 'oo-ui-indicatorElement-indicator' )
5190 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
5191 if ( this.indicatorTitle
!== null ) {
5192 this.$indicator
.attr( 'title', this.indicatorTitle
);
5197 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5199 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5202 OO
.ui
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
5203 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
5205 if ( this.indicator
!== indicator
) {
5206 if ( this.$indicator
) {
5207 if ( this.indicator
!== null ) {
5208 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
5210 if ( indicator
!== null ) {
5211 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
5214 this.indicator
= indicator
;
5217 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
5218 this.updateThemeClasses();
5224 * Set the indicator title.
5226 * The title is displayed when a user moves the mouse over the indicator.
5228 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5229 * `null` for no indicator title
5232 OO
.ui
.IndicatorElement
.prototype.setIndicatorTitle = function ( indicatorTitle
) {
5233 indicatorTitle
= typeof indicatorTitle
=== 'function' ||
5234 ( typeof indicatorTitle
=== 'string' && indicatorTitle
.length
) ?
5235 OO
.ui
.resolveMsg( indicatorTitle
) : null;
5237 if ( this.indicatorTitle
!== indicatorTitle
) {
5238 this.indicatorTitle
= indicatorTitle
;
5239 if ( this.$indicator
) {
5240 if ( this.indicatorTitle
!== null ) {
5241 this.$indicator
.attr( 'title', indicatorTitle
);
5243 this.$indicator
.removeAttr( 'title' );
5252 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5254 * @return {string} Symbolic name of indicator
5256 OO
.ui
.IndicatorElement
.prototype.getIndicator = function () {
5257 return this.indicator
;
5261 * Get the indicator title.
5263 * The title is displayed when a user moves the mouse over the indicator.
5265 * @return {string} Indicator title text
5267 OO
.ui
.IndicatorElement
.prototype.getIndicatorTitle = function () {
5268 return this.indicatorTitle
;
5272 * LabelElement is often mixed into other classes to generate a label, which
5273 * helps identify the function of an interface element.
5274 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5276 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5282 * @param {Object} [config] Configuration options
5283 * @cfg {jQuery} [$label] The label element created by the class. If this
5284 * configuration is omitted, the label element will use a generated `<span>`.
5285 * @cfg {jQuery|string|Function} [label] The label text. The label can be specified as a plaintext string,
5286 * a jQuery selection of elements, or a function that will produce a string in the future. See the
5287 * [OOjs UI documentation on MediaWiki] [2] for examples.
5288 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5289 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5290 * The label will be truncated to fit if necessary.
5292 OO
.ui
.LabelElement
= function OoUiLabelElement( config
) {
5293 // Configuration initialization
5294 config
= config
|| {};
5299 this.autoFitLabel
= config
.autoFitLabel
=== undefined || !!config
.autoFitLabel
;
5302 this.setLabel( config
.label
|| this.constructor.static.label
);
5303 this.setLabelElement( config
.$label
|| $( '<span>' ) );
5308 OO
.initClass( OO
.ui
.LabelElement
);
5313 * @event labelChange
5314 * @param {string} value
5317 /* Static Properties */
5320 * The label text. The label can be specified as a plaintext string, a function that will
5321 * produce a string in the future, or `null` for no label. The static value will
5322 * be overridden if a label is specified with the #label config option.
5326 * @property {string|Function|null}
5328 OO
.ui
.LabelElement
.static.label
= null;
5333 * Set the label element.
5335 * If an element is already set, it will be cleaned up before setting up the new element.
5337 * @param {jQuery} $label Element to use as label
5339 OO
.ui
.LabelElement
.prototype.setLabelElement = function ( $label
) {
5340 if ( this.$label
) {
5341 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
5344 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
5345 this.setLabelContent( this.label
);
5351 * An empty string will result in the label being hidden. A string containing only whitespace will
5352 * be converted to a single ` `.
5354 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
5355 * text; or null for no label
5358 OO
.ui
.LabelElement
.prototype.setLabel = function ( label
) {
5359 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
5360 label
= ( ( typeof label
=== 'string' && label
.length
) || label
instanceof jQuery
|| label
instanceof OO
.ui
.HtmlSnippet
) ? label
: null;
5362 this.$element
.toggleClass( 'oo-ui-labelElement', !!label
);
5364 if ( this.label
!== label
) {
5365 if ( this.$label
) {
5366 this.setLabelContent( label
);
5369 this.emit( 'labelChange' );
5378 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
5379 * text; or null for no label
5381 OO
.ui
.LabelElement
.prototype.getLabel = function () {
5390 OO
.ui
.LabelElement
.prototype.fitLabel = function () {
5391 if ( this.$label
&& this.$label
.autoEllipsis
&& this.autoFitLabel
) {
5392 this.$label
.autoEllipsis( { hasSpan
: false, tooltip
: true } );
5399 * Set the content of the label.
5401 * Do not call this method until after the label element has been set by #setLabelElement.
5404 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5405 * text; or null for no label
5407 OO
.ui
.LabelElement
.prototype.setLabelContent = function ( label
) {
5408 if ( typeof label
=== 'string' ) {
5409 if ( label
.match( /^\s*$/ ) ) {
5410 // Convert whitespace only string to a single non-breaking space
5411 this.$label
.html( ' ' );
5413 this.$label
.text( label
);
5415 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
5416 this.$label
.html( label
.toString() );
5417 } else if ( label
instanceof jQuery
) {
5418 this.$label
.empty().append( label
);
5420 this.$label
.empty();
5425 * LookupElement is a mixin that creates a {@link OO.ui.TextInputMenuSelectWidget menu} of suggested values for
5426 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
5427 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
5428 * from the lookup menu, that value becomes the value of the input field.
5430 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
5431 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
5432 * re-enable lookups.
5434 * See the [OOjs UI demos][1] for an example.
5436 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
5442 * @param {Object} [config] Configuration options
5443 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
5444 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
5445 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
5446 * By default, the lookup menu is not generated and displayed until the user begins to type.
5448 OO
.ui
.LookupElement
= function OoUiLookupElement( config
) {
5449 // Configuration initialization
5450 config
= config
|| {};
5453 this.$overlay
= config
.$overlay
|| this.$element
;
5454 this.lookupMenu
= new OO
.ui
.TextInputMenuSelectWidget( this, {
5457 $container
: config
.$container
5460 this.allowSuggestionsWhenEmpty
= config
.allowSuggestionsWhenEmpty
|| false;
5462 this.lookupCache
= {};
5463 this.lookupQuery
= null;
5464 this.lookupRequest
= null;
5465 this.lookupsDisabled
= false;
5466 this.lookupInputFocused
= false;
5470 focus
: this.onLookupInputFocus
.bind( this ),
5471 blur
: this.onLookupInputBlur
.bind( this ),
5472 mousedown
: this.onLookupInputMouseDown
.bind( this )
5474 this.connect( this, { change
: 'onLookupInputChange' } );
5475 this.lookupMenu
.connect( this, {
5476 toggle
: 'onLookupMenuToggle',
5477 choose
: 'onLookupMenuItemChoose'
5481 this.$element
.addClass( 'oo-ui-lookupElement' );
5482 this.lookupMenu
.$element
.addClass( 'oo-ui-lookupElement-menu' );
5483 this.$overlay
.append( this.lookupMenu
.$element
);
5489 * Handle input focus event.
5492 * @param {jQuery.Event} e Input focus event
5494 OO
.ui
.LookupElement
.prototype.onLookupInputFocus = function () {
5495 this.lookupInputFocused
= true;
5496 this.populateLookupMenu();
5500 * Handle input blur event.
5503 * @param {jQuery.Event} e Input blur event
5505 OO
.ui
.LookupElement
.prototype.onLookupInputBlur = function () {
5506 this.closeLookupMenu();
5507 this.lookupInputFocused
= false;
5511 * Handle input mouse down event.
5514 * @param {jQuery.Event} e Input mouse down event
5516 OO
.ui
.LookupElement
.prototype.onLookupInputMouseDown = function () {
5517 // Only open the menu if the input was already focused.
5518 // This way we allow the user to open the menu again after closing it with Esc
5519 // by clicking in the input. Opening (and populating) the menu when initially
5520 // clicking into the input is handled by the focus handler.
5521 if ( this.lookupInputFocused
&& !this.lookupMenu
.isVisible() ) {
5522 this.populateLookupMenu();
5527 * Handle input change event.
5530 * @param {string} value New input value
5532 OO
.ui
.LookupElement
.prototype.onLookupInputChange = function () {
5533 if ( this.lookupInputFocused
) {
5534 this.populateLookupMenu();
5539 * Handle the lookup menu being shown/hidden.
5542 * @param {boolean} visible Whether the lookup menu is now visible.
5544 OO
.ui
.LookupElement
.prototype.onLookupMenuToggle = function ( visible
) {
5546 // When the menu is hidden, abort any active request and clear the menu.
5547 // This has to be done here in addition to closeLookupMenu(), because
5548 // MenuSelectWidget will close itself when the user presses Esc.
5549 this.abortLookupRequest();
5550 this.lookupMenu
.clearItems();
5555 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
5558 * @param {OO.ui.MenuOptionWidget} item Selected item
5560 OO
.ui
.LookupElement
.prototype.onLookupMenuItemChoose = function ( item
) {
5561 this.setValue( item
.getData() );
5568 * @return {OO.ui.TextInputMenuSelectWidget}
5570 OO
.ui
.LookupElement
.prototype.getLookupMenu = function () {
5571 return this.lookupMenu
;
5575 * Disable or re-enable lookups.
5577 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
5579 * @param {boolean} disabled Disable lookups
5581 OO
.ui
.LookupElement
.prototype.setLookupsDisabled = function ( disabled
) {
5582 this.lookupsDisabled
= !!disabled
;
5586 * Open the menu. If there are no entries in the menu, this does nothing.
5591 OO
.ui
.LookupElement
.prototype.openLookupMenu = function () {
5592 if ( !this.lookupMenu
.isEmpty() ) {
5593 this.lookupMenu
.toggle( true );
5599 * Close the menu, empty it, and abort any pending request.
5604 OO
.ui
.LookupElement
.prototype.closeLookupMenu = function () {
5605 this.lookupMenu
.toggle( false );
5606 this.abortLookupRequest();
5607 this.lookupMenu
.clearItems();
5612 * Request menu items based on the input's current value, and when they arrive,
5613 * populate the menu with these items and show the menu.
5615 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
5620 OO
.ui
.LookupElement
.prototype.populateLookupMenu = function () {
5622 value
= this.getValue();
5624 if ( this.lookupsDisabled
) {
5628 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
5629 if ( !this.allowSuggestionsWhenEmpty
&& value
=== '' ) {
5630 this.closeLookupMenu();
5631 // Skip population if there is already a request pending for the current value
5632 } else if ( value
!== this.lookupQuery
) {
5633 this.getLookupMenuItems()
5634 .done( function ( items
) {
5635 widget
.lookupMenu
.clearItems();
5636 if ( items
.length
) {
5640 widget
.initializeLookupMenuSelection();
5642 widget
.lookupMenu
.toggle( false );
5645 .fail( function () {
5646 widget
.lookupMenu
.clearItems();
5654 * Select and highlight the first selectable item in the menu.
5659 OO
.ui
.LookupElement
.prototype.initializeLookupMenuSelection = function () {
5660 if ( !this.lookupMenu
.getSelectedItem() ) {
5661 this.lookupMenu
.selectItem( this.lookupMenu
.getFirstSelectableItem() );
5663 this.lookupMenu
.highlightItem( this.lookupMenu
.getSelectedItem() );
5667 * Get lookup menu items for the current query.
5670 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
5671 * the done event. If the request was aborted to make way for a subsequent request, this promise
5672 * will not be rejected: it will remain pending forever.
5674 OO
.ui
.LookupElement
.prototype.getLookupMenuItems = function () {
5676 value
= this.getValue(),
5677 deferred
= $.Deferred(),
5680 this.abortLookupRequest();
5681 if ( Object
.prototype.hasOwnProperty
.call( this.lookupCache
, value
) ) {
5682 deferred
.resolve( this.getLookupMenuOptionsFromData( this.lookupCache
[ value
] ) );
5685 this.lookupQuery
= value
;
5686 ourRequest
= this.lookupRequest
= this.getLookupRequest();
5688 .always( function () {
5689 // We need to pop pending even if this is an old request, otherwise
5690 // the widget will remain pending forever.
5691 // TODO: this assumes that an aborted request will fail or succeed soon after
5692 // being aborted, or at least eventually. It would be nice if we could popPending()
5693 // at abort time, but only if we knew that we hadn't already called popPending()
5694 // for that request.
5695 widget
.popPending();
5697 .done( function ( response
) {
5698 // If this is an old request (and aborting it somehow caused it to still succeed),
5699 // ignore its success completely
5700 if ( ourRequest
=== widget
.lookupRequest
) {
5701 widget
.lookupQuery
= null;
5702 widget
.lookupRequest
= null;
5703 widget
.lookupCache
[ value
] = widget
.getLookupCacheDataFromResponse( response
);
5704 deferred
.resolve( widget
.getLookupMenuOptionsFromData( widget
.lookupCache
[ value
] ) );
5707 .fail( function () {
5708 // If this is an old request (or a request failing because it's being aborted),
5709 // ignore its failure completely
5710 if ( ourRequest
=== widget
.lookupRequest
) {
5711 widget
.lookupQuery
= null;
5712 widget
.lookupRequest
= null;
5717 return deferred
.promise();
5721 * Abort the currently pending lookup request, if any.
5725 OO
.ui
.LookupElement
.prototype.abortLookupRequest = function () {
5726 var oldRequest
= this.lookupRequest
;
5728 // First unset this.lookupRequest to the fail handler will notice
5729 // that the request is no longer current
5730 this.lookupRequest
= null;
5731 this.lookupQuery
= null;
5737 * Get a new request object of the current lookup query value.
5741 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
5743 OO
.ui
.LookupElement
.prototype.getLookupRequest = function () {
5744 // Stub, implemented in subclass
5749 * Pre-process data returned by the request from #getLookupRequest.
5751 * The return value of this function will be cached, and any further queries for the given value
5752 * will use the cache rather than doing API requests.
5756 * @param {Mixed} response Response from server
5757 * @return {Mixed} Cached result data
5759 OO
.ui
.LookupElement
.prototype.getLookupCacheDataFromResponse = function () {
5760 // Stub, implemented in subclass
5765 * Get a list of menu option widgets from the (possibly cached) data returned by
5766 * #getLookupCacheDataFromResponse.
5770 * @param {Mixed} data Cached result data, usually an array
5771 * @return {OO.ui.MenuOptionWidget[]} Menu items
5773 OO
.ui
.LookupElement
.prototype.getLookupMenuOptionsFromData = function () {
5774 // Stub, implemented in subclass
5779 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5780 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5781 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5782 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5788 * @param {Object} [config] Configuration options
5789 * @cfg {Object} [popup] Configuration to pass to popup
5790 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5792 OO
.ui
.PopupElement
= function OoUiPopupElement( config
) {
5793 // Configuration initialization
5794 config
= config
|| {};
5797 this.popup
= new OO
.ui
.PopupWidget( $.extend(
5798 { autoClose
: true },
5800 { $autoCloseIgnore
: this.$element
}
5809 * @return {OO.ui.PopupWidget} Popup widget
5811 OO
.ui
.PopupElement
.prototype.getPopup = function () {
5816 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
5817 * additional functionality to an element created by another class. The class provides
5818 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
5819 * which are used to customize the look and feel of a widget to better describe its
5820 * importance and functionality.
5822 * The library currently contains the following styling flags for general use:
5824 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
5825 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
5826 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
5828 * The flags affect the appearance of the buttons:
5831 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
5832 * var button1 = new OO.ui.ButtonWidget( {
5833 * label: 'Constructive',
5834 * flags: 'constructive'
5836 * var button2 = new OO.ui.ButtonWidget( {
5837 * label: 'Destructive',
5838 * flags: 'destructive'
5840 * var button3 = new OO.ui.ButtonWidget( {
5841 * label: 'Progressive',
5842 * flags: 'progressive'
5844 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
5846 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
5847 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
5849 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
5855 * @param {Object} [config] Configuration options
5856 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
5857 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
5858 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
5859 * @cfg {jQuery} [$flagged] The flagged element. By default,
5860 * the flagged functionality is applied to the element created by the class ($element).
5861 * If a different element is specified, the flagged functionality will be applied to it instead.
5863 OO
.ui
.FlaggedElement
= function OoUiFlaggedElement( config
) {
5864 // Configuration initialization
5865 config
= config
|| {};
5869 this.$flagged
= null;
5872 this.setFlags( config
.flags
);
5873 this.setFlaggedElement( config
.$flagged
|| this.$element
);
5880 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
5881 * parameter contains the name of each modified flag and indicates whether it was
5884 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
5885 * that the flag was added, `false` that the flag was removed.
5891 * Set the flagged element.
5893 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
5894 * If an element is already set, the method will remove the mixin’s effect on that element.
5896 * @param {jQuery} $flagged Element that should be flagged
5898 OO
.ui
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
5899 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
5900 return 'oo-ui-flaggedElement-' + flag
;
5903 if ( this.$flagged
) {
5904 this.$flagged
.removeClass( classNames
);
5907 this.$flagged
= $flagged
.addClass( classNames
);
5911 * Check if the specified flag is set.
5913 * @param {string} flag Name of flag
5914 * @return {boolean} The flag is set
5916 OO
.ui
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
5917 return flag
in this.flags
;
5921 * Get the names of all flags set.
5923 * @return {string[]} Flag names
5925 OO
.ui
.FlaggedElement
.prototype.getFlags = function () {
5926 return Object
.keys( this.flags
);
5935 OO
.ui
.FlaggedElement
.prototype.clearFlags = function () {
5936 var flag
, className
,
5939 classPrefix
= 'oo-ui-flaggedElement-';
5941 for ( flag
in this.flags
) {
5942 className
= classPrefix
+ flag
;
5943 changes
[ flag
] = false;
5944 delete this.flags
[ flag
];
5945 remove
.push( className
);
5948 if ( this.$flagged
) {
5949 this.$flagged
.removeClass( remove
.join( ' ' ) );
5952 this.updateThemeClasses();
5953 this.emit( 'flag', changes
);
5959 * Add one or more flags.
5961 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
5962 * or an object keyed by flag name with a boolean value that indicates whether the flag should
5963 * be added (`true`) or removed (`false`).
5967 OO
.ui
.FlaggedElement
.prototype.setFlags = function ( flags
) {
5968 var i
, len
, flag
, className
,
5972 classPrefix
= 'oo-ui-flaggedElement-';
5974 if ( typeof flags
=== 'string' ) {
5975 className
= classPrefix
+ flags
;
5977 if ( !this.flags
[ flags
] ) {
5978 this.flags
[ flags
] = true;
5979 add
.push( className
);
5981 } else if ( Array
.isArray( flags
) ) {
5982 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
5984 className
= classPrefix
+ flag
;
5986 if ( !this.flags
[ flag
] ) {
5987 changes
[ flag
] = true;
5988 this.flags
[ flag
] = true;
5989 add
.push( className
);
5992 } else if ( OO
.isPlainObject( flags
) ) {
5993 for ( flag
in flags
) {
5994 className
= classPrefix
+ flag
;
5995 if ( flags
[ flag
] ) {
5997 if ( !this.flags
[ flag
] ) {
5998 changes
[ flag
] = true;
5999 this.flags
[ flag
] = true;
6000 add
.push( className
);
6004 if ( this.flags
[ flag
] ) {
6005 changes
[ flag
] = false;
6006 delete this.flags
[ flag
];
6007 remove
.push( className
);
6013 if ( this.$flagged
) {
6015 .addClass( add
.join( ' ' ) )
6016 .removeClass( remove
.join( ' ' ) );
6019 this.updateThemeClasses();
6020 this.emit( 'flag', changes
);
6026 * TitledElement is mixed into other classes to provide a `title` attribute.
6027 * Titles are rendered by the browser and are made visible when the user moves
6028 * the mouse over the element. Titles are not visible on touch devices.
6031 * // TitledElement provides a 'title' attribute to the
6032 * // ButtonWidget class
6033 * var button = new OO.ui.ButtonWidget( {
6034 * label: 'Button with Title',
6035 * title: 'I am a button'
6037 * $( 'body' ).append( button.$element );
6043 * @param {Object} [config] Configuration options
6044 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
6045 * If this config is omitted, the title functionality is applied to $element, the
6046 * element created by the class.
6047 * @cfg {string|Function} [title] The title text or a function that returns text. If
6048 * this config is omitted, the value of the {@link #static-title static title} property is used.
6050 OO
.ui
.TitledElement
= function OoUiTitledElement( config
) {
6051 // Configuration initialization
6052 config
= config
|| {};
6055 this.$titled
= null;
6059 this.setTitle( config
.title
|| this.constructor.static.title
);
6060 this.setTitledElement( config
.$titled
|| this.$element
);
6065 OO
.initClass( OO
.ui
.TitledElement
);
6067 /* Static Properties */
6070 * The title text, a function that returns text, or `null` for no title. The value of the static property
6071 * is overridden if the #title config option is used.
6075 * @property {string|Function|null}
6077 OO
.ui
.TitledElement
.static.title
= null;
6082 * Set the titled element.
6084 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6085 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6087 * @param {jQuery} $titled Element that should use the 'titled' functionality
6089 OO
.ui
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
6090 if ( this.$titled
) {
6091 this.$titled
.removeAttr( 'title' );
6094 this.$titled
= $titled
;
6096 this.$titled
.attr( 'title', this.title
);
6103 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6106 OO
.ui
.TitledElement
.prototype.setTitle = function ( title
) {
6107 title
= typeof title
=== 'string' ? OO
.ui
.resolveMsg( title
) : null;
6109 if ( this.title
!== title
) {
6110 if ( this.$titled
) {
6111 if ( title
!== null ) {
6112 this.$titled
.attr( 'title', title
);
6114 this.$titled
.removeAttr( 'title' );
6126 * @return {string} Title string
6128 OO
.ui
.TitledElement
.prototype.getTitle = function () {
6133 * Element that can be automatically clipped to visible boundaries.
6135 * Whenever the element's natural height changes, you have to call
6136 * #clip to make sure it's still clipping correctly.
6142 * @param {Object} [config] Configuration options
6143 * @cfg {jQuery} [$clippable] Nodes to clip, assigned to #$clippable, omit to use #$element
6145 OO
.ui
.ClippableElement
= function OoUiClippableElement( config
) {
6146 // Configuration initialization
6147 config
= config
|| {};
6150 this.$clippable
= null;
6151 this.clipping
= false;
6152 this.clippedHorizontally
= false;
6153 this.clippedVertically
= false;
6154 this.$clippableContainer
= null;
6155 this.$clippableScroller
= null;
6156 this.$clippableWindow
= null;
6157 this.idealWidth
= null;
6158 this.idealHeight
= null;
6159 this.onClippableContainerScrollHandler
= this.clip
.bind( this );
6160 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
6163 this.setClippableElement( config
.$clippable
|| this.$element
);
6169 * Set clippable element.
6171 * If an element is already set, it will be cleaned up before setting up the new element.
6173 * @param {jQuery} $clippable Element to make clippable
6175 OO
.ui
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
6176 if ( this.$clippable
) {
6177 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
6178 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
6179 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6182 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
6189 * Do not turn clipping on until after the element is attached to the DOM and visible.
6191 * @param {boolean} [clipping] Enable clipping, omit to toggle
6194 OO
.ui
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
6195 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
6197 if ( this.clipping
!== clipping
) {
6198 this.clipping
= clipping
;
6200 this.$clippableContainer
= $( this.getClosestScrollableElementContainer() );
6201 // If the clippable container is the root, we have to listen to scroll events and check
6202 // jQuery.scrollTop on the window because of browser inconsistencies
6203 this.$clippableScroller
= this.$clippableContainer
.is( 'html, body' ) ?
6204 $( OO
.ui
.Element
.static.getWindow( this.$clippableContainer
) ) :
6205 this.$clippableContainer
;
6206 this.$clippableScroller
.on( 'scroll', this.onClippableContainerScrollHandler
);
6207 this.$clippableWindow
= $( this.getElementWindow() )
6208 .on( 'resize', this.onClippableWindowResizeHandler
);
6209 // Initial clip after visible
6212 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
6213 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6215 this.$clippableContainer
= null;
6216 this.$clippableScroller
.off( 'scroll', this.onClippableContainerScrollHandler
);
6217 this.$clippableScroller
= null;
6218 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
6219 this.$clippableWindow
= null;
6227 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6229 * @return {boolean} Element will be clipped to the visible area
6231 OO
.ui
.ClippableElement
.prototype.isClipping = function () {
6232 return this.clipping
;
6236 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6238 * @return {boolean} Part of the element is being clipped
6240 OO
.ui
.ClippableElement
.prototype.isClipped = function () {
6241 return this.clippedHorizontally
|| this.clippedVertically
;
6245 * Check if the right of the element is being clipped by the nearest scrollable container.
6247 * @return {boolean} Part of the element is being clipped
6249 OO
.ui
.ClippableElement
.prototype.isClippedHorizontally = function () {
6250 return this.clippedHorizontally
;
6254 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6256 * @return {boolean} Part of the element is being clipped
6258 OO
.ui
.ClippableElement
.prototype.isClippedVertically = function () {
6259 return this.clippedVertically
;
6263 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6265 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6266 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6268 OO
.ui
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
6269 this.idealWidth
= width
;
6270 this.idealHeight
= height
;
6272 if ( !this.clipping
) {
6273 // Update dimensions
6274 this.$clippable
.css( { width
: width
, height
: height
} );
6276 // While clipping, idealWidth and idealHeight are not considered
6280 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6281 * the element's natural height changes.
6283 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6284 * overlapped by, the visible area of the nearest scrollable container.
6288 OO
.ui
.ClippableElement
.prototype.clip = function () {
6289 if ( !this.clipping
) {
6290 // this.$clippableContainer and this.$clippableWindow are null, so the below will fail
6294 var buffer
= 7, // Chosen by fair dice roll
6295 cOffset
= this.$clippable
.offset(),
6296 $container
= this.$clippableContainer
.is( 'html, body' ) ?
6297 this.$clippableWindow
: this.$clippableContainer
,
6298 ccOffset
= $container
.offset() || { top
: 0, left
: 0 },
6299 ccHeight
= $container
.innerHeight() - buffer
,
6300 ccWidth
= $container
.innerWidth() - buffer
,
6301 cHeight
= this.$clippable
.outerHeight() + buffer
,
6302 cWidth
= this.$clippable
.outerWidth() + buffer
,
6303 scrollTop
= this.$clippableScroller
.scrollTop(),
6304 scrollLeft
= this.$clippableScroller
.scrollLeft(),
6305 desiredWidth
= cOffset
.left
< 0 ?
6306 cWidth
+ cOffset
.left
:
6307 ( ccOffset
.left
+ scrollLeft
+ ccWidth
) - cOffset
.left
,
6308 desiredHeight
= cOffset
.top
< 0 ?
6309 cHeight
+ cOffset
.top
:
6310 ( ccOffset
.top
+ scrollTop
+ ccHeight
) - cOffset
.top
,
6311 naturalWidth
= this.$clippable
.prop( 'scrollWidth' ),
6312 naturalHeight
= this.$clippable
.prop( 'scrollHeight' ),
6313 clipWidth
= desiredWidth
< naturalWidth
,
6314 clipHeight
= desiredHeight
< naturalHeight
;
6317 this.$clippable
.css( { overflowX
: 'scroll', width
: desiredWidth
} );
6319 this.$clippable
.css( { width
: this.idealWidth
|| '', overflowX
: '' } );
6322 this.$clippable
.css( { overflowY
: 'scroll', height
: desiredHeight
} );
6324 this.$clippable
.css( { height
: this.idealHeight
|| '', overflowY
: '' } );
6327 // If we stopped clipping in at least one of the dimensions
6328 if ( !clipWidth
|| !clipHeight
) {
6329 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6332 this.clippedHorizontally
= clipWidth
;
6333 this.clippedVertically
= clipHeight
;
6339 * Generic toolbar tool.
6343 * @extends OO.ui.Widget
6344 * @mixins OO.ui.IconElement
6345 * @mixins OO.ui.FlaggedElement
6348 * @param {OO.ui.ToolGroup} toolGroup
6349 * @param {Object} [config] Configuration options
6350 * @cfg {string|Function} [title] Title text or a function that returns text
6352 OO
.ui
.Tool
= function OoUiTool( toolGroup
, config
) {
6353 // Allow passing positional parameters inside the config object
6354 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
6356 toolGroup
= config
.toolGroup
;
6359 // Configuration initialization
6360 config
= config
|| {};
6362 // Parent constructor
6363 OO
.ui
.Tool
.super.call( this, config
);
6365 // Mixin constructors
6366 OO
.ui
.IconElement
.call( this, config
);
6367 OO
.ui
.FlaggedElement
.call( this, config
);
6370 this.toolGroup
= toolGroup
;
6371 this.toolbar
= this.toolGroup
.getToolbar();
6372 this.active
= false;
6373 this.$title
= $( '<span>' );
6374 this.$accel
= $( '<span>' );
6375 this.$link
= $( '<a>' );
6379 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
6382 this.$title
.addClass( 'oo-ui-tool-title' );
6384 .addClass( 'oo-ui-tool-accel' )
6386 // This may need to be changed if the key names are ever localized,
6387 // but for now they are essentially written in English
6392 .addClass( 'oo-ui-tool-link' )
6393 .append( this.$icon
, this.$title
, this.$accel
)
6394 .prop( 'tabIndex', 0 )
6395 .attr( 'role', 'button' );
6397 .data( 'oo-ui-tool', this )
6399 'oo-ui-tool ' + 'oo-ui-tool-name-' +
6400 this.constructor.static.name
.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
6402 .append( this.$link
);
6403 this.setTitle( config
.title
|| this.constructor.static.title
);
6408 OO
.inheritClass( OO
.ui
.Tool
, OO
.ui
.Widget
);
6409 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.IconElement
);
6410 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.FlaggedElement
);
6418 /* Static Properties */
6424 OO
.ui
.Tool
.static.tagName
= 'span';
6427 * Symbolic name of tool.
6432 * @property {string}
6434 OO
.ui
.Tool
.static.name
= '';
6442 * @property {string}
6444 OO
.ui
.Tool
.static.group
= '';
6449 * Title is used as a tooltip when the tool is part of a bar tool group, or a label when the tool
6450 * is part of a list or menu tool group. If a trigger is associated with an action by the same name
6451 * as the tool, a description of its keyboard shortcut for the appropriate platform will be
6452 * appended to the title if the tool is part of a bar tool group.
6457 * @property {string|Function} Title text or a function that returns text
6459 OO
.ui
.Tool
.static.title
= '';
6462 * Tool can be automatically added to catch-all groups.
6466 * @property {boolean}
6468 OO
.ui
.Tool
.static.autoAddToCatchall
= true;
6471 * Tool can be automatically added to named groups.
6474 * @property {boolean}
6477 OO
.ui
.Tool
.static.autoAddToGroup
= true;
6480 * Check if this tool is compatible with given data.
6484 * @param {Mixed} data Data to check
6485 * @return {boolean} Tool can be used with data
6487 OO
.ui
.Tool
.static.isCompatibleWith = function () {
6494 * Handle the toolbar state being updated.
6496 * This is an abstract method that must be overridden in a concrete subclass.
6500 OO
.ui
.Tool
.prototype.onUpdateState = function () {
6502 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
6507 * Handle the tool being selected.
6509 * This is an abstract method that must be overridden in a concrete subclass.
6513 OO
.ui
.Tool
.prototype.onSelect = function () {
6515 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
6520 * Check if the button is active.
6522 * @return {boolean} Button is active
6524 OO
.ui
.Tool
.prototype.isActive = function () {
6529 * Make the button appear active or inactive.
6531 * @param {boolean} state Make button appear active
6533 OO
.ui
.Tool
.prototype.setActive = function ( state
) {
6534 this.active
= !!state
;
6535 if ( this.active
) {
6536 this.$element
.addClass( 'oo-ui-tool-active' );
6538 this.$element
.removeClass( 'oo-ui-tool-active' );
6543 * Get the tool title.
6545 * @param {string|Function} title Title text or a function that returns text
6548 OO
.ui
.Tool
.prototype.setTitle = function ( title
) {
6549 this.title
= OO
.ui
.resolveMsg( title
);
6555 * Get the tool title.
6557 * @return {string} Title text
6559 OO
.ui
.Tool
.prototype.getTitle = function () {
6564 * Get the tool's symbolic name.
6566 * @return {string} Symbolic name of tool
6568 OO
.ui
.Tool
.prototype.getName = function () {
6569 return this.constructor.static.name
;
6575 OO
.ui
.Tool
.prototype.updateTitle = function () {
6576 var titleTooltips
= this.toolGroup
.constructor.static.titleTooltips
,
6577 accelTooltips
= this.toolGroup
.constructor.static.accelTooltips
,
6578 accel
= this.toolbar
.getToolAccelerator( this.constructor.static.name
),
6581 this.$title
.text( this.title
);
6582 this.$accel
.text( accel
);
6584 if ( titleTooltips
&& typeof this.title
=== 'string' && this.title
.length
) {
6585 tooltipParts
.push( this.title
);
6587 if ( accelTooltips
&& typeof accel
=== 'string' && accel
.length
) {
6588 tooltipParts
.push( accel
);
6590 if ( tooltipParts
.length
) {
6591 this.$link
.attr( 'title', tooltipParts
.join( ' ' ) );
6593 this.$link
.removeAttr( 'title' );
6600 OO
.ui
.Tool
.prototype.destroy = function () {
6601 this.toolbar
.disconnect( this );
6602 this.$element
.remove();
6606 * Collection of tool groups.
6609 * @extends OO.ui.Element
6610 * @mixins OO.EventEmitter
6611 * @mixins OO.ui.GroupElement
6614 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
6615 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating tool groups
6616 * @param {Object} [config] Configuration options
6617 * @cfg {boolean} [actions] Add an actions section opposite to the tools
6618 * @cfg {boolean} [shadow] Add a shadow below the toolbar
6620 OO
.ui
.Toolbar
= function OoUiToolbar( toolFactory
, toolGroupFactory
, config
) {
6621 // Allow passing positional parameters inside the config object
6622 if ( OO
.isPlainObject( toolFactory
) && config
=== undefined ) {
6623 config
= toolFactory
;
6624 toolFactory
= config
.toolFactory
;
6625 toolGroupFactory
= config
.toolGroupFactory
;
6628 // Configuration initialization
6629 config
= config
|| {};
6631 // Parent constructor
6632 OO
.ui
.Toolbar
.super.call( this, config
);
6634 // Mixin constructors
6635 OO
.EventEmitter
.call( this );
6636 OO
.ui
.GroupElement
.call( this, config
);
6639 this.toolFactory
= toolFactory
;
6640 this.toolGroupFactory
= toolGroupFactory
;
6643 this.$bar
= $( '<div>' );
6644 this.$actions
= $( '<div>' );
6645 this.initialized
= false;
6646 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
6650 .add( this.$bar
).add( this.$group
).add( this.$actions
)
6651 .on( 'mousedown', this.onPointerDown
.bind( this ) );
6654 this.$group
.addClass( 'oo-ui-toolbar-tools' );
6655 if ( config
.actions
) {
6656 this.$bar
.append( this.$actions
.addClass( 'oo-ui-toolbar-actions' ) );
6659 .addClass( 'oo-ui-toolbar-bar' )
6660 .append( this.$group
, '<div style="clear:both"></div>' );
6661 if ( config
.shadow
) {
6662 this.$bar
.append( '<div class="oo-ui-toolbar-shadow"></div>' );
6664 this.$element
.addClass( 'oo-ui-toolbar' ).append( this.$bar
);
6669 OO
.inheritClass( OO
.ui
.Toolbar
, OO
.ui
.Element
);
6670 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.EventEmitter
);
6671 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.ui
.GroupElement
);
6676 * Get the tool factory.
6678 * @return {OO.ui.ToolFactory} Tool factory
6680 OO
.ui
.Toolbar
.prototype.getToolFactory = function () {
6681 return this.toolFactory
;
6685 * Get the tool group factory.
6687 * @return {OO.Factory} Tool group factory
6689 OO
.ui
.Toolbar
.prototype.getToolGroupFactory = function () {
6690 return this.toolGroupFactory
;
6694 * Handles mouse down events.
6696 * @param {jQuery.Event} e Mouse down event
6698 OO
.ui
.Toolbar
.prototype.onPointerDown = function ( e
) {
6699 var $closestWidgetToEvent
= $( e
.target
).closest( '.oo-ui-widget' ),
6700 $closestWidgetToToolbar
= this.$element
.closest( '.oo-ui-widget' );
6701 if ( !$closestWidgetToEvent
.length
|| $closestWidgetToEvent
[ 0 ] === $closestWidgetToToolbar
[ 0 ] ) {
6707 * Handle window resize event.
6710 * @param {jQuery.Event} e Window resize event
6712 OO
.ui
.Toolbar
.prototype.onWindowResize = function () {
6713 this.$element
.toggleClass(
6714 'oo-ui-toolbar-narrow',
6715 this.$bar
.width() <= this.narrowThreshold
6720 * Sets up handles and preloads required information for the toolbar to work.
6721 * This must be called after it is attached to a visible document and before doing anything else.
6723 OO
.ui
.Toolbar
.prototype.initialize = function () {
6724 this.initialized
= true;
6725 this.narrowThreshold
= this.$group
.width() + this.$actions
.width();
6726 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler
);
6727 this.onWindowResize();
6733 * Tools can be specified in the following ways:
6735 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
6736 * - All tools in a group: `{ group: 'group-name' }`
6737 * - All tools: `'*'` - Using this will make the group a list with a "More" label by default
6739 * @param {Object.<string,Array>} groups List of tool group configurations
6740 * @param {Array|string} [groups.include] Tools to include
6741 * @param {Array|string} [groups.exclude] Tools to exclude
6742 * @param {Array|string} [groups.promote] Tools to promote to the beginning
6743 * @param {Array|string} [groups.demote] Tools to demote to the end
6745 OO
.ui
.Toolbar
.prototype.setup = function ( groups
) {
6746 var i
, len
, type
, group
,
6748 defaultType
= 'bar';
6750 // Cleanup previous groups
6753 // Build out new groups
6754 for ( i
= 0, len
= groups
.length
; i
< len
; i
++ ) {
6755 group
= groups
[ i
];
6756 if ( group
.include
=== '*' ) {
6757 // Apply defaults to catch-all groups
6758 if ( group
.type
=== undefined ) {
6759 group
.type
= 'list';
6761 if ( group
.label
=== undefined ) {
6762 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
6765 // Check type has been registered
6766 type
= this.getToolGroupFactory().lookup( group
.type
) ? group
.type
: defaultType
;
6768 this.getToolGroupFactory().create( type
, this, group
)
6771 this.addItems( items
);
6775 * Remove all tools and groups from the toolbar.
6777 OO
.ui
.Toolbar
.prototype.reset = function () {
6782 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6783 this.items
[ i
].destroy();
6789 * Destroys toolbar, removing event handlers and DOM elements.
6791 * Call this whenever you are done using a toolbar.
6793 OO
.ui
.Toolbar
.prototype.destroy = function () {
6794 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler
);
6796 this.$element
.remove();
6800 * Check if tool has not been used yet.
6802 * @param {string} name Symbolic name of tool
6803 * @return {boolean} Tool is available
6805 OO
.ui
.Toolbar
.prototype.isToolAvailable = function ( name
) {
6806 return !this.tools
[ name
];
6810 * Prevent tool from being used again.
6812 * @param {OO.ui.Tool} tool Tool to reserve
6814 OO
.ui
.Toolbar
.prototype.reserveTool = function ( tool
) {
6815 this.tools
[ tool
.getName() ] = tool
;
6819 * Allow tool to be used again.
6821 * @param {OO.ui.Tool} tool Tool to release
6823 OO
.ui
.Toolbar
.prototype.releaseTool = function ( tool
) {
6824 delete this.tools
[ tool
.getName() ];
6828 * Get accelerator label for tool.
6830 * This is a stub that should be overridden to provide access to accelerator information.
6832 * @param {string} name Symbolic name of tool
6833 * @return {string|undefined} Tool accelerator label if available
6835 OO
.ui
.Toolbar
.prototype.getToolAccelerator = function () {
6840 * Collection of tools.
6842 * Tools can be specified in the following ways:
6844 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
6845 * - All tools in a group: `{ group: 'group-name' }`
6846 * - All tools: `'*'`
6850 * @extends OO.ui.Widget
6851 * @mixins OO.ui.GroupElement
6854 * @param {OO.ui.Toolbar} toolbar
6855 * @param {Object} [config] Configuration options
6856 * @cfg {Array|string} [include=[]] List of tools to include
6857 * @cfg {Array|string} [exclude=[]] List of tools to exclude
6858 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning
6859 * @cfg {Array|string} [demote=[]] List of tools to demote to the end
6861 OO
.ui
.ToolGroup
= function OoUiToolGroup( toolbar
, config
) {
6862 // Allow passing positional parameters inside the config object
6863 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
6865 toolbar
= config
.toolbar
;
6868 // Configuration initialization
6869 config
= config
|| {};
6871 // Parent constructor
6872 OO
.ui
.ToolGroup
.super.call( this, config
);
6874 // Mixin constructors
6875 OO
.ui
.GroupElement
.call( this, config
);
6878 this.toolbar
= toolbar
;
6880 this.pressed
= null;
6881 this.autoDisabled
= false;
6882 this.include
= config
.include
|| [];
6883 this.exclude
= config
.exclude
|| [];
6884 this.promote
= config
.promote
|| [];
6885 this.demote
= config
.demote
|| [];
6886 this.onCapturedMouseUpHandler
= this.onCapturedMouseUp
.bind( this );
6890 mousedown
: this.onPointerDown
.bind( this ),
6891 mouseup
: this.onPointerUp
.bind( this ),
6892 mouseover
: this.onMouseOver
.bind( this ),
6893 mouseout
: this.onMouseOut
.bind( this )
6895 this.toolbar
.getToolFactory().connect( this, { register
: 'onToolFactoryRegister' } );
6896 this.aggregate( { disable
: 'itemDisable' } );
6897 this.connect( this, { itemDisable
: 'updateDisabled' } );
6900 this.$group
.addClass( 'oo-ui-toolGroup-tools' );
6902 .addClass( 'oo-ui-toolGroup' )
6903 .append( this.$group
);
6909 OO
.inheritClass( OO
.ui
.ToolGroup
, OO
.ui
.Widget
);
6910 OO
.mixinClass( OO
.ui
.ToolGroup
, OO
.ui
.GroupElement
);
6918 /* Static Properties */
6921 * Show labels in tooltips.
6925 * @property {boolean}
6927 OO
.ui
.ToolGroup
.static.titleTooltips
= false;
6930 * Show acceleration labels in tooltips.
6934 * @property {boolean}
6936 OO
.ui
.ToolGroup
.static.accelTooltips
= false;
6939 * Automatically disable the toolgroup when all tools are disabled
6943 * @property {boolean}
6945 OO
.ui
.ToolGroup
.static.autoDisable
= true;
6952 OO
.ui
.ToolGroup
.prototype.isDisabled = function () {
6953 return this.autoDisabled
|| OO
.ui
.ToolGroup
.super.prototype.isDisabled
.apply( this, arguments
);
6959 OO
.ui
.ToolGroup
.prototype.updateDisabled = function () {
6960 var i
, item
, allDisabled
= true;
6962 if ( this.constructor.static.autoDisable
) {
6963 for ( i
= this.items
.length
- 1; i
>= 0; i
-- ) {
6964 item
= this.items
[ i
];
6965 if ( !item
.isDisabled() ) {
6966 allDisabled
= false;
6970 this.autoDisabled
= allDisabled
;
6972 OO
.ui
.ToolGroup
.super.prototype.updateDisabled
.apply( this, arguments
);
6976 * Handle mouse down events.
6978 * @param {jQuery.Event} e Mouse down event
6980 OO
.ui
.ToolGroup
.prototype.onPointerDown = function ( e
) {
6981 if ( !this.isDisabled() && e
.which
=== 1 ) {
6982 this.pressed
= this.getTargetTool( e
);
6983 if ( this.pressed
) {
6984 this.pressed
.setActive( true );
6985 this.getElementDocument().addEventListener(
6986 'mouseup', this.onCapturedMouseUpHandler
, true
6994 * Handle captured mouse up events.
6996 * @param {Event} e Mouse up event
6998 OO
.ui
.ToolGroup
.prototype.onCapturedMouseUp = function ( e
) {
6999 this.getElementDocument().removeEventListener( 'mouseup', this.onCapturedMouseUpHandler
, true );
7000 // onPointerUp may be called a second time, depending on where the mouse is when the button is
7001 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
7002 this.onPointerUp( e
);
7006 * Handle mouse up events.
7008 * @param {jQuery.Event} e Mouse up event
7010 OO
.ui
.ToolGroup
.prototype.onPointerUp = function ( e
) {
7011 var tool
= this.getTargetTool( e
);
7013 if ( !this.isDisabled() && e
.which
=== 1 && this.pressed
&& this.pressed
=== tool
) {
7014 this.pressed
.onSelect();
7017 this.pressed
= null;
7022 * Handle mouse over events.
7024 * @param {jQuery.Event} e Mouse over event
7026 OO
.ui
.ToolGroup
.prototype.onMouseOver = function ( e
) {
7027 var tool
= this.getTargetTool( e
);
7029 if ( this.pressed
&& this.pressed
=== tool
) {
7030 this.pressed
.setActive( true );
7035 * Handle mouse out events.
7037 * @param {jQuery.Event} e Mouse out event
7039 OO
.ui
.ToolGroup
.prototype.onMouseOut = function ( e
) {
7040 var tool
= this.getTargetTool( e
);
7042 if ( this.pressed
&& this.pressed
=== tool
) {
7043 this.pressed
.setActive( false );
7048 * Get the closest tool to a jQuery.Event.
7050 * Only tool links are considered, which prevents other elements in the tool such as popups from
7051 * triggering tool group interactions.
7054 * @param {jQuery.Event} e
7055 * @return {OO.ui.Tool|null} Tool, `null` if none was found
7057 OO
.ui
.ToolGroup
.prototype.getTargetTool = function ( e
) {
7059 $item
= $( e
.target
).closest( '.oo-ui-tool-link' );
7061 if ( $item
.length
) {
7062 tool
= $item
.parent().data( 'oo-ui-tool' );
7065 return tool
&& !tool
.isDisabled() ? tool
: null;
7069 * Handle tool registry register events.
7071 * If a tool is registered after the group is created, we must repopulate the list to account for:
7073 * - a tool being added that may be included
7074 * - a tool already included being overridden
7076 * @param {string} name Symbolic name of tool
7078 OO
.ui
.ToolGroup
.prototype.onToolFactoryRegister = function () {
7083 * Get the toolbar this group is in.
7085 * @return {OO.ui.Toolbar} Toolbar of group
7087 OO
.ui
.ToolGroup
.prototype.getToolbar = function () {
7088 return this.toolbar
;
7092 * Add and remove tools based on configuration.
7094 OO
.ui
.ToolGroup
.prototype.populate = function () {
7095 var i
, len
, name
, tool
,
7096 toolFactory
= this.toolbar
.getToolFactory(),
7100 list
= this.toolbar
.getToolFactory().getTools(
7101 this.include
, this.exclude
, this.promote
, this.demote
7104 // Build a list of needed tools
7105 for ( i
= 0, len
= list
.length
; i
< len
; i
++ ) {
7109 toolFactory
.lookup( name
) &&
7110 // Tool is available or is already in this group
7111 ( this.toolbar
.isToolAvailable( name
) || this.tools
[ name
] )
7113 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
7114 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
7115 this.toolbar
.tools
[ name
] = true;
7116 tool
= this.tools
[ name
];
7118 // Auto-initialize tools on first use
7119 this.tools
[ name
] = tool
= toolFactory
.create( name
, this );
7122 this.toolbar
.reserveTool( tool
);
7124 names
[ name
] = true;
7127 // Remove tools that are no longer needed
7128 for ( name
in this.tools
) {
7129 if ( !names
[ name
] ) {
7130 this.tools
[ name
].destroy();
7131 this.toolbar
.releaseTool( this.tools
[ name
] );
7132 remove
.push( this.tools
[ name
] );
7133 delete this.tools
[ name
];
7136 if ( remove
.length
) {
7137 this.removeItems( remove
);
7139 // Update emptiness state
7141 this.$element
.removeClass( 'oo-ui-toolGroup-empty' );
7143 this.$element
.addClass( 'oo-ui-toolGroup-empty' );
7145 // Re-add tools (moving existing ones to new locations)
7146 this.addItems( add
);
7147 // Disabled state may depend on items
7148 this.updateDisabled();
7152 * Destroy tool group.
7154 OO
.ui
.ToolGroup
.prototype.destroy = function () {
7158 this.toolbar
.getToolFactory().disconnect( this );
7159 for ( name
in this.tools
) {
7160 this.toolbar
.releaseTool( this.tools
[ name
] );
7161 this.tools
[ name
].disconnect( this ).destroy();
7162 delete this.tools
[ name
];
7164 this.$element
.remove();
7168 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
7169 * consists of a header that contains the dialog title, a body with the message, and a footer that
7170 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
7171 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
7173 * There are two basic types of message dialogs, confirmation and alert:
7175 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
7176 * more details about the consequences.
7177 * - **alert**: the dialog title describes which event occurred and the message provides more information
7178 * about why the event occurred.
7180 * The MessageDialog class specifies two actions: ‘accept’, the primary
7181 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
7182 * passing along the selected action.
7184 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
7187 * // Example: Creating and opening a message dialog window.
7188 * var messageDialog = new OO.ui.MessageDialog();
7190 * // Create and append a window manager.
7191 * var windowManager = new OO.ui.WindowManager();
7192 * $( 'body' ).append( windowManager.$element );
7193 * windowManager.addWindows( [ messageDialog ] );
7194 * // Open the window.
7195 * windowManager.openWindow( messageDialog, {
7196 * title: 'Basic message dialog',
7197 * message: 'This is the message'
7200 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
7203 * @extends OO.ui.Dialog
7206 * @param {Object} [config] Configuration options
7208 OO
.ui
.MessageDialog
= function OoUiMessageDialog( config
) {
7209 // Parent constructor
7210 OO
.ui
.MessageDialog
.super.call( this, config
);
7213 this.verticalActionLayout
= null;
7216 this.$element
.addClass( 'oo-ui-messageDialog' );
7221 OO
.inheritClass( OO
.ui
.MessageDialog
, OO
.ui
.Dialog
);
7223 /* Static Properties */
7225 OO
.ui
.MessageDialog
.static.name
= 'message';
7227 OO
.ui
.MessageDialog
.static.size
= 'small';
7229 OO
.ui
.MessageDialog
.static.verbose
= false;
7234 * The title of a confirmation dialog describes what a progressive action will do. The
7235 * title of an alert dialog describes which event occurred.
7239 * @property {jQuery|string|Function|null}
7241 OO
.ui
.MessageDialog
.static.title
= null;
7244 * The message displayed in the dialog body.
7246 * A confirmation message describes the consequences of a progressive action. An alert
7247 * message describes why an event occurred.
7251 * @property {jQuery|string|Function|null}
7253 OO
.ui
.MessageDialog
.static.message
= null;
7255 OO
.ui
.MessageDialog
.static.actions
= [
7256 { action
: 'accept', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-accept' ), flags
: 'primary' },
7257 { action
: 'reject', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-reject' ), flags
: 'safe' }
7265 OO
.ui
.MessageDialog
.prototype.setManager = function ( manager
) {
7266 OO
.ui
.MessageDialog
.super.prototype.setManager
.call( this, manager
);
7269 this.manager
.connect( this, {
7279 OO
.ui
.MessageDialog
.prototype.onActionResize = function ( action
) {
7281 return OO
.ui
.MessageDialog
.super.prototype.onActionResize
.call( this, action
);
7285 * Handle window resized events.
7289 OO
.ui
.MessageDialog
.prototype.onResize = function () {
7291 dialog
.fitActions();
7292 // Wait for CSS transition to finish and do it again :(
7293 setTimeout( function () {
7294 dialog
.fitActions();
7299 * Toggle action layout between vertical and horizontal.
7303 * @param {boolean} [value] Layout actions vertically, omit to toggle
7306 OO
.ui
.MessageDialog
.prototype.toggleVerticalActionLayout = function ( value
) {
7307 value
= value
=== undefined ? !this.verticalActionLayout
: !!value
;
7309 if ( value
!== this.verticalActionLayout
) {
7310 this.verticalActionLayout
= value
;
7312 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value
)
7313 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value
);
7322 OO
.ui
.MessageDialog
.prototype.getActionProcess = function ( action
) {
7324 return new OO
.ui
.Process( function () {
7325 this.close( { action
: action
} );
7328 return OO
.ui
.MessageDialog
.super.prototype.getActionProcess
.call( this, action
);
7334 * @param {Object} [data] Dialog opening data
7335 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
7336 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
7337 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
7338 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
7341 OO
.ui
.MessageDialog
.prototype.getSetupProcess = function ( data
) {
7345 return OO
.ui
.MessageDialog
.super.prototype.getSetupProcess
.call( this, data
)
7346 .next( function () {
7347 this.title
.setLabel(
7348 data
.title
!== undefined ? data
.title
: this.constructor.static.title
7350 this.message
.setLabel(
7351 data
.message
!== undefined ? data
.message
: this.constructor.static.message
7353 this.message
.$element
.toggleClass(
7354 'oo-ui-messageDialog-message-verbose',
7355 data
.verbose
!== undefined ? data
.verbose
: this.constructor.static.verbose
7363 OO
.ui
.MessageDialog
.prototype.getBodyHeight = function () {
7364 var bodyHeight
, oldOverflow
,
7365 $scrollable
= this.container
.$element
;
7367 oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
7368 $scrollable
[ 0 ].style
.overflow
= 'hidden';
7370 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
7372 bodyHeight
= this.text
.$element
.outerHeight( true );
7373 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
7381 OO
.ui
.MessageDialog
.prototype.setDimensions = function ( dim
) {
7382 var $scrollable
= this.container
.$element
;
7383 OO
.ui
.MessageDialog
.super.prototype.setDimensions
.call( this, dim
);
7385 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
7386 // Need to do it after transition completes (250ms), add 50ms just in case.
7387 setTimeout( function () {
7388 var oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
7389 $scrollable
[ 0 ].style
.overflow
= 'hidden';
7391 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
7393 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
7402 OO
.ui
.MessageDialog
.prototype.initialize = function () {
7404 OO
.ui
.MessageDialog
.super.prototype.initialize
.call( this );
7407 this.$actions
= $( '<div>' );
7408 this.container
= new OO
.ui
.PanelLayout( {
7409 scrollable
: true, classes
: [ 'oo-ui-messageDialog-container' ]
7411 this.text
= new OO
.ui
.PanelLayout( {
7412 padded
: true, expanded
: false, classes
: [ 'oo-ui-messageDialog-text' ]
7414 this.message
= new OO
.ui
.LabelWidget( {
7415 classes
: [ 'oo-ui-messageDialog-message' ]
7419 this.title
.$element
.addClass( 'oo-ui-messageDialog-title' );
7420 this.$content
.addClass( 'oo-ui-messageDialog-content' );
7421 this.container
.$element
.append( this.text
.$element
);
7422 this.text
.$element
.append( this.title
.$element
, this.message
.$element
);
7423 this.$body
.append( this.container
.$element
);
7424 this.$actions
.addClass( 'oo-ui-messageDialog-actions' );
7425 this.$foot
.append( this.$actions
);
7431 OO
.ui
.MessageDialog
.prototype.attachActions = function () {
7432 var i
, len
, other
, special
, others
;
7435 OO
.ui
.MessageDialog
.super.prototype.attachActions
.call( this );
7437 special
= this.actions
.getSpecial();
7438 others
= this.actions
.getOthers();
7439 if ( special
.safe
) {
7440 this.$actions
.append( special
.safe
.$element
);
7441 special
.safe
.toggleFramed( false );
7443 if ( others
.length
) {
7444 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
7445 other
= others
[ i
];
7446 this.$actions
.append( other
.$element
);
7447 other
.toggleFramed( false );
7450 if ( special
.primary
) {
7451 this.$actions
.append( special
.primary
.$element
);
7452 special
.primary
.toggleFramed( false );
7455 if ( !this.isOpening() ) {
7456 // If the dialog is currently opening, this will be called automatically soon.
7457 // This also calls #fitActions.
7463 * Fit action actions into columns or rows.
7465 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
7469 OO
.ui
.MessageDialog
.prototype.fitActions = function () {
7471 previous
= this.verticalActionLayout
,
7472 actions
= this.actions
.get();
7475 this.toggleVerticalActionLayout( false );
7476 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
7477 action
= actions
[ i
];
7478 if ( action
.$element
.innerWidth() < action
.$label
.outerWidth( true ) ) {
7479 this.toggleVerticalActionLayout( true );
7484 // Move the body out of the way of the foot
7485 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
7487 if ( this.verticalActionLayout
!== previous
) {
7488 // We changed the layout, window height might need to be updated.
7494 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
7495 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
7496 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
7497 * relevant. The ProcessDialog class is always extended and customized with the actions and content
7498 * required for each process.
7500 * The process dialog box consists of a header that visually represents the ‘working’ state of long
7501 * processes with an animation. The header contains the dialog title as well as
7502 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
7503 * a ‘primary’ action on the right (e.g., ‘Done’).
7505 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
7506 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
7509 * // Example: Creating and opening a process dialog window.
7510 * function MyProcessDialog( config ) {
7511 * MyProcessDialog.super.call( this, config );
7513 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
7515 * MyProcessDialog.static.title = 'Process dialog';
7516 * MyProcessDialog.static.actions = [
7517 * { action: 'save', label: 'Done', flags: 'primary' },
7518 * { label: 'Cancel', flags: 'safe' }
7521 * MyProcessDialog.prototype.initialize = function () {
7522 * MyProcessDialog.super.prototype.initialize.apply( this, arguments );
7523 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true, expanded: false } );
7524 * 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>' );
7525 * this.$body.append( this.content.$element );
7527 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
7528 * var dialog = this;
7530 * return new OO.ui.Process( function () {
7531 * dialog.close( { action: action } );
7534 * return MyProcessDialog.super.prototype.getActionProcess.call( this, action );
7537 * var windowManager = new OO.ui.WindowManager();
7538 * $( 'body' ).append( windowManager.$element );
7540 * var dialog = new MyProcessDialog();
7541 * windowManager.addWindows( [ dialog ] );
7542 * windowManager.openWindow( dialog );
7544 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
7548 * @extends OO.ui.Dialog
7551 * @param {Object} [config] Configuration options
7553 OO
.ui
.ProcessDialog
= function OoUiProcessDialog( config
) {
7554 // Parent constructor
7555 OO
.ui
.ProcessDialog
.super.call( this, config
);
7558 this.$element
.addClass( 'oo-ui-processDialog' );
7563 OO
.inheritClass( OO
.ui
.ProcessDialog
, OO
.ui
.Dialog
);
7568 * Handle dismiss button click events.
7574 OO
.ui
.ProcessDialog
.prototype.onDismissErrorButtonClick = function () {
7579 * Handle retry button click events.
7581 * Hides errors and then tries again.
7585 OO
.ui
.ProcessDialog
.prototype.onRetryButtonClick = function () {
7587 this.executeAction( this.currentAction
);
7593 OO
.ui
.ProcessDialog
.prototype.onActionResize = function ( action
) {
7594 if ( this.actions
.isSpecial( action
) ) {
7597 return OO
.ui
.ProcessDialog
.super.prototype.onActionResize
.call( this, action
);
7603 OO
.ui
.ProcessDialog
.prototype.initialize = function () {
7605 OO
.ui
.ProcessDialog
.super.prototype.initialize
.call( this );
7608 this.$navigation
= $( '<div>' );
7609 this.$location
= $( '<div>' );
7610 this.$safeActions
= $( '<div>' );
7611 this.$primaryActions
= $( '<div>' );
7612 this.$otherActions
= $( '<div>' );
7613 this.dismissButton
= new OO
.ui
.ButtonWidget( {
7614 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' )
7616 this.retryButton
= new OO
.ui
.ButtonWidget();
7617 this.$errors
= $( '<div>' );
7618 this.$errorsTitle
= $( '<div>' );
7621 this.dismissButton
.connect( this, { click
: 'onDismissErrorButtonClick' } );
7622 this.retryButton
.connect( this, { click
: 'onRetryButtonClick' } );
7625 this.title
.$element
.addClass( 'oo-ui-processDialog-title' );
7627 .append( this.title
.$element
)
7628 .addClass( 'oo-ui-processDialog-location' );
7629 this.$safeActions
.addClass( 'oo-ui-processDialog-actions-safe' );
7630 this.$primaryActions
.addClass( 'oo-ui-processDialog-actions-primary' );
7631 this.$otherActions
.addClass( 'oo-ui-processDialog-actions-other' );
7633 .addClass( 'oo-ui-processDialog-errors-title' )
7634 .text( OO
.ui
.msg( 'ooui-dialog-process-error' ) );
7636 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
7637 .append( this.$errorsTitle
, this.dismissButton
.$element
, this.retryButton
.$element
);
7639 .addClass( 'oo-ui-processDialog-content' )
7640 .append( this.$errors
);
7642 .addClass( 'oo-ui-processDialog-navigation' )
7643 .append( this.$safeActions
, this.$location
, this.$primaryActions
);
7644 this.$head
.append( this.$navigation
);
7645 this.$foot
.append( this.$otherActions
);
7651 OO
.ui
.ProcessDialog
.prototype.getActionWidgets = function ( actions
) {
7652 var i
, len
, widgets
= [];
7653 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
7655 new OO
.ui
.ActionWidget( $.extend( { framed
: true }, actions
[ i
] ) )
7664 OO
.ui
.ProcessDialog
.prototype.attachActions = function () {
7665 var i
, len
, other
, special
, others
;
7668 OO
.ui
.ProcessDialog
.super.prototype.attachActions
.call( this );
7670 special
= this.actions
.getSpecial();
7671 others
= this.actions
.getOthers();
7672 if ( special
.primary
) {
7673 this.$primaryActions
.append( special
.primary
.$element
);
7675 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
7676 other
= others
[ i
];
7677 this.$otherActions
.append( other
.$element
);
7679 if ( special
.safe
) {
7680 this.$safeActions
.append( special
.safe
.$element
);
7684 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
7690 OO
.ui
.ProcessDialog
.prototype.executeAction = function ( action
) {
7692 return OO
.ui
.ProcessDialog
.super.prototype.executeAction
.call( this, action
)
7693 .fail( function ( errors
) {
7694 process
.showErrors( errors
|| [] );
7699 * Fit label between actions.
7704 OO
.ui
.ProcessDialog
.prototype.fitLabel = function () {
7705 var width
= Math
.max(
7706 this.$safeActions
.is( ':visible' ) ? this.$safeActions
.width() : 0,
7707 this.$primaryActions
.is( ':visible' ) ? this.$primaryActions
.width() : 0
7709 this.$location
.css( { paddingLeft
: width
, paddingRight
: width
} );
7715 * Handle errors that occurred during accept or reject processes.
7718 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
7720 OO
.ui
.ProcessDialog
.prototype.showErrors = function ( errors
) {
7721 var i
, len
, $item
, actions
,
7727 if ( errors
instanceof OO
.ui
.Error
) {
7728 errors
= [ errors
];
7731 for ( i
= 0, len
= errors
.length
; i
< len
; i
++ ) {
7732 if ( !errors
[ i
].isRecoverable() ) {
7733 recoverable
= false;
7735 if ( errors
[ i
].isWarning() ) {
7738 $item
= $( '<div>' )
7739 .addClass( 'oo-ui-processDialog-error' )
7740 .append( errors
[ i
].getMessage() );
7741 items
.push( $item
[ 0 ] );
7743 this.$errorItems
= $( items
);
7744 if ( recoverable
) {
7745 abilities
[this.currentAction
] = true;
7746 // Copy the flags from the first matching action
7747 actions
= this.actions
.get( { actions
: this.currentAction
} );
7748 if ( actions
.length
) {
7749 this.retryButton
.clearFlags().setFlags( actions
[0].getFlags() );
7752 abilities
[this.currentAction
] = false;
7753 this.actions
.setAbilities( abilities
);
7756 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-continue' ) );
7758 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-retry' ) );
7760 this.retryButton
.toggle( recoverable
);
7761 this.$errorsTitle
.after( this.$errorItems
);
7762 this.$errors
.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
7770 OO
.ui
.ProcessDialog
.prototype.hideErrors = function () {
7771 this.$errors
.addClass( 'oo-ui-element-hidden' );
7772 if ( this.$errorItems
) {
7773 this.$errorItems
.remove();
7774 this.$errorItems
= null;
7781 OO
.ui
.ProcessDialog
.prototype.getTeardownProcess = function ( data
) {
7783 return OO
.ui
.ProcessDialog
.super.prototype.getTeardownProcess
.call( this, data
)
7784 .first( function () {
7785 // Make sure to hide errors
7791 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
7792 * which is a widget that is specified by reference before any optional configuration settings.
7794 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
7796 * - **left**: The label is placed before the field-widget and aligned with the left margin.
7797 * A left-alignment is used for forms with many fields.
7798 * - **right**: The label is placed before the field-widget and aligned to the right margin.
7799 * A right-alignment is used for long but familiar forms which users tab through,
7800 * verifying the current field with a quick glance at the label.
7801 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
7802 * that users fill out from top to bottom.
7803 * - **inline**: The label is placed after the field-widget and aligned to the left.
7804 * An inline-alignment is best used with checkboxes or radio buttons.
7806 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
7807 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
7809 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
7811 * @extends OO.ui.Layout
7812 * @mixins OO.ui.LabelElement
7815 * @param {OO.ui.Widget} fieldWidget Field widget
7816 * @param {Object} [config] Configuration options
7817 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
7818 * @cfg {string} [help] Help text. When help text is specified, a help icon will appear
7819 * in the upper-right corner of the rendered field.
7821 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
7822 // Allow passing positional parameters inside the config object
7823 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
7824 config
= fieldWidget
;
7825 fieldWidget
= config
.fieldWidget
;
7828 var hasInputWidget
= fieldWidget
instanceof OO
.ui
.InputWidget
;
7830 // Configuration initialization
7831 config
= $.extend( { align
: 'left' }, config
);
7833 // Parent constructor
7834 OO
.ui
.FieldLayout
.super.call( this, config
);
7836 // Mixin constructors
7837 OO
.ui
.LabelElement
.call( this, config
);
7840 this.fieldWidget
= fieldWidget
;
7841 this.$field
= $( '<div>' );
7842 this.$body
= $( '<' + ( hasInputWidget
? 'label' : 'div' ) + '>' );
7844 if ( config
.help
) {
7845 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
7846 classes
: [ 'oo-ui-fieldLayout-help' ],
7851 this.popupButtonWidget
.getPopup().$body
.append(
7853 .text( config
.help
)
7854 .addClass( 'oo-ui-fieldLayout-help-content' )
7856 this.$help
= this.popupButtonWidget
.$element
;
7858 this.$help
= $( [] );
7862 if ( hasInputWidget
) {
7863 this.$label
.on( 'click', this.onLabelClick
.bind( this ) );
7865 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
7869 .addClass( 'oo-ui-fieldLayout' )
7870 .append( this.$help
, this.$body
);
7871 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
7873 .addClass( 'oo-ui-fieldLayout-field' )
7874 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget
.isDisabled() )
7875 .append( this.fieldWidget
.$element
);
7877 this.setAlignment( config
.align
);
7882 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
7883 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.LabelElement
);
7888 * Handle field disable events.
7891 * @param {boolean} value Field is disabled
7893 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
7894 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
7898 * Handle label mouse click events.
7901 * @param {jQuery.Event} e Mouse click event
7903 OO
.ui
.FieldLayout
.prototype.onLabelClick = function () {
7904 this.fieldWidget
.simulateLabelClick();
7909 * Get the widget contained by the field.
7911 * @return {OO.ui.Widget} Field widget
7913 OO
.ui
.FieldLayout
.prototype.getField = function () {
7914 return this.fieldWidget
;
7918 * Set the field alignment mode.
7921 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
7924 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
7925 if ( value
!== this.align
) {
7926 // Default to 'left'
7927 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
7931 if ( value
=== 'inline' ) {
7932 this.$body
.append( this.$field
, this.$label
);
7934 this.$body
.append( this.$label
, this.$field
);
7936 // Set classes. The following classes can be used here:
7937 // * oo-ui-fieldLayout-align-left
7938 // * oo-ui-fieldLayout-align-right
7939 // * oo-ui-fieldLayout-align-top
7940 // * oo-ui-fieldLayout-align-inline
7942 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
7944 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
7952 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
7953 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
7954 * is required and is specified before any optional configuration settings.
7956 * Labels can be aligned in one of four ways:
7958 * - **left**: The label is placed before the field-widget and aligned with the left margin.
7959 * A left-alignment is used for forms with many fields.
7960 * - **right**: The label is placed before the field-widget and aligned to the right margin.
7961 * A right-alignment is used for long but familiar forms which users tab through,
7962 * verifying the current field with a quick glance at the label.
7963 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
7964 * that users fill out from top to bottom.
7965 * - **inline**: The label is placed after the field-widget and aligned to the left.
7966 * An inline-alignment is best used with checkboxes or radio buttons.
7968 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
7969 * text is specified.
7972 * // Example of an ActionFieldLayout
7973 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
7974 * new OO.ui.TextInputWidget( {
7975 * placeholder: 'Field widget'
7977 * new OO.ui.ButtonWidget( {
7981 * label: 'An ActionFieldLayout. This label is aligned top',
7983 * help: 'This is help text'
7987 * $( 'body' ).append( actionFieldLayout.$element );
7991 * @extends OO.ui.FieldLayout
7994 * @param {OO.ui.Widget} fieldWidget Field widget
7995 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
7996 * @param {Object} [config] Configuration options
7997 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
7998 * @cfg {string} [help] Help text. When help text is specified, a help icon will appear in the
7999 * upper-right corner of the rendered field.
8001 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
8002 // Allow passing positional parameters inside the config object
8003 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
8004 config
= fieldWidget
;
8005 fieldWidget
= config
.fieldWidget
;
8006 buttonWidget
= config
.buttonWidget
;
8009 // Configuration initialization
8010 config
= $.extend( { align
: 'left' }, config
);
8012 // Parent constructor
8013 OO
.ui
.ActionFieldLayout
.super.call( this, fieldWidget
, config
);
8016 this.fieldWidget
= fieldWidget
;
8017 this.buttonWidget
= buttonWidget
;
8018 this.$button
= $( '<div>' )
8019 .addClass( 'oo-ui-actionFieldLayout-button' )
8020 .append( this.buttonWidget
.$element
);
8021 this.$input
= $( '<div>' )
8022 .addClass( 'oo-ui-actionFieldLayout-input' )
8023 .append( this.fieldWidget
.$element
);
8025 .addClass( 'oo-ui-actionFieldLayout' )
8026 .append( this.$input
, this.$button
);
8031 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
8034 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
8035 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
8036 * configured with a label as well. For more information and examples,
8037 * please see the [OOjs UI documentation on MediaWiki][1].
8040 * // Example of a fieldset layout
8041 * var input1 = new OO.ui.TextInputWidget( {
8042 * placeholder: 'A text input field'
8045 * var input2 = new OO.ui.TextInputWidget( {
8046 * placeholder: 'A text input field'
8049 * var fieldset = new OO.ui.FieldsetLayout( {
8050 * label: 'Example of a fieldset layout'
8053 * fieldset.addItems( [
8054 * new OO.ui.FieldLayout( input1, {
8055 * label: 'Field One'
8057 * new OO.ui.FieldLayout( input2, {
8058 * label: 'Field Two'
8061 * $( 'body' ).append( fieldset.$element );
8063 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8066 * @extends OO.ui.Layout
8067 * @mixins OO.ui.IconElement
8068 * @mixins OO.ui.LabelElement
8069 * @mixins OO.ui.GroupElement
8072 * @param {Object} [config] Configuration options
8073 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
8075 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
8076 // Configuration initialization
8077 config
= config
|| {};
8079 // Parent constructor
8080 OO
.ui
.FieldsetLayout
.super.call( this, config
);
8082 // Mixin constructors
8083 OO
.ui
.IconElement
.call( this, config
);
8084 OO
.ui
.LabelElement
.call( this, config
);
8085 OO
.ui
.GroupElement
.call( this, config
);
8087 if ( config
.help
) {
8088 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
8089 classes
: [ 'oo-ui-fieldsetLayout-help' ],
8094 this.popupButtonWidget
.getPopup().$body
.append(
8096 .text( config
.help
)
8097 .addClass( 'oo-ui-fieldsetLayout-help-content' )
8099 this.$help
= this.popupButtonWidget
.$element
;
8101 this.$help
= $( [] );
8106 .addClass( 'oo-ui-fieldsetLayout' )
8107 .prepend( this.$help
, this.$icon
, this.$label
, this.$group
);
8108 if ( Array
.isArray( config
.items
) ) {
8109 this.addItems( config
.items
);
8115 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
8116 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.IconElement
);
8117 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.LabelElement
);
8118 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.GroupElement
);
8121 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
8122 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
8123 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
8126 * // Example of a form layout that wraps a fieldset layout
8127 * var input1 = new OO.ui.TextInputWidget( {
8128 * placeholder: 'Username'
8130 * var input2 = new OO.ui.TextInputWidget( {
8131 * placeholder: 'Password',
8134 * var submit = new OO.ui.ButtonInputWidget( {
8138 * var fieldset = new OO.ui.FieldsetLayout( {
8139 * label: 'A form layout'
8141 * fieldset.addItems( [
8142 * new OO.ui.FieldLayout( input1, {
8143 * label: 'Username',
8146 * new OO.ui.FieldLayout( input2, {
8147 * label: 'Password',
8150 * new OO.ui.FieldLayout( submit )
8152 * var form = new OO.ui.FormLayout( {
8153 * items: [ fieldset ],
8154 * action: '/api/formhandler',
8157 * $( 'body' ).append( form.$element );
8160 * @extends OO.ui.Layout
8161 * @mixins OO.ui.GroupElement
8164 * @param {Object} [config] Configuration options
8165 * @cfg {string} [method] HTML form `method` attribute
8166 * @cfg {string} [action] HTML form `action` attribute
8167 * @cfg {string} [enctype] HTML form `enctype` attribute
8168 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
8170 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
8171 // Configuration initialization
8172 config
= config
|| {};
8174 // Parent constructor
8175 OO
.ui
.FormLayout
.super.call( this, config
);
8177 // Mixin constructors
8178 OO
.ui
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
8181 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
8185 .addClass( 'oo-ui-formLayout' )
8187 method
: config
.method
,
8188 action
: config
.action
,
8189 enctype
: config
.enctype
8191 if ( Array
.isArray( config
.items
) ) {
8192 this.addItems( config
.items
);
8198 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
8199 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.GroupElement
);
8204 * A 'submit' event is emitted when the form is submitted.
8209 /* Static Properties */
8211 OO
.ui
.FormLayout
.static.tagName
= 'form';
8216 * Handle form submit events.
8219 * @param {jQuery.Event} e Submit event
8222 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
8223 this.emit( 'submit' );
8228 * Layout with a content and menu area.
8230 * The menu area can be positioned at the top, after, bottom or before. The content area will fill
8231 * all remaining space.
8234 * @extends OO.ui.Layout
8237 * @param {Object} [config] Configuration options
8238 * @cfg {number|string} [menuSize='18em'] Size of menu in pixels or any CSS unit
8239 * @cfg {boolean} [showMenu=true] Show menu
8240 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
8242 OO
.ui
.MenuLayout
= function OoUiMenuLayout( config
) {
8243 var positions
= this.constructor.static.menuPositions
;
8245 // Configuration initialization
8246 config
= config
|| {};
8248 // Parent constructor
8249 OO
.ui
.MenuLayout
.super.call( this, config
);
8252 this.showMenu
= config
.showMenu
!== false;
8253 this.menuSize
= config
.menuSize
|| '18em';
8254 this.menuPosition
= positions
[ config
.menuPosition
] || positions
.before
;
8259 * @property {jQuery}
8261 this.$menu
= $( '<div>' );
8265 * @property {jQuery}
8267 this.$content
= $( '<div>' );
8270 this.toggleMenu( this.showMenu
);
8273 .addClass( 'oo-ui-menuLayout-menu' )
8274 .css( this.menuPosition
.sizeProperty
, this.menuSize
);
8275 this.$content
.addClass( 'oo-ui-menuLayout-content' );
8277 .addClass( 'oo-ui-menuLayout ' + this.menuPosition
.className
)
8278 .append( this.$content
, this.$menu
);
8283 OO
.inheritClass( OO
.ui
.MenuLayout
, OO
.ui
.Layout
);
8285 /* Static Properties */
8287 OO
.ui
.MenuLayout
.static.menuPositions
= {
8289 sizeProperty
: 'height',
8290 className
: 'oo-ui-menuLayout-top'
8293 sizeProperty
: 'width',
8294 className
: 'oo-ui-menuLayout-after'
8297 sizeProperty
: 'height',
8298 className
: 'oo-ui-menuLayout-bottom'
8301 sizeProperty
: 'width',
8302 className
: 'oo-ui-menuLayout-before'
8311 * @param {boolean} showMenu Show menu, omit to toggle
8314 OO
.ui
.MenuLayout
.prototype.toggleMenu = function ( showMenu
) {
8315 showMenu
= showMenu
=== undefined ? !this.showMenu
: !!showMenu
;
8317 if ( this.showMenu
!== showMenu
) {
8318 this.showMenu
= showMenu
;
8326 * Check if menu is visible
8328 * @return {boolean} Menu is visible
8330 OO
.ui
.MenuLayout
.prototype.isMenuVisible = function () {
8331 return this.showMenu
;
8337 * @param {number|string} size Size of menu in pixels or any CSS unit
8340 OO
.ui
.MenuLayout
.prototype.setMenuSize = function ( size
) {
8341 this.menuSize
= size
;
8348 * Update menu and content CSS based on current menu size and visibility
8350 * This method is called internally when size or position is changed.
8352 OO
.ui
.MenuLayout
.prototype.updateSizes = function () {
8353 if ( this.showMenu
) {
8355 .css( this.menuPosition
.sizeProperty
, this.menuSize
)
8356 .css( 'overflow', '' );
8357 // Set offsets on all sides. CSS resets all but one with
8358 // 'important' rules so directionality flips are supported
8359 this.$content
.css( {
8361 right
: this.menuSize
,
8362 bottom
: this.menuSize
,
8367 .css( this.menuPosition
.sizeProperty
, 0 )
8368 .css( 'overflow', 'hidden' );
8369 this.$content
.css( {
8381 * @return {number|string} Menu size
8383 OO
.ui
.MenuLayout
.prototype.getMenuSize = function () {
8384 return this.menuSize
;
8388 * Set menu position.
8390 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
8391 * @throws {Error} If position value is not supported
8394 OO
.ui
.MenuLayout
.prototype.setMenuPosition = function ( position
) {
8395 var positions
= this.constructor.static.menuPositions
;
8397 if ( !positions
[ position
] ) {
8398 throw new Error( 'Cannot set position; unsupported position value: ' + position
);
8401 this.$menu
.css( this.menuPosition
.sizeProperty
, '' );
8402 this.$element
.removeClass( this.menuPosition
.className
);
8404 this.menuPosition
= positions
[ position
];
8407 this.$element
.addClass( this.menuPosition
.className
);
8413 * Get menu position.
8415 * @return {string} Menu position
8417 OO
.ui
.MenuLayout
.prototype.getMenuPosition = function () {
8418 return this.menuPosition
;
8422 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
8423 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
8424 * through the pages and select which one to display. By default, only one page is
8425 * displayed at a time and the outline is hidden. When a user navigates to a new page,
8426 * the booklet layout automatically focuses on the first focusable element, unless the
8427 * default setting is changed. Optionally, booklets can be configured to show
8428 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
8431 * // Example of a BookletLayout that contains two PageLayouts.
8433 * function PageOneLayout( name, config ) {
8434 * PageOneLayout.super.call( this, name, config );
8435 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
8437 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
8438 * PageOneLayout.prototype.setupOutlineItem = function () {
8439 * this.outlineItem.setLabel( 'Page One' );
8442 * function PageTwoLayout( name, config ) {
8443 * PageTwoLayout.super.call( this, name, config );
8444 * this.$element.append( '<p>Second page</p>' );
8446 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
8447 * PageTwoLayout.prototype.setupOutlineItem = function () {
8448 * this.outlineItem.setLabel( 'Page Two' );
8451 * var page1 = new PageOneLayout( 'one' ),
8452 * page2 = new PageTwoLayout( 'two' );
8454 * var booklet = new OO.ui.BookletLayout( {
8458 * booklet.addPages ( [ page1, page2 ] );
8459 * $( 'body' ).append( booklet.$element );
8462 * @extends OO.ui.MenuLayout
8465 * @param {Object} [config] Configuration options
8466 * @cfg {boolean} [continuous=false] Show all pages, one after another
8467 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
8468 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
8469 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
8471 OO
.ui
.BookletLayout
= function OoUiBookletLayout( config
) {
8472 // Configuration initialization
8473 config
= config
|| {};
8475 // Parent constructor
8476 OO
.ui
.BookletLayout
.super.call( this, config
);
8479 this.currentPageName
= null;
8481 this.ignoreFocus
= false;
8482 this.stackLayout
= new OO
.ui
.StackLayout( { continuous
: !!config
.continuous
} );
8483 this.$content
.append( this.stackLayout
.$element
);
8484 this.autoFocus
= config
.autoFocus
=== undefined || !!config
.autoFocus
;
8485 this.outlineVisible
= false;
8486 this.outlined
= !!config
.outlined
;
8487 if ( this.outlined
) {
8488 this.editable
= !!config
.editable
;
8489 this.outlineControlsWidget
= null;
8490 this.outlineSelectWidget
= new OO
.ui
.OutlineSelectWidget();
8491 this.outlinePanel
= new OO
.ui
.PanelLayout( { scrollable
: true } );
8492 this.$menu
.append( this.outlinePanel
.$element
);
8493 this.outlineVisible
= true;
8494 if ( this.editable
) {
8495 this.outlineControlsWidget
= new OO
.ui
.OutlineControlsWidget(
8496 this.outlineSelectWidget
8500 this.toggleMenu( this.outlined
);
8503 this.stackLayout
.connect( this, { set: 'onStackLayoutSet' } );
8504 if ( this.outlined
) {
8505 this.outlineSelectWidget
.connect( this, { select
: 'onOutlineSelectWidgetSelect' } );
8507 if ( this.autoFocus
) {
8508 // Event 'focus' does not bubble, but 'focusin' does
8509 this.stackLayout
.$element
.on( 'focusin', this.onStackLayoutFocus
.bind( this ) );
8513 this.$element
.addClass( 'oo-ui-bookletLayout' );
8514 this.stackLayout
.$element
.addClass( 'oo-ui-bookletLayout-stackLayout' );
8515 if ( this.outlined
) {
8516 this.outlinePanel
.$element
8517 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
8518 .append( this.outlineSelectWidget
.$element
);
8519 if ( this.editable
) {
8520 this.outlinePanel
.$element
8521 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
8522 .append( this.outlineControlsWidget
.$element
);
8529 OO
.inheritClass( OO
.ui
.BookletLayout
, OO
.ui
.MenuLayout
);
8534 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
8536 * @param {OO.ui.PageLayout} page Current page
8540 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
8543 * @param {OO.ui.PageLayout[]} page Added pages
8544 * @param {number} index Index pages were added at
8548 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
8549 * {@link #removePages removed} from the booklet.
8552 * @param {OO.ui.PageLayout[]} pages Removed pages
8558 * Handle stack layout focus.
8561 * @param {jQuery.Event} e Focusin event
8563 OO
.ui
.BookletLayout
.prototype.onStackLayoutFocus = function ( e
) {
8566 // Find the page that an element was focused within
8567 $target
= $( e
.target
).closest( '.oo-ui-pageLayout' );
8568 for ( name
in this.pages
) {
8569 // Check for page match, exclude current page to find only page changes
8570 if ( this.pages
[ name
].$element
[ 0 ] === $target
[ 0 ] && name
!== this.currentPageName
) {
8571 this.setPage( name
);
8578 * Handle stack layout set events.
8581 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
8583 OO
.ui
.BookletLayout
.prototype.onStackLayoutSet = function ( page
) {
8586 page
.scrollElementIntoView( { complete: function () {
8587 if ( layout
.autoFocus
) {
8595 * Focus the first input in the current page.
8597 * If no page is selected, the first selectable page will be selected.
8598 * If the focus is already in an element on the current page, nothing will happen.
8600 OO
.ui
.BookletLayout
.prototype.focus = function () {
8601 var $input
, page
= this.stackLayout
.getCurrentItem();
8602 if ( !page
&& this.outlined
) {
8603 this.selectFirstSelectablePage();
8604 page
= this.stackLayout
.getCurrentItem();
8609 // Only change the focus if is not already in the current page
8610 if ( !page
.$element
.find( ':focus' ).length
) {
8611 $input
= page
.$element
.find( ':input:first' );
8612 if ( $input
.length
) {
8613 $input
[ 0 ].focus();
8619 * Handle outline widget select events.
8622 * @param {OO.ui.OptionWidget|null} item Selected item
8624 OO
.ui
.BookletLayout
.prototype.onOutlineSelectWidgetSelect = function ( item
) {
8626 this.setPage( item
.getData() );
8631 * Check if booklet has an outline.
8633 * @return {boolean} Booklet has an outline
8635 OO
.ui
.BookletLayout
.prototype.isOutlined = function () {
8636 return this.outlined
;
8640 * Check if booklet has editing controls.
8642 * @return {boolean} Booklet is editable
8644 OO
.ui
.BookletLayout
.prototype.isEditable = function () {
8645 return this.editable
;
8649 * Check if booklet has a visible outline.
8651 * @return {boolean} Outline is visible
8653 OO
.ui
.BookletLayout
.prototype.isOutlineVisible = function () {
8654 return this.outlined
&& this.outlineVisible
;
8658 * Hide or show the outline.
8660 * @param {boolean} [show] Show outline, omit to invert current state
8663 OO
.ui
.BookletLayout
.prototype.toggleOutline = function ( show
) {
8664 if ( this.outlined
) {
8665 show
= show
=== undefined ? !this.outlineVisible
: !!show
;
8666 this.outlineVisible
= show
;
8667 this.toggleMenu( show
);
8674 * Get the page closest to the specified page.
8676 * @param {OO.ui.PageLayout} page Page to use as a reference point
8677 * @return {OO.ui.PageLayout|null} Page closest to the specified page
8679 OO
.ui
.BookletLayout
.prototype.getClosestPage = function ( page
) {
8680 var next
, prev
, level
,
8681 pages
= this.stackLayout
.getItems(),
8682 index
= $.inArray( page
, pages
);
8684 if ( index
!== -1 ) {
8685 next
= pages
[ index
+ 1 ];
8686 prev
= pages
[ index
- 1 ];
8687 // Prefer adjacent pages at the same level
8688 if ( this.outlined
) {
8689 level
= this.outlineSelectWidget
.getItemFromData( page
.getName() ).getLevel();
8692 level
=== this.outlineSelectWidget
.getItemFromData( prev
.getName() ).getLevel()
8698 level
=== this.outlineSelectWidget
.getItemFromData( next
.getName() ).getLevel()
8704 return prev
|| next
|| null;
8708 * Get the outline widget.
8710 * If the booklet is not outlined, the method will return `null`.
8712 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
8714 OO
.ui
.BookletLayout
.prototype.getOutline = function () {
8715 return this.outlineSelectWidget
;
8719 * Get the outline controls widget.
8721 * If the outline is not editable, the method will return `null`.
8723 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
8725 OO
.ui
.BookletLayout
.prototype.getOutlineControls = function () {
8726 return this.outlineControlsWidget
;
8730 * Get a page by its symbolic name.
8732 * @param {string} name Symbolic name of page
8733 * @return {OO.ui.PageLayout|undefined} Page, if found
8735 OO
.ui
.BookletLayout
.prototype.getPage = function ( name
) {
8736 return this.pages
[ name
];
8740 * Get the current page.
8742 * @return {OO.ui.PageLayout|undefined} Current page, if found
8744 OO
.ui
.BookletLayout
.prototype.getCurrentPage = function () {
8745 var name
= this.getCurrentPageName();
8746 return name
? this.getPage( name
) : undefined;
8750 * Get the symbolic name of the current page.
8752 * @return {string|null} Symbolic name of the current page
8754 OO
.ui
.BookletLayout
.prototype.getCurrentPageName = function () {
8755 return this.currentPageName
;
8759 * Add pages to the booklet layout
8761 * When pages are added with the same names as existing pages, the existing pages will be
8762 * automatically removed before the new pages are added.
8764 * @param {OO.ui.PageLayout[]} pages Pages to add
8765 * @param {number} index Index of the insertion point
8769 OO
.ui
.BookletLayout
.prototype.addPages = function ( pages
, index
) {
8770 var i
, len
, name
, page
, item
, currentIndex
,
8771 stackLayoutPages
= this.stackLayout
.getItems(),
8775 // Remove pages with same names
8776 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
8778 name
= page
.getName();
8780 if ( Object
.prototype.hasOwnProperty
.call( this.pages
, name
) ) {
8781 // Correct the insertion index
8782 currentIndex
= $.inArray( this.pages
[ name
], stackLayoutPages
);
8783 if ( currentIndex
!== -1 && currentIndex
+ 1 < index
) {
8786 remove
.push( this.pages
[ name
] );
8789 if ( remove
.length
) {
8790 this.removePages( remove
);
8794 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
8796 name
= page
.getName();
8797 this.pages
[ page
.getName() ] = page
;
8798 if ( this.outlined
) {
8799 item
= new OO
.ui
.OutlineOptionWidget( { data
: name
} );
8800 page
.setOutlineItem( item
);
8805 if ( this.outlined
&& items
.length
) {
8806 this.outlineSelectWidget
.addItems( items
, index
);
8807 this.selectFirstSelectablePage();
8809 this.stackLayout
.addItems( pages
, index
);
8810 this.emit( 'add', pages
, index
);
8816 * Remove the specified pages from the booklet layout.
8818 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
8820 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
8824 OO
.ui
.BookletLayout
.prototype.removePages = function ( pages
) {
8825 var i
, len
, name
, page
,
8828 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
8830 name
= page
.getName();
8831 delete this.pages
[ name
];
8832 if ( this.outlined
) {
8833 items
.push( this.outlineSelectWidget
.getItemFromData( name
) );
8834 page
.setOutlineItem( null );
8837 if ( this.outlined
&& items
.length
) {
8838 this.outlineSelectWidget
.removeItems( items
);
8839 this.selectFirstSelectablePage();
8841 this.stackLayout
.removeItems( pages
);
8842 this.emit( 'remove', pages
);
8848 * Clear all pages from the booklet layout.
8850 * To remove only a subset of pages from the booklet, use the #removePages method.
8855 OO
.ui
.BookletLayout
.prototype.clearPages = function () {
8857 pages
= this.stackLayout
.getItems();
8860 this.currentPageName
= null;
8861 if ( this.outlined
) {
8862 this.outlineSelectWidget
.clearItems();
8863 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
8864 pages
[ i
].setOutlineItem( null );
8867 this.stackLayout
.clearItems();
8869 this.emit( 'remove', pages
);
8875 * Set the current page by symbolic name.
8878 * @param {string} name Symbolic name of page
8880 OO
.ui
.BookletLayout
.prototype.setPage = function ( name
) {
8883 page
= this.pages
[ name
];
8885 if ( name
!== this.currentPageName
) {
8886 if ( this.outlined
) {
8887 selectedItem
= this.outlineSelectWidget
.getSelectedItem();
8888 if ( selectedItem
&& selectedItem
.getData() !== name
) {
8889 this.outlineSelectWidget
.selectItem( this.outlineSelectWidget
.getItemFromData( name
) );
8893 if ( this.currentPageName
&& this.pages
[ this.currentPageName
] ) {
8894 this.pages
[ this.currentPageName
].setActive( false );
8895 // Blur anything focused if the next page doesn't have anything focusable - this
8896 // is not needed if the next page has something focusable because once it is focused
8897 // this blur happens automatically
8898 if ( this.autoFocus
&& !page
.$element
.find( ':input' ).length
) {
8899 $focused
= this.pages
[ this.currentPageName
].$element
.find( ':focus' );
8900 if ( $focused
.length
) {
8901 $focused
[ 0 ].blur();
8905 this.currentPageName
= name
;
8906 this.stackLayout
.setItem( page
);
8907 page
.setActive( true );
8908 this.emit( 'set', page
);
8914 * Select the first selectable page.
8918 OO
.ui
.BookletLayout
.prototype.selectFirstSelectablePage = function () {
8919 if ( !this.outlineSelectWidget
.getSelectedItem() ) {
8920 this.outlineSelectWidget
.selectItem( this.outlineSelectWidget
.getFirstSelectableItem() );
8927 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
8928 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
8931 * // Example of a panel layout
8932 * var panel = new OO.ui.PanelLayout( {
8936 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
8938 * $( 'body' ).append( panel.$element );
8941 * @extends OO.ui.Layout
8944 * @param {Object} [config] Configuration options
8945 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
8946 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
8947 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
8948 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
8950 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
8951 // Configuration initialization
8952 config
= $.extend( {
8959 // Parent constructor
8960 OO
.ui
.PanelLayout
.super.call( this, config
);
8963 this.$element
.addClass( 'oo-ui-panelLayout' );
8964 if ( config
.scrollable
) {
8965 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
8967 if ( config
.padded
) {
8968 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
8970 if ( config
.expanded
) {
8971 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
8973 if ( config
.framed
) {
8974 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
8980 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
8983 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
8984 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
8985 * rather extended to include the required content and functionality.
8987 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
8988 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
8989 * {@link OO.ui.BookletLayout BookletLayout} for an example.
8992 * @extends OO.ui.PanelLayout
8995 * @param {string} name Unique symbolic name of page
8996 * @param {Object} [config] Configuration options
8998 OO
.ui
.PageLayout
= function OoUiPageLayout( name
, config
) {
8999 // Allow passing positional parameters inside the config object
9000 if ( OO
.isPlainObject( name
) && config
=== undefined ) {
9005 // Configuration initialization
9006 config
= $.extend( { scrollable
: true }, config
);
9008 // Parent constructor
9009 OO
.ui
.PageLayout
.super.call( this, config
);
9013 this.outlineItem
= null;
9014 this.active
= false;
9017 this.$element
.addClass( 'oo-ui-pageLayout' );
9022 OO
.inheritClass( OO
.ui
.PageLayout
, OO
.ui
.PanelLayout
);
9027 * An 'active' event is emitted when the page becomes active. Pages become active when they are
9028 * shown in a booklet layout that is configured to display only one page at a time.
9031 * @param {boolean} active Page is active
9037 * Get the symbolic name of the page.
9039 * @return {string} Symbolic name of page
9041 OO
.ui
.PageLayout
.prototype.getName = function () {
9046 * Check if page is active.
9048 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
9049 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
9051 * @return {boolean} Page is active
9053 OO
.ui
.PageLayout
.prototype.isActive = function () {
9060 * The outline item allows users to access the page from the booklet's outline
9061 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
9063 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
9065 OO
.ui
.PageLayout
.prototype.getOutlineItem = function () {
9066 return this.outlineItem
;
9070 * Set or unset the outline item.
9072 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
9073 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
9074 * level), use #setupOutlineItem instead of this method.
9076 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
9079 OO
.ui
.PageLayout
.prototype.setOutlineItem = function ( outlineItem
) {
9080 this.outlineItem
= outlineItem
|| null;
9081 if ( outlineItem
) {
9082 this.setupOutlineItem();
9088 * Set up the outline item.
9090 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
9091 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
9092 * the #setOutlineItem method instead.
9094 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
9097 OO
.ui
.PageLayout
.prototype.setupOutlineItem = function () {
9102 * Set the page to its 'active' state.
9104 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
9105 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
9106 * context, setting the active state on a page does nothing.
9108 * @param {boolean} value Page is active
9111 OO
.ui
.PageLayout
.prototype.setActive = function ( active
) {
9114 if ( active
!== this.active
) {
9115 this.active
= active
;
9116 this.$element
.toggleClass( 'oo-ui-pageLayout-active', active
);
9117 this.emit( 'active', this.active
);
9122 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
9123 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
9124 * by setting the #continuous option to 'true'.
9127 * // A stack layout with two panels, configured to be displayed continously
9128 * var myStack = new OO.ui.StackLayout( {
9130 * new OO.ui.PanelLayout( {
9131 * $content: $( '<p>Panel One</p>' ),
9135 * new OO.ui.PanelLayout( {
9136 * $content: $( '<p>Panel Two</p>' ),
9143 * $( 'body' ).append( myStack.$element );
9146 * @extends OO.ui.PanelLayout
9147 * @mixins OO.ui.GroupElement
9150 * @param {Object} [config] Configuration options
9151 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
9152 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
9154 OO
.ui
.StackLayout
= function OoUiStackLayout( config
) {
9155 // Configuration initialization
9156 config
= $.extend( { scrollable
: true }, config
);
9158 // Parent constructor
9159 OO
.ui
.StackLayout
.super.call( this, config
);
9161 // Mixin constructors
9162 OO
.ui
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
9165 this.currentItem
= null;
9166 this.continuous
= !!config
.continuous
;
9169 this.$element
.addClass( 'oo-ui-stackLayout' );
9170 if ( this.continuous
) {
9171 this.$element
.addClass( 'oo-ui-stackLayout-continuous' );
9173 if ( Array
.isArray( config
.items
) ) {
9174 this.addItems( config
.items
);
9180 OO
.inheritClass( OO
.ui
.StackLayout
, OO
.ui
.PanelLayout
);
9181 OO
.mixinClass( OO
.ui
.StackLayout
, OO
.ui
.GroupElement
);
9186 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
9187 * {@link #clearItems cleared} or {@link #setItem displayed}.
9190 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
9196 * Get the current panel.
9198 * @return {OO.ui.Layout|null}
9200 OO
.ui
.StackLayout
.prototype.getCurrentItem = function () {
9201 return this.currentItem
;
9205 * Unset the current item.
9208 * @param {OO.ui.StackLayout} layout
9211 OO
.ui
.StackLayout
.prototype.unsetCurrentItem = function () {
9212 var prevItem
= this.currentItem
;
9213 if ( prevItem
=== null ) {
9217 this.currentItem
= null;
9218 this.emit( 'set', null );
9222 * Add panel layouts to the stack layout.
9224 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
9225 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
9228 * @param {OO.ui.Layout[]} items Panels to add
9229 * @param {number} [index] Index of the insertion point
9232 OO
.ui
.StackLayout
.prototype.addItems = function ( items
, index
) {
9233 // Update the visibility
9234 this.updateHiddenState( items
, this.currentItem
);
9237 OO
.ui
.GroupElement
.prototype.addItems
.call( this, items
, index
);
9239 if ( !this.currentItem
&& items
.length
) {
9240 this.setItem( items
[ 0 ] );
9247 * Remove the specified panels from the stack layout.
9249 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
9250 * you may wish to use the #clearItems method instead.
9252 * @param {OO.ui.Layout[]} items Panels to remove
9256 OO
.ui
.StackLayout
.prototype.removeItems = function ( items
) {
9258 OO
.ui
.GroupElement
.prototype.removeItems
.call( this, items
);
9260 if ( $.inArray( this.currentItem
, items
) !== -1 ) {
9261 if ( this.items
.length
) {
9262 this.setItem( this.items
[ 0 ] );
9264 this.unsetCurrentItem();
9272 * Clear all panels from the stack layout.
9274 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
9275 * a subset of panels, use the #removeItems method.
9280 OO
.ui
.StackLayout
.prototype.clearItems = function () {
9281 this.unsetCurrentItem();
9282 OO
.ui
.GroupElement
.prototype.clearItems
.call( this );
9288 * Show the specified panel.
9290 * If another panel is currently displayed, it will be hidden.
9292 * @param {OO.ui.Layout} item Panel to show
9296 OO
.ui
.StackLayout
.prototype.setItem = function ( item
) {
9297 if ( item
!== this.currentItem
) {
9298 this.updateHiddenState( this.items
, item
);
9300 if ( $.inArray( item
, this.items
) !== -1 ) {
9301 this.currentItem
= item
;
9302 this.emit( 'set', item
);
9304 this.unsetCurrentItem();
9312 * Update the visibility of all items in case of non-continuous view.
9314 * Ensure all items are hidden except for the selected one.
9315 * This method does nothing when the stack is continuous.
9318 * @param {OO.ui.Layout[]} items Item list iterate over
9319 * @param {OO.ui.Layout} [selectedItem] Selected item to show
9321 OO
.ui
.StackLayout
.prototype.updateHiddenState = function ( items
, selectedItem
) {
9324 if ( !this.continuous
) {
9325 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
9326 if ( !selectedItem
|| selectedItem
!== items
[ i
] ) {
9327 items
[ i
].$element
.addClass( 'oo-ui-element-hidden' );
9330 if ( selectedItem
) {
9331 selectedItem
.$element
.removeClass( 'oo-ui-element-hidden' );
9337 * Horizontal bar layout of tools as icon buttons.
9340 * @extends OO.ui.ToolGroup
9343 * @param {OO.ui.Toolbar} toolbar
9344 * @param {Object} [config] Configuration options
9346 OO
.ui
.BarToolGroup
= function OoUiBarToolGroup( toolbar
, config
) {
9347 // Allow passing positional parameters inside the config object
9348 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
9350 toolbar
= config
.toolbar
;
9353 // Parent constructor
9354 OO
.ui
.BarToolGroup
.super.call( this, toolbar
, config
);
9357 this.$element
.addClass( 'oo-ui-barToolGroup' );
9362 OO
.inheritClass( OO
.ui
.BarToolGroup
, OO
.ui
.ToolGroup
);
9364 /* Static Properties */
9366 OO
.ui
.BarToolGroup
.static.titleTooltips
= true;
9368 OO
.ui
.BarToolGroup
.static.accelTooltips
= true;
9370 OO
.ui
.BarToolGroup
.static.name
= 'bar';
9373 * Popup list of tools with an icon and optional label.
9377 * @extends OO.ui.ToolGroup
9378 * @mixins OO.ui.IconElement
9379 * @mixins OO.ui.IndicatorElement
9380 * @mixins OO.ui.LabelElement
9381 * @mixins OO.ui.TitledElement
9382 * @mixins OO.ui.ClippableElement
9385 * @param {OO.ui.Toolbar} toolbar
9386 * @param {Object} [config] Configuration options
9387 * @cfg {string} [header] Text to display at the top of the pop-up
9389 OO
.ui
.PopupToolGroup
= function OoUiPopupToolGroup( toolbar
, config
) {
9390 // Allow passing positional parameters inside the config object
9391 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
9393 toolbar
= config
.toolbar
;
9396 // Configuration initialization
9397 config
= config
|| {};
9399 // Parent constructor
9400 OO
.ui
.PopupToolGroup
.super.call( this, toolbar
, config
);
9402 // Mixin constructors
9403 OO
.ui
.IconElement
.call( this, config
);
9404 OO
.ui
.IndicatorElement
.call( this, config
);
9405 OO
.ui
.LabelElement
.call( this, config
);
9406 OO
.ui
.TitledElement
.call( this, config
);
9407 OO
.ui
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
9410 this.active
= false;
9411 this.dragging
= false;
9412 this.onBlurHandler
= this.onBlur
.bind( this );
9413 this.$handle
= $( '<span>' );
9417 mousedown
: this.onHandlePointerDown
.bind( this ),
9418 mouseup
: this.onHandlePointerUp
.bind( this )
9423 .addClass( 'oo-ui-popupToolGroup-handle' )
9424 .append( this.$icon
, this.$label
, this.$indicator
);
9425 // If the pop-up should have a header, add it to the top of the toolGroup.
9426 // Note: If this feature is useful for other widgets, we could abstract it into an
9427 // OO.ui.HeaderedElement mixin constructor.
9428 if ( config
.header
!== undefined ) {
9430 .prepend( $( '<span>' )
9431 .addClass( 'oo-ui-popupToolGroup-header' )
9432 .text( config
.header
)
9436 .addClass( 'oo-ui-popupToolGroup' )
9437 .prepend( this.$handle
);
9442 OO
.inheritClass( OO
.ui
.PopupToolGroup
, OO
.ui
.ToolGroup
);
9443 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.IconElement
);
9444 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.IndicatorElement
);
9445 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.LabelElement
);
9446 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.TitledElement
);
9447 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.ClippableElement
);
9449 /* Static Properties */
9456 OO
.ui
.PopupToolGroup
.prototype.setDisabled = function () {
9458 OO
.ui
.PopupToolGroup
.super.prototype.setDisabled
.apply( this, arguments
);
9460 if ( this.isDisabled() && this.isElementAttached() ) {
9461 this.setActive( false );
9466 * Handle focus being lost.
9468 * The event is actually generated from a mouseup, so it is not a normal blur event object.
9470 * @param {jQuery.Event} e Mouse up event
9472 OO
.ui
.PopupToolGroup
.prototype.onBlur = function ( e
) {
9473 // Only deactivate when clicking outside the dropdown element
9474 if ( $( e
.target
).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element
[ 0 ] ) {
9475 this.setActive( false );
9482 OO
.ui
.PopupToolGroup
.prototype.onPointerUp = function ( e
) {
9483 // Only close toolgroup when a tool was actually selected
9484 if ( !this.isDisabled() && e
.which
=== 1 && this.pressed
&& this.pressed
=== this.getTargetTool( e
) ) {
9485 this.setActive( false );
9487 return OO
.ui
.PopupToolGroup
.super.prototype.onPointerUp
.call( this, e
);
9491 * Handle mouse up events.
9493 * @param {jQuery.Event} e Mouse up event
9495 OO
.ui
.PopupToolGroup
.prototype.onHandlePointerUp = function () {
9500 * Handle mouse down events.
9502 * @param {jQuery.Event} e Mouse down event
9504 OO
.ui
.PopupToolGroup
.prototype.onHandlePointerDown = function ( e
) {
9505 if ( !this.isDisabled() && e
.which
=== 1 ) {
9506 this.setActive( !this.active
);
9512 * Switch into active mode.
9514 * When active, mouseup events anywhere in the document will trigger deactivation.
9516 OO
.ui
.PopupToolGroup
.prototype.setActive = function ( value
) {
9518 if ( this.active
!== value
) {
9519 this.active
= value
;
9521 this.getElementDocument().addEventListener( 'mouseup', this.onBlurHandler
, true );
9523 // Try anchoring the popup to the left first
9524 this.$element
.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
9525 this.toggleClipping( true );
9526 if ( this.isClippedHorizontally() ) {
9527 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
9528 this.toggleClipping( false );
9530 .removeClass( 'oo-ui-popupToolGroup-left' )
9531 .addClass( 'oo-ui-popupToolGroup-right' );
9532 this.toggleClipping( true );
9535 this.getElementDocument().removeEventListener( 'mouseup', this.onBlurHandler
, true );
9536 this.$element
.removeClass(
9537 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
9539 this.toggleClipping( false );
9545 * Drop down list layout of tools as labeled icon buttons.
9547 * This layout allows some tools to be collapsible, controlled by a "More" / "Fewer" option at the
9548 * bottom of the main list. These are not automatically positioned at the bottom of the list; you
9549 * may want to use the 'promote' and 'demote' configuration options to achieve this.
9552 * @extends OO.ui.PopupToolGroup
9555 * @param {OO.ui.Toolbar} toolbar
9556 * @param {Object} [config] Configuration options
9557 * @cfg {Array} [allowCollapse] List of tools that can be collapsed. Remaining tools will be always
9559 * @cfg {Array} [forceExpand] List of tools that *may not* be collapsed. All remaining tools will be
9560 * allowed to be collapsed.
9561 * @cfg {boolean} [expanded=false] Whether the collapsible tools are expanded by default
9563 OO
.ui
.ListToolGroup
= function OoUiListToolGroup( toolbar
, config
) {
9564 // Allow passing positional parameters inside the config object
9565 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
9567 toolbar
= config
.toolbar
;
9570 // Configuration initialization
9571 config
= config
|| {};
9573 // Properties (must be set before parent constructor, which calls #populate)
9574 this.allowCollapse
= config
.allowCollapse
;
9575 this.forceExpand
= config
.forceExpand
;
9576 this.expanded
= config
.expanded
!== undefined ? config
.expanded
: false;
9577 this.collapsibleTools
= [];
9579 // Parent constructor
9580 OO
.ui
.ListToolGroup
.super.call( this, toolbar
, config
);
9583 this.$element
.addClass( 'oo-ui-listToolGroup' );
9588 OO
.inheritClass( OO
.ui
.ListToolGroup
, OO
.ui
.PopupToolGroup
);
9590 /* Static Properties */
9592 OO
.ui
.ListToolGroup
.static.accelTooltips
= true;
9594 OO
.ui
.ListToolGroup
.static.name
= 'list';
9601 OO
.ui
.ListToolGroup
.prototype.populate = function () {
9602 var i
, len
, allowCollapse
= [];
9604 OO
.ui
.ListToolGroup
.super.prototype.populate
.call( this );
9606 // Update the list of collapsible tools
9607 if ( this.allowCollapse
!== undefined ) {
9608 allowCollapse
= this.allowCollapse
;
9609 } else if ( this.forceExpand
!== undefined ) {
9610 allowCollapse
= OO
.simpleArrayDifference( Object
.keys( this.tools
), this.forceExpand
);
9613 this.collapsibleTools
= [];
9614 for ( i
= 0, len
= allowCollapse
.length
; i
< len
; i
++ ) {
9615 if ( this.tools
[ allowCollapse
[ i
] ] !== undefined ) {
9616 this.collapsibleTools
.push( this.tools
[ allowCollapse
[ i
] ] );
9620 // Keep at the end, even when tools are added
9621 this.$group
.append( this.getExpandCollapseTool().$element
);
9623 this.getExpandCollapseTool().toggle( this.collapsibleTools
.length
!== 0 );
9624 this.updateCollapsibleState();
9627 OO
.ui
.ListToolGroup
.prototype.getExpandCollapseTool = function () {
9628 if ( this.expandCollapseTool
=== undefined ) {
9629 var ExpandCollapseTool = function () {
9630 ExpandCollapseTool
.super.apply( this, arguments
);
9633 OO
.inheritClass( ExpandCollapseTool
, OO
.ui
.Tool
);
9635 ExpandCollapseTool
.prototype.onSelect = function () {
9636 this.toolGroup
.expanded
= !this.toolGroup
.expanded
;
9637 this.toolGroup
.updateCollapsibleState();
9638 this.setActive( false );
9640 ExpandCollapseTool
.prototype.onUpdateState = function () {
9641 // Do nothing. Tool interface requires an implementation of this function.
9644 ExpandCollapseTool
.static.name
= 'more-fewer';
9646 this.expandCollapseTool
= new ExpandCollapseTool( this );
9648 return this.expandCollapseTool
;
9654 OO
.ui
.ListToolGroup
.prototype.onPointerUp = function ( e
) {
9655 var ret
= OO
.ui
.ListToolGroup
.super.prototype.onPointerUp
.call( this, e
);
9657 // Do not close the popup when the user wants to show more/fewer tools
9658 if ( $( e
.target
).closest( '.oo-ui-tool-name-more-fewer' ).length
) {
9659 // Prevent the popup list from being hidden
9660 this.setActive( true );
9666 OO
.ui
.ListToolGroup
.prototype.updateCollapsibleState = function () {
9669 this.getExpandCollapseTool()
9670 .setIcon( this.expanded
? 'collapse' : 'expand' )
9671 .setTitle( OO
.ui
.msg( this.expanded
? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
9673 for ( i
= 0, len
= this.collapsibleTools
.length
; i
< len
; i
++ ) {
9674 this.collapsibleTools
[ i
].toggle( this.expanded
);
9679 * Drop down menu layout of tools as selectable menu items.
9682 * @extends OO.ui.PopupToolGroup
9685 * @param {OO.ui.Toolbar} toolbar
9686 * @param {Object} [config] Configuration options
9688 OO
.ui
.MenuToolGroup
= function OoUiMenuToolGroup( toolbar
, config
) {
9689 // Allow passing positional parameters inside the config object
9690 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
9692 toolbar
= config
.toolbar
;
9695 // Configuration initialization
9696 config
= config
|| {};
9698 // Parent constructor
9699 OO
.ui
.MenuToolGroup
.super.call( this, toolbar
, config
);
9702 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
9705 this.$element
.addClass( 'oo-ui-menuToolGroup' );
9710 OO
.inheritClass( OO
.ui
.MenuToolGroup
, OO
.ui
.PopupToolGroup
);
9712 /* Static Properties */
9714 OO
.ui
.MenuToolGroup
.static.accelTooltips
= true;
9716 OO
.ui
.MenuToolGroup
.static.name
= 'menu';
9721 * Handle the toolbar state being updated.
9723 * When the state changes, the title of each active item in the menu will be joined together and
9724 * used as a label for the group. The label will be empty if none of the items are active.
9726 OO
.ui
.MenuToolGroup
.prototype.onUpdateState = function () {
9730 for ( name
in this.tools
) {
9731 if ( this.tools
[ name
].isActive() ) {
9732 labelTexts
.push( this.tools
[ name
].getTitle() );
9736 this.setLabel( labelTexts
.join( ', ' ) || ' ' );
9740 * Tool that shows a popup when selected.
9744 * @extends OO.ui.Tool
9745 * @mixins OO.ui.PopupElement
9748 * @param {OO.ui.ToolGroup} toolGroup
9749 * @param {Object} [config] Configuration options
9751 OO
.ui
.PopupTool
= function OoUiPopupTool( toolGroup
, config
) {
9752 // Allow passing positional parameters inside the config object
9753 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
9755 toolGroup
= config
.toolGroup
;
9758 // Parent constructor
9759 OO
.ui
.PopupTool
.super.call( this, toolGroup
, config
);
9761 // Mixin constructors
9762 OO
.ui
.PopupElement
.call( this, config
);
9766 .addClass( 'oo-ui-popupTool' )
9767 .append( this.popup
.$element
);
9772 OO
.inheritClass( OO
.ui
.PopupTool
, OO
.ui
.Tool
);
9773 OO
.mixinClass( OO
.ui
.PopupTool
, OO
.ui
.PopupElement
);
9778 * Handle the tool being selected.
9782 OO
.ui
.PopupTool
.prototype.onSelect = function () {
9783 if ( !this.isDisabled() ) {
9784 this.popup
.toggle();
9786 this.setActive( false );
9791 * Handle the toolbar state being updated.
9795 OO
.ui
.PopupTool
.prototype.onUpdateState = function () {
9796 this.setActive( false );
9800 * Tool that has a tool group inside. This is a bad workaround for the lack of proper hierarchical
9801 * menus in toolbars (T74159).
9805 * @extends OO.ui.Tool
9808 * @param {OO.ui.ToolGroup} toolGroup
9809 * @param {Object} [config] Configuration options
9811 OO
.ui
.ToolGroupTool
= function OoUiToolGroupTool( toolGroup
, config
) {
9812 // Allow passing positional parameters inside the config object
9813 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
9815 toolGroup
= config
.toolGroup
;
9818 // Parent constructor
9819 OO
.ui
.ToolGroupTool
.super.call( this, toolGroup
, config
);
9822 this.innerToolGroup
= this.createGroup( this.constructor.static.groupConfig
);
9825 this.$link
.remove();
9827 .addClass( 'oo-ui-toolGroupTool' )
9828 .append( this.innerToolGroup
.$element
);
9833 OO
.inheritClass( OO
.ui
.ToolGroupTool
, OO
.ui
.Tool
);
9835 /* Static Properties */
9838 * Tool group configuration. See OO.ui.Toolbar#setup for the accepted values.
9840 * @property {Object.<string,Array>}
9842 OO
.ui
.ToolGroupTool
.static.groupConfig
= {};
9847 * Handle the tool being selected.
9851 OO
.ui
.ToolGroupTool
.prototype.onSelect = function () {
9852 this.innerToolGroup
.setActive( !this.innerToolGroup
.active
);
9857 * Handle the toolbar state being updated.
9861 OO
.ui
.ToolGroupTool
.prototype.onUpdateState = function () {
9862 this.setActive( false );
9866 * Build a OO.ui.ToolGroup from the configuration.
9868 * @param {Object.<string,Array>} group Tool group configuration. See OO.ui.Toolbar#setup for the
9870 * @return {OO.ui.ListToolGroup}
9872 OO
.ui
.ToolGroupTool
.prototype.createGroup = function ( group
) {
9873 if ( group
.include
=== '*' ) {
9874 // Apply defaults to catch-all groups
9875 if ( group
.label
=== undefined ) {
9876 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
9880 return this.toolbar
.getToolGroupFactory().create( 'list', this.toolbar
, group
);
9884 * Mixin for OO.ui.Widget subclasses to provide OO.ui.GroupElement.
9886 * Use together with OO.ui.ItemWidget to make disabled state inheritable.
9891 * @extends OO.ui.GroupElement
9894 * @param {Object} [config] Configuration options
9896 OO
.ui
.GroupWidget
= function OoUiGroupWidget( config
) {
9897 // Parent constructor
9898 OO
.ui
.GroupWidget
.super.call( this, config
);
9903 OO
.inheritClass( OO
.ui
.GroupWidget
, OO
.ui
.GroupElement
);
9908 * Set the disabled state of the widget.
9910 * This will also update the disabled state of child widgets.
9912 * @param {boolean} disabled Disable widget
9915 OO
.ui
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
9919 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
9920 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
9922 // During construction, #setDisabled is called before the OO.ui.GroupElement constructor
9924 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
9925 this.items
[ i
].updateDisabled();
9933 * Mixin for widgets used as items in widgets that inherit OO.ui.GroupWidget.
9935 * Item widgets have a reference to a OO.ui.GroupWidget while they are attached to the group. This
9936 * allows bidirectional communication.
9938 * Use together with OO.ui.GroupWidget to make disabled state inheritable.
9946 OO
.ui
.ItemWidget
= function OoUiItemWidget() {
9953 * Check if widget is disabled.
9955 * Checks parent if present, making disabled state inheritable.
9957 * @return {boolean} Widget is disabled
9959 OO
.ui
.ItemWidget
.prototype.isDisabled = function () {
9960 return this.disabled
||
9961 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
9965 * Set group element is in.
9967 * @param {OO.ui.GroupElement|null} group Group element, null if none
9970 OO
.ui
.ItemWidget
.prototype.setElementGroup = function ( group
) {
9972 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
9973 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
9975 // Initialize item disabled states
9976 this.updateDisabled();
9982 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
9983 * Controls include moving items up and down, removing items, and adding different kinds of items.
9984 * ####Currently, this class is only used by {@link OO.ui.BookletLayout BookletLayouts}.####
9987 * @extends OO.ui.Widget
9988 * @mixins OO.ui.GroupElement
9989 * @mixins OO.ui.IconElement
9992 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
9993 * @param {Object} [config] Configuration options
9994 * @cfg {Object} [abilities] List of abilties
9995 * @cfg {boolean} [abilities.move=true] Allow moving movable items
9996 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
9998 OO
.ui
.OutlineControlsWidget
= function OoUiOutlineControlsWidget( outline
, config
) {
9999 // Allow passing positional parameters inside the config object
10000 if ( OO
.isPlainObject( outline
) && config
=== undefined ) {
10002 outline
= config
.outline
;
10005 // Configuration initialization
10006 config
= $.extend( { icon
: 'add' }, config
);
10008 // Parent constructor
10009 OO
.ui
.OutlineControlsWidget
.super.call( this, config
);
10011 // Mixin constructors
10012 OO
.ui
.GroupElement
.call( this, config
);
10013 OO
.ui
.IconElement
.call( this, config
);
10016 this.outline
= outline
;
10017 this.$movers
= $( '<div>' );
10018 this.upButton
= new OO
.ui
.ButtonWidget( {
10021 title
: OO
.ui
.msg( 'ooui-outline-control-move-up' )
10023 this.downButton
= new OO
.ui
.ButtonWidget( {
10026 title
: OO
.ui
.msg( 'ooui-outline-control-move-down' )
10028 this.removeButton
= new OO
.ui
.ButtonWidget( {
10031 title
: OO
.ui
.msg( 'ooui-outline-control-remove' )
10033 this.abilities
= { move: true, remove
: true };
10036 outline
.connect( this, {
10037 select
: 'onOutlineChange',
10038 add
: 'onOutlineChange',
10039 remove
: 'onOutlineChange'
10041 this.upButton
.connect( this, { click
: [ 'emit', 'move', -1 ] } );
10042 this.downButton
.connect( this, { click
: [ 'emit', 'move', 1 ] } );
10043 this.removeButton
.connect( this, { click
: [ 'emit', 'remove' ] } );
10046 this.$element
.addClass( 'oo-ui-outlineControlsWidget' );
10047 this.$group
.addClass( 'oo-ui-outlineControlsWidget-items' );
10049 .addClass( 'oo-ui-outlineControlsWidget-movers' )
10050 .append( this.removeButton
.$element
, this.upButton
.$element
, this.downButton
.$element
);
10051 this.$element
.append( this.$icon
, this.$group
, this.$movers
);
10052 this.setAbilities( config
.abilities
|| {} );
10057 OO
.inheritClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.Widget
);
10058 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.GroupElement
);
10059 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.IconElement
);
10065 * @param {number} places Number of places to move
10077 * @param {Object} abilities List of abilties
10078 * @param {boolean} [abilities.move] Allow moving movable items
10079 * @param {boolean} [abilities.remove] Allow removing removable items
10081 OO
.ui
.OutlineControlsWidget
.prototype.setAbilities = function ( abilities
) {
10084 for ( ability
in this.abilities
) {
10085 if ( abilities
[ability
] !== undefined ) {
10086 this.abilities
[ability
] = !!abilities
[ability
];
10090 this.onOutlineChange();
10096 * Handle outline change events.
10098 OO
.ui
.OutlineControlsWidget
.prototype.onOutlineChange = function () {
10099 var i
, len
, firstMovable
, lastMovable
,
10100 items
= this.outline
.getItems(),
10101 selectedItem
= this.outline
.getSelectedItem(),
10102 movable
= this.abilities
.move && selectedItem
&& selectedItem
.isMovable(),
10103 removable
= this.abilities
.remove
&& selectedItem
&& selectedItem
.isRemovable();
10107 len
= items
.length
;
10108 while ( ++i
< len
) {
10109 if ( items
[ i
].isMovable() ) {
10110 firstMovable
= items
[ i
];
10116 if ( items
[ i
].isMovable() ) {
10117 lastMovable
= items
[ i
];
10122 this.upButton
.setDisabled( !movable
|| selectedItem
=== firstMovable
);
10123 this.downButton
.setDisabled( !movable
|| selectedItem
=== lastMovable
);
10124 this.removeButton
.setDisabled( !removable
);
10128 * ToggleWidget is mixed into other classes to create widgets with an on/off state.
10129 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
10135 * @param {Object} [config] Configuration options
10136 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
10137 * By default, the toggle is in the 'off' state.
10139 OO
.ui
.ToggleWidget
= function OoUiToggleWidget( config
) {
10140 // Configuration initialization
10141 config
= config
|| {};
10147 this.$element
.addClass( 'oo-ui-toggleWidget' );
10148 this.setValue( !!config
.value
);
10156 * A change event is emitted when the on/off state of the toggle changes.
10158 * @param {boolean} value Value representing the new state of the toggle
10164 * Get the value representing the toggle’s state.
10166 * @return {boolean} The on/off state of the toggle
10168 OO
.ui
.ToggleWidget
.prototype.getValue = function () {
10173 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
10175 * @param {boolean} value The state of the toggle
10179 OO
.ui
.ToggleWidget
.prototype.setValue = function ( value
) {
10181 if ( this.value
!== value
) {
10182 this.value
= value
;
10183 this.emit( 'change', value
);
10184 this.$element
.toggleClass( 'oo-ui-toggleWidget-on', value
);
10185 this.$element
.toggleClass( 'oo-ui-toggleWidget-off', !value
);
10186 this.$element
.attr( 'aria-checked', value
.toString() );
10192 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
10193 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
10194 * removed, and cleared from the group.
10197 * // Example: A ButtonGroupWidget with two buttons
10198 * var button1 = new OO.ui.PopupButtonWidget( {
10199 * label: 'Select a category',
10202 * $content: $( '<p>List of categories...</p>' ),
10207 * var button2 = new OO.ui.ButtonWidget( {
10208 * label: 'Add item'
10210 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
10211 * items: [button1, button2]
10213 * $( 'body' ).append( buttonGroup.$element );
10216 * @extends OO.ui.Widget
10217 * @mixins OO.ui.GroupElement
10220 * @param {Object} [config] Configuration options
10221 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
10223 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
10224 // Configuration initialization
10225 config
= config
|| {};
10227 // Parent constructor
10228 OO
.ui
.ButtonGroupWidget
.super.call( this, config
);
10230 // Mixin constructors
10231 OO
.ui
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
10234 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
10235 if ( Array
.isArray( config
.items
) ) {
10236 this.addItems( config
.items
);
10242 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
10243 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.GroupElement
);
10246 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
10247 * feels, and functionality can be customized via the class’s configuration options
10248 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
10251 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
10254 * // A button widget
10255 * var button = new OO.ui.ButtonWidget( {
10256 * label: 'Button with Icon',
10258 * iconTitle: 'Remove'
10260 * $( 'body' ).append( button.$element );
10262 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
10265 * @extends OO.ui.Widget
10266 * @mixins OO.ui.ButtonElement
10267 * @mixins OO.ui.IconElement
10268 * @mixins OO.ui.IndicatorElement
10269 * @mixins OO.ui.LabelElement
10270 * @mixins OO.ui.TitledElement
10271 * @mixins OO.ui.FlaggedElement
10272 * @mixins OO.ui.TabIndexedElement
10275 * @param {Object} [config] Configuration options
10276 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
10277 * @cfg {string} [target] The frame or window in which to open the hyperlink.
10278 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
10280 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
10281 // Configuration initialization
10282 // FIXME: The `nofollow` alias is deprecated and will be removed (T89767)
10283 config
= $.extend( { noFollow
: config
&& config
.nofollow
}, config
);
10285 // Parent constructor
10286 OO
.ui
.ButtonWidget
.super.call( this, config
);
10288 // Mixin constructors
10289 OO
.ui
.ButtonElement
.call( this, config
);
10290 OO
.ui
.IconElement
.call( this, config
);
10291 OO
.ui
.IndicatorElement
.call( this, config
);
10292 OO
.ui
.LabelElement
.call( this, config
);
10293 OO
.ui
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
10294 OO
.ui
.FlaggedElement
.call( this, config
);
10295 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
10299 this.target
= null;
10300 this.noFollow
= false;
10301 this.isHyperlink
= false;
10304 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
10306 .addClass( 'oo-ui-buttonWidget' )
10307 .append( this.$button
);
10308 this.setHref( config
.href
);
10309 this.setTarget( config
.target
);
10310 this.setNoFollow( config
.noFollow
);
10315 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
10316 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.ButtonElement
);
10317 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.IconElement
);
10318 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.IndicatorElement
);
10319 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.LabelElement
);
10320 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.TitledElement
);
10321 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.FlaggedElement
);
10322 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.TabIndexedElement
);
10329 OO
.ui
.ButtonWidget
.prototype.onMouseDown = function ( e
) {
10330 if ( !this.isDisabled() ) {
10331 // Remove the tab-index while the button is down to prevent the button from stealing focus
10332 this.$button
.removeAttr( 'tabindex' );
10335 return OO
.ui
.ButtonElement
.prototype.onMouseDown
.call( this, e
);
10341 OO
.ui
.ButtonWidget
.prototype.onMouseUp = function ( e
) {
10342 if ( !this.isDisabled() ) {
10343 // Restore the tab-index after the button is up to restore the button's accessibility
10344 this.$button
.attr( 'tabindex', this.tabIndex
);
10347 return OO
.ui
.ButtonElement
.prototype.onMouseUp
.call( this, e
);
10353 OO
.ui
.ButtonWidget
.prototype.onClick = function ( e
) {
10354 var ret
= OO
.ui
.ButtonElement
.prototype.onClick
.call( this, e
);
10355 if ( this.isHyperlink
) {
10364 OO
.ui
.ButtonWidget
.prototype.onKeyPress = function ( e
) {
10365 var ret
= OO
.ui
.ButtonElement
.prototype.onKeyPress
.call( this, e
);
10366 if ( this.isHyperlink
) {
10373 * Get hyperlink location.
10375 * @return {string} Hyperlink location
10377 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
10382 * Get hyperlink target.
10384 * @return {string} Hyperlink target
10386 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
10387 return this.target
;
10391 * Get search engine traversal hint.
10393 * @return {boolean} Whether search engines should avoid traversing this hyperlink
10395 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
10396 return this.noFollow
;
10400 * Set hyperlink location.
10402 * @param {string|null} href Hyperlink location, null to remove
10404 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
10405 href
= typeof href
=== 'string' ? href
: null;
10407 if ( href
!== this.href
) {
10409 if ( href
!== null ) {
10410 this.$button
.attr( 'href', href
);
10411 this.isHyperlink
= true;
10413 this.$button
.removeAttr( 'href' );
10414 this.isHyperlink
= false;
10422 * Set hyperlink target.
10424 * @param {string|null} target Hyperlink target, null to remove
10426 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
10427 target
= typeof target
=== 'string' ? target
: null;
10429 if ( target
!== this.target
) {
10430 this.target
= target
;
10431 if ( target
!== null ) {
10432 this.$button
.attr( 'target', target
);
10434 this.$button
.removeAttr( 'target' );
10442 * Set search engine traversal hint.
10444 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
10446 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
10447 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
10449 if ( noFollow
!== this.noFollow
) {
10450 this.noFollow
= noFollow
;
10452 this.$button
.attr( 'rel', 'nofollow' );
10454 this.$button
.removeAttr( 'rel' );
10462 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
10463 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
10466 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
10467 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
10470 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
10473 * @extends OO.ui.ButtonWidget
10474 * @mixins OO.ui.PendingElement
10477 * @param {Object} [config] Configuration options
10478 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
10479 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
10480 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
10481 * for more information about setting modes.
10482 * @cfg {boolean} [framed=false] Render the action button with a frame
10484 OO
.ui
.ActionWidget
= function OoUiActionWidget( config
) {
10485 // Configuration initialization
10486 config
= $.extend( { framed
: false }, config
);
10488 // Parent constructor
10489 OO
.ui
.ActionWidget
.super.call( this, config
);
10491 // Mixin constructors
10492 OO
.ui
.PendingElement
.call( this, config
);
10495 this.action
= config
.action
|| '';
10496 this.modes
= config
.modes
|| [];
10501 this.$element
.addClass( 'oo-ui-actionWidget' );
10506 OO
.inheritClass( OO
.ui
.ActionWidget
, OO
.ui
.ButtonWidget
);
10507 OO
.mixinClass( OO
.ui
.ActionWidget
, OO
.ui
.PendingElement
);
10512 * A resize event is emitted when the size of the widget changes.
10520 * Check if the action is configured to be available in the specified `mode`.
10522 * @param {string} mode Name of mode
10523 * @return {boolean} The action is configured with the mode
10525 OO
.ui
.ActionWidget
.prototype.hasMode = function ( mode
) {
10526 return this.modes
.indexOf( mode
) !== -1;
10530 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
10534 OO
.ui
.ActionWidget
.prototype.getAction = function () {
10535 return this.action
;
10539 * Get the symbolic name of the mode or modes for which the action is configured to be available.
10541 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
10542 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
10545 * @return {string[]}
10547 OO
.ui
.ActionWidget
.prototype.getModes = function () {
10548 return this.modes
.slice();
10552 * Emit a resize event if the size has changed.
10557 OO
.ui
.ActionWidget
.prototype.propagateResize = function () {
10560 if ( this.isElementAttached() ) {
10561 width
= this.$element
.width();
10562 height
= this.$element
.height();
10564 if ( width
!== this.width
|| height
!== this.height
) {
10565 this.width
= width
;
10566 this.height
= height
;
10567 this.emit( 'resize' );
10577 OO
.ui
.ActionWidget
.prototype.setIcon = function () {
10579 OO
.ui
.IconElement
.prototype.setIcon
.apply( this, arguments
);
10580 this.propagateResize();
10588 OO
.ui
.ActionWidget
.prototype.setLabel = function () {
10590 OO
.ui
.LabelElement
.prototype.setLabel
.apply( this, arguments
);
10591 this.propagateResize();
10599 OO
.ui
.ActionWidget
.prototype.setFlags = function () {
10601 OO
.ui
.FlaggedElement
.prototype.setFlags
.apply( this, arguments
);
10602 this.propagateResize();
10610 OO
.ui
.ActionWidget
.prototype.clearFlags = function () {
10612 OO
.ui
.FlaggedElement
.prototype.clearFlags
.apply( this, arguments
);
10613 this.propagateResize();
10619 * Toggle the visibility of the action button.
10621 * @param {boolean} [show] Show button, omit to toggle visibility
10624 OO
.ui
.ActionWidget
.prototype.toggle = function () {
10626 OO
.ui
.ActionWidget
.super.prototype.toggle
.apply( this, arguments
);
10627 this.propagateResize();
10633 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
10634 * which is used to display additional information or options.
10637 * // Example of a popup button.
10638 * var popupButton = new OO.ui.PopupButtonWidget( {
10639 * label: 'Popup button with options',
10642 * $content: $( '<p>Additional options here.</p>' ),
10647 * // Append the button to the DOM.
10648 * $( 'body' ).append( popupButton.$element );
10651 * @extends OO.ui.ButtonWidget
10652 * @mixins OO.ui.PopupElement
10655 * @param {Object} [config] Configuration options
10657 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
10658 // Parent constructor
10659 OO
.ui
.PopupButtonWidget
.super.call( this, config
);
10661 // Mixin constructors
10662 OO
.ui
.PopupElement
.call( this, config
);
10665 this.connect( this, { click
: 'onAction' } );
10669 .addClass( 'oo-ui-popupButtonWidget' )
10670 .attr( 'aria-haspopup', 'true' )
10671 .append( this.popup
.$element
);
10676 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
10677 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.PopupElement
);
10682 * Handle the button action being triggered.
10686 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
10687 this.popup
.toggle();
10691 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
10692 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
10693 * configured with {@link OO.ui.IconElement icons}, {@link OO.ui.IndicatorElement indicators},
10694 * {@link OO.ui.TitledElement titles}, {@link OO.ui.FlaggedElement styling flags},
10695 * and {@link OO.ui.LabelElement labels}. Please see
10696 * the [OOjs UI documentation][1] on MediaWiki for more information.
10699 * // Toggle buttons in the 'off' and 'on' state.
10700 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
10701 * label: 'Toggle Button off'
10703 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
10704 * label: 'Toggle Button on',
10707 * // Append the buttons to the DOM.
10708 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
10710 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
10713 * @extends OO.ui.ButtonWidget
10714 * @mixins OO.ui.ToggleWidget
10717 * @param {Object} [config] Configuration options
10718 * @cfg {boolean} [value=false] The toggle button’s initial on/off
10719 * state. By default, the button is in the 'off' state.
10721 OO
.ui
.ToggleButtonWidget
= function OoUiToggleButtonWidget( config
) {
10722 // Configuration initialization
10723 config
= config
|| {};
10725 // Parent constructor
10726 OO
.ui
.ToggleButtonWidget
.super.call( this, config
);
10728 // Mixin constructors
10729 OO
.ui
.ToggleWidget
.call( this, config
);
10732 this.connect( this, { click
: 'onAction' } );
10735 this.$element
.addClass( 'oo-ui-toggleButtonWidget' );
10740 OO
.inheritClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.ButtonWidget
);
10741 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.ToggleWidget
);
10748 * Handle the button action being triggered.
10750 OO
.ui
.ToggleButtonWidget
.prototype.onAction = function () {
10751 this.setValue( !this.value
);
10757 OO
.ui
.ToggleButtonWidget
.prototype.setValue = function ( value
) {
10759 if ( value
!== this.value
) {
10760 this.$button
.attr( 'aria-pressed', value
.toString() );
10761 this.setActive( value
);
10764 // Parent method (from mixin)
10765 OO
.ui
.ToggleWidget
.prototype.setValue
.call( this, value
);
10771 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
10772 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
10773 * users can interact with it.
10776 * // Example: A DropdownWidget with a menu that contains three options
10777 * var dropDown = new OO.ui.DropdownWidget( {
10778 * label: 'Dropdown menu: Select a menu option',
10781 * new OO.ui.MenuOptionWidget( {
10785 * new OO.ui.MenuOptionWidget( {
10789 * new OO.ui.MenuOptionWidget( {
10797 * $( 'body' ).append( dropDown.$element );
10799 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
10801 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
10804 * @extends OO.ui.Widget
10805 * @mixins OO.ui.IconElement
10806 * @mixins OO.ui.IndicatorElement
10807 * @mixins OO.ui.LabelElement
10808 * @mixins OO.ui.TitledElement
10809 * @mixins OO.ui.TabIndexedElement
10812 * @param {Object} [config] Configuration options
10813 * @cfg {Object} [menu] Configuration options to pass to menu widget
10815 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
10816 // Configuration initialization
10817 config
= $.extend( { indicator
: 'down' }, config
);
10819 // Parent constructor
10820 OO
.ui
.DropdownWidget
.super.call( this, config
);
10822 // Properties (must be set before TabIndexedElement constructor call)
10823 this.$handle
= this.$( '<span>' );
10825 // Mixin constructors
10826 OO
.ui
.IconElement
.call( this, config
);
10827 OO
.ui
.IndicatorElement
.call( this, config
);
10828 OO
.ui
.LabelElement
.call( this, config
);
10829 OO
.ui
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
10830 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
10833 this.menu
= new OO
.ui
.MenuSelectWidget( $.extend( { widget
: this }, config
.menu
) );
10837 click
: this.onClick
.bind( this ),
10838 keypress
: this.onKeyPress
.bind( this )
10840 this.menu
.connect( this, { select
: 'onMenuSelect' } );
10844 .addClass( 'oo-ui-dropdownWidget-handle' )
10845 .append( this.$icon
, this.$label
, this.$indicator
);
10847 .addClass( 'oo-ui-dropdownWidget' )
10848 .append( this.$handle
, this.menu
.$element
);
10853 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
10854 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.IconElement
);
10855 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.IndicatorElement
);
10856 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.LabelElement
);
10857 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.TitledElement
);
10858 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.TabIndexedElement
);
10865 * @return {OO.ui.MenuSelectWidget} Menu of widget
10867 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
10872 * Handles menu select events.
10875 * @param {OO.ui.MenuOptionWidget} item Selected menu item
10877 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
10884 selectedLabel
= item
.getLabel();
10886 // If the label is a DOM element, clone it, because setLabel will append() it
10887 if ( selectedLabel
instanceof jQuery
) {
10888 selectedLabel
= selectedLabel
.clone();
10891 this.setLabel( selectedLabel
);
10895 * Handle mouse click events.
10898 * @param {jQuery.Event} e Mouse click event
10900 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
10901 if ( !this.isDisabled() && e
.which
=== 1 ) {
10902 this.menu
.toggle();
10908 * Handle key press events.
10911 * @param {jQuery.Event} e Key press event
10913 OO
.ui
.DropdownWidget
.prototype.onKeyPress = function ( e
) {
10914 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
10915 this.menu
.toggle();
10921 * IconWidget is a generic widget for {@link OO.ui.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
10922 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
10923 * for a list of icons included in the library.
10926 * // An icon widget with a label
10927 * var myIcon = new OO.ui.IconWidget( {
10929 * iconTitle: 'Help'
10931 * // Create a label.
10932 * var iconLabel = new OO.ui.LabelWidget( {
10935 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
10937 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
10940 * @extends OO.ui.Widget
10941 * @mixins OO.ui.IconElement
10942 * @mixins OO.ui.TitledElement
10943 * @mixins OO.ui.FlaggedElement
10946 * @param {Object} [config] Configuration options
10948 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
10949 // Configuration initialization
10950 config
= config
|| {};
10952 // Parent constructor
10953 OO
.ui
.IconWidget
.super.call( this, config
);
10955 // Mixin constructors
10956 OO
.ui
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
10957 OO
.ui
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
10958 OO
.ui
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
10961 this.$element
.addClass( 'oo-ui-iconWidget' );
10966 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
10967 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.IconElement
);
10968 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.TitledElement
);
10969 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.FlaggedElement
);
10971 /* Static Properties */
10973 OO
.ui
.IconWidget
.static.tagName
= 'span';
10976 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
10977 * attention to the status of an item or to clarify the function of a control. For a list of
10978 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
10981 * // Example of an indicator widget
10982 * var indicator1 = new OO.ui.IndicatorWidget( {
10983 * indicator: 'alert'
10986 * // Create a fieldset layout to add a label
10987 * var fieldset = new OO.ui.FieldsetLayout();
10988 * fieldset.addItems( [
10989 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
10991 * $( 'body' ).append( fieldset.$element );
10993 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
10996 * @extends OO.ui.Widget
10997 * @mixins OO.ui.IndicatorElement
10998 * @mixins OO.ui.TitledElement
11001 * @param {Object} [config] Configuration options
11003 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
11004 // Configuration initialization
11005 config
= config
|| {};
11007 // Parent constructor
11008 OO
.ui
.IndicatorWidget
.super.call( this, config
);
11010 // Mixin constructors
11011 OO
.ui
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
11012 OO
.ui
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
11015 this.$element
.addClass( 'oo-ui-indicatorWidget' );
11020 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
11021 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.IndicatorElement
);
11022 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.TitledElement
);
11024 /* Static Properties */
11026 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
11029 * InputWidget is the base class for all input widgets, which
11030 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
11031 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
11032 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
11034 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11038 * @extends OO.ui.Widget
11039 * @mixins OO.ui.FlaggedElement
11040 * @mixins OO.ui.TabIndexedElement
11043 * @param {Object} [config] Configuration options
11044 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
11045 * @cfg {string} [value=''] The value of the input.
11046 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
11047 * before it is accepted.
11049 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
11050 // Configuration initialization
11051 config
= config
|| {};
11053 // Parent constructor
11054 OO
.ui
.InputWidget
.super.call( this, config
);
11057 this.$input
= this.getInputElement( config
);
11059 this.inputFilter
= config
.inputFilter
;
11061 // Mixin constructors
11062 OO
.ui
.FlaggedElement
.call( this, config
);
11063 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
11066 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
11070 .attr( 'name', config
.name
)
11071 .prop( 'disabled', this.isDisabled() );
11072 this.$element
.addClass( 'oo-ui-inputWidget' ).append( this.$input
, $( '<span>' ) );
11073 this.setValue( config
.value
);
11078 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
11079 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.FlaggedElement
);
11080 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.TabIndexedElement
);
11087 * A change event is emitted when the value of the input changes.
11089 * @param {string} value
11095 * Get input element.
11097 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
11098 * different circumstances. The element must have a `value` property (like form elements).
11101 * @param {Object} config Configuration options
11102 * @return {jQuery} Input element
11104 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
11105 return $( '<input>' );
11109 * Handle potentially value-changing events.
11112 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
11114 OO
.ui
.InputWidget
.prototype.onEdit = function () {
11116 if ( !this.isDisabled() ) {
11117 // Allow the stack to clear so the value will be updated
11118 setTimeout( function () {
11119 widget
.setValue( widget
.$input
.val() );
11125 * Get the value of the input.
11127 * @return {string} Input value
11129 OO
.ui
.InputWidget
.prototype.getValue = function () {
11130 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
11131 // it, and we won't know unless they're kind enough to trigger a 'change' event.
11132 var value
= this.$input
.val();
11133 if ( this.value
!== value
) {
11134 this.setValue( value
);
11140 * Set the direction of the input, either RTL (right-to-left) or LTR (left-to-right).
11142 * @param {boolean} isRTL
11143 * Direction is right-to-left
11145 OO
.ui
.InputWidget
.prototype.setRTL = function ( isRTL
) {
11146 this.$input
.prop( 'dir', isRTL
? 'rtl' : 'ltr' );
11150 * Set the value of the input.
11152 * @param {string} value New value
11156 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
11157 value
= this.cleanUpValue( value
);
11158 // Update the DOM if it has changed. Note that with cleanUpValue, it
11159 // is possible for the DOM value to change without this.value changing.
11160 if ( this.$input
.val() !== value
) {
11161 this.$input
.val( value
);
11163 if ( this.value
!== value
) {
11164 this.value
= value
;
11165 this.emit( 'change', this.value
);
11171 * Clean up incoming value.
11173 * Ensures value is a string, and converts undefined and null to empty string.
11176 * @param {string} value Original value
11177 * @return {string} Cleaned up value
11179 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
11180 if ( value
=== undefined || value
=== null ) {
11182 } else if ( this.inputFilter
) {
11183 return this.inputFilter( String( value
) );
11185 return String( value
);
11190 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
11191 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
11194 OO
.ui
.InputWidget
.prototype.simulateLabelClick = function () {
11195 if ( !this.isDisabled() ) {
11196 if ( this.$input
.is( ':checkbox, :radio' ) ) {
11197 this.$input
.click();
11199 if ( this.$input
.is( ':input' ) ) {
11200 this.$input
[ 0 ].focus();
11208 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
11209 OO
.ui
.InputWidget
.super.prototype.setDisabled
.call( this, state
);
11210 if ( this.$input
) {
11211 this.$input
.prop( 'disabled', this.isDisabled() );
11221 OO
.ui
.InputWidget
.prototype.focus = function () {
11222 this.$input
[ 0 ].focus();
11231 OO
.ui
.InputWidget
.prototype.blur = function () {
11232 this.$input
[ 0 ].blur();
11237 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
11238 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
11239 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
11240 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
11241 * [OOjs UI documentation on MediaWiki] [1] for more information.
11244 * // A ButtonInputWidget rendered as an HTML button, the default.
11245 * var button = new OO.ui.ButtonInputWidget( {
11246 * label: 'Input button',
11250 * $( 'body' ).append( button.$element );
11252 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
11255 * @extends OO.ui.InputWidget
11256 * @mixins OO.ui.ButtonElement
11257 * @mixins OO.ui.IconElement
11258 * @mixins OO.ui.IndicatorElement
11259 * @mixins OO.ui.LabelElement
11260 * @mixins OO.ui.TitledElement
11261 * @mixins OO.ui.FlaggedElement
11264 * @param {Object} [config] Configuration options
11265 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
11266 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
11267 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
11268 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
11269 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
11271 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
11272 // Configuration initialization
11273 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
11275 // Properties (must be set before parent constructor, which calls #setValue)
11276 this.useInputTag
= config
.useInputTag
;
11278 // Parent constructor
11279 OO
.ui
.ButtonInputWidget
.super.call( this, config
);
11281 // Mixin constructors
11282 OO
.ui
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
11283 OO
.ui
.IconElement
.call( this, config
);
11284 OO
.ui
.IndicatorElement
.call( this, config
);
11285 OO
.ui
.LabelElement
.call( this, config
);
11286 OO
.ui
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
11287 OO
.ui
.FlaggedElement
.call( this, config
);
11290 if ( !config
.useInputTag
) {
11291 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
11293 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
11298 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
11299 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.ButtonElement
);
11300 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.IconElement
);
11301 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.IndicatorElement
);
11302 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.LabelElement
);
11303 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.TitledElement
);
11304 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.FlaggedElement
);
11312 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
11313 var html
= '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + config
.type
+ '">';
11320 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
11322 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
11323 * text, or `null` for no label
11326 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
11327 OO
.ui
.LabelElement
.prototype.setLabel
.call( this, label
);
11329 if ( this.useInputTag
) {
11330 if ( typeof label
=== 'function' ) {
11331 label
= OO
.ui
.resolveMsg( label
);
11333 if ( label
instanceof jQuery
) {
11334 label
= label
.text();
11339 this.$input
.val( label
);
11346 * Set the value of the input.
11348 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
11349 * they do not support {@link #value values}.
11351 * @param {string} value New value
11354 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
11355 if ( !this.useInputTag
) {
11356 OO
.ui
.ButtonInputWidget
.super.prototype.setValue
.call( this, value
);
11362 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
11363 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
11364 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
11365 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
11368 * // An example of selected, unselected, and disabled checkbox inputs
11369 * var checkbox1=new OO.ui.CheckboxInputWidget( {
11373 * var checkbox2=new OO.ui.CheckboxInputWidget( {
11376 * var checkbox3=new OO.ui.CheckboxInputWidget( {
11380 * // Create a fieldset layout with fields for each checkbox.
11381 * var fieldset = new OO.ui.FieldsetLayout( {
11382 * label: 'Checkboxes'
11384 * fieldset.addItems( [
11385 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
11386 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
11387 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
11389 * $( 'body' ).append( fieldset.$element );
11391 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11394 * @extends OO.ui.InputWidget
11397 * @param {Object} [config] Configuration options
11398 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
11400 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
11401 // Configuration initialization
11402 config
= config
|| {};
11404 // Parent constructor
11405 OO
.ui
.CheckboxInputWidget
.super.call( this, config
);
11408 this.$element
.addClass( 'oo-ui-checkboxInputWidget' );
11409 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
11414 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
11422 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
11423 return $( '<input type="checkbox" />' );
11429 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
11431 if ( !this.isDisabled() ) {
11432 // Allow the stack to clear so the value will be updated
11433 setTimeout( function () {
11434 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
11440 * Set selection state of this checkbox.
11442 * @param {boolean} state `true` for selected
11445 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
11447 if ( this.selected
!== state
) {
11448 this.selected
= state
;
11449 this.$input
.prop( 'checked', this.selected
);
11450 this.emit( 'change', this.selected
);
11456 * Check if this checkbox is selected.
11458 * @return {boolean} Checkbox is selected
11460 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
11461 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
11462 // it, and we won't know unless they're kind enough to trigger a 'change' event.
11463 var selected
= this.$input
.prop( 'checked' );
11464 if ( this.selected
!== selected
) {
11465 this.setSelected( selected
);
11467 return this.selected
;
11471 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
11472 * within a {@link OO.ui.FormLayout form}. The selected value is synchronized with the value
11473 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
11474 * more information about input widgets.
11477 * // Example: A DropdownInputWidget with three options
11478 * var dropDown = new OO.ui.DropdownInputWidget( {
11479 * label: 'Dropdown menu: Select a menu option',
11481 * { data: 'a', label: 'First' } ,
11482 * { data: 'b', label: 'Second'} ,
11483 * { data: 'c', label: 'Third' }
11486 * $( 'body' ).append( dropDown.$element );
11488 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11491 * @extends OO.ui.InputWidget
11494 * @param {Object} [config] Configuration options
11495 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
11497 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
11498 // Configuration initialization
11499 config
= config
|| {};
11501 // Properties (must be done before parent constructor which calls #setDisabled)
11502 this.dropdownWidget
= new OO
.ui
.DropdownWidget();
11504 // Parent constructor
11505 OO
.ui
.DropdownInputWidget
.super.call( this, config
);
11508 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
11511 this.setOptions( config
.options
|| [] );
11513 .addClass( 'oo-ui-dropdownInputWidget' )
11514 .append( this.dropdownWidget
.$element
);
11519 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
11527 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
11528 return $( '<input type="hidden">' );
11532 * Handles menu select events.
11535 * @param {OO.ui.MenuOptionWidget} item Selected menu item
11537 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
11538 this.setValue( item
.getData() );
11544 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
11545 var item
= this.dropdownWidget
.getMenu().getItemFromData( value
);
11547 this.dropdownWidget
.getMenu().selectItem( item
);
11549 OO
.ui
.DropdownInputWidget
.super.prototype.setValue
.call( this, value
);
11556 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
11557 this.dropdownWidget
.setDisabled( state
);
11558 OO
.ui
.DropdownInputWidget
.super.prototype.setDisabled
.call( this, state
);
11563 * Set the options available for this input.
11565 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
11568 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
11569 var value
= this.getValue();
11571 // Rebuild the dropdown menu
11572 this.dropdownWidget
.getMenu()
11574 .addItems( options
.map( function ( opt
) {
11575 return new OO
.ui
.MenuOptionWidget( {
11577 label
: opt
.label
!== undefined ? opt
.label
: opt
.data
11581 // Restore the previous value, or reset to something sensible
11582 if ( this.dropdownWidget
.getMenu().getItemFromData( value
) ) {
11583 // Previous value is still available, ensure consistency with the dropdown
11584 this.setValue( value
);
11586 // No longer valid, reset
11587 if ( options
.length
) {
11588 this.setValue( options
[ 0 ].data
);
11598 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
11599 this.dropdownWidget
.getMenu().toggle( true );
11606 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
11607 this.dropdownWidget
.getMenu().toggle( false );
11612 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
11613 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
11614 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
11615 * please see the [OOjs UI documentation on MediaWiki][1].
11618 * // An example of selected, unselected, and disabled radio inputs
11619 * var radio1 = new OO.ui.RadioInputWidget( {
11623 * var radio2 = new OO.ui.RadioInputWidget( {
11626 * var radio3 = new OO.ui.RadioInputWidget( {
11630 * // Create a fieldset layout with fields for each radio button.
11631 * var fieldset = new OO.ui.FieldsetLayout( {
11632 * label: 'Radio inputs'
11634 * fieldset.addItems( [
11635 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
11636 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
11637 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
11639 * $( 'body' ).append( fieldset.$element );
11641 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11644 * @extends OO.ui.InputWidget
11647 * @param {Object} [config] Configuration options
11648 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
11650 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
11651 // Configuration initialization
11652 config
= config
|| {};
11654 // Parent constructor
11655 OO
.ui
.RadioInputWidget
.super.call( this, config
);
11658 this.$element
.addClass( 'oo-ui-radioInputWidget' );
11659 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
11664 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
11672 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
11673 return $( '<input type="radio" />' );
11679 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
11680 // RadioInputWidget doesn't track its state.
11684 * Set selection state of this radio button.
11686 * @param {boolean} state `true` for selected
11689 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
11690 // RadioInputWidget doesn't track its state.
11691 this.$input
.prop( 'checked', state
);
11696 * Check if this radio button is selected.
11698 * @return {boolean} Radio is selected
11700 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
11701 return this.$input
.prop( 'checked' );
11705 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
11706 * size of the field as well as its presentation. In addition, these widgets can be configured
11707 * with {@link OO.ui.IconElement icons}, {@link OO.ui.IndicatorElement indicators}, an optional
11708 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
11709 * which modifies incoming values rather than validating them.
11710 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
11713 * // Example of a text input widget
11714 * var textInput = new OO.ui.TextInputWidget( {
11715 * value: 'Text input'
11717 * $( 'body' ).append( textInput.$element );
11719 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11722 * @extends OO.ui.InputWidget
11723 * @mixins OO.ui.IconElement
11724 * @mixins OO.ui.IndicatorElement
11725 * @mixins OO.ui.PendingElement
11726 * @mixins OO.ui.LabelElement
11729 * @param {Object} [config] Configuration options
11730 * @cfg {string} [type='text'] The value of the HTML `type` attribute
11731 * @cfg {string} [placeholder] Placeholder text
11732 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
11733 * instruct the browser to focus this widget.
11734 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
11735 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
11736 * @cfg {boolean} [multiline=false] Allow multiple lines of text
11737 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
11738 * Use the #maxRows config to specify a maximum number of displayed rows.
11739 * @cfg {boolean} [maxRows=10] Maximum number of rows to display when #autosize is set to true.
11740 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
11741 * the value or placeholder text: `'before'` or `'after'`
11742 * @cfg {boolean} [required=false] Mark the field as required
11743 * @cfg {RegExp|string} [validate] Validation pattern, either a regular expression or the
11744 * symbolic name of a pattern defined by the class: 'non-empty' (the value cannot be an empty string)
11745 * or 'integer' (the value must contain only numbers).
11747 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
11748 // Configuration initialization
11749 config
= $.extend( {
11751 labelPosition
: 'after',
11755 // Parent constructor
11756 OO
.ui
.TextInputWidget
.super.call( this, config
);
11758 // Mixin constructors
11759 OO
.ui
.IconElement
.call( this, config
);
11760 OO
.ui
.IndicatorElement
.call( this, config
);
11761 OO
.ui
.PendingElement
.call( this, config
);
11762 OO
.ui
.LabelElement
.call( this, config
);
11765 this.readOnly
= false;
11766 this.multiline
= !!config
.multiline
;
11767 this.autosize
= !!config
.autosize
;
11768 this.maxRows
= config
.maxRows
;
11769 this.validate
= null;
11771 // Clone for resizing
11772 if ( this.autosize
) {
11773 this.$clone
= this.$input
11775 .insertAfter( this.$input
)
11776 .attr( 'aria-hidden', 'true' )
11777 .addClass( 'oo-ui-element-hidden' );
11780 this.setValidation( config
.validate
);
11781 this.setLabelPosition( config
.labelPosition
);
11785 keypress
: this.onKeyPress
.bind( this ),
11786 blur
: this.setValidityFlag
.bind( this )
11789 focus
: this.onElementAttach
.bind( this )
11791 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
11792 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
11793 this.on( 'labelChange', this.updatePosition
.bind( this ) );
11797 .addClass( 'oo-ui-textInputWidget' )
11798 .append( this.$icon
, this.$indicator
);
11799 this.setReadOnly( !!config
.readOnly
);
11800 if ( config
.placeholder
) {
11801 this.$input
.attr( 'placeholder', config
.placeholder
);
11803 if ( config
.maxLength
!== undefined ) {
11804 this.$input
.attr( 'maxlength', config
.maxLength
);
11806 if ( config
.autofocus
) {
11807 this.$input
.attr( 'autofocus', 'autofocus' );
11809 if ( config
.required
) {
11810 this.$input
.attr( 'required', 'true' );
11812 if ( this.label
|| config
.autosize
) {
11813 this.installParentChangeDetector();
11819 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
11820 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.IconElement
);
11821 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.IndicatorElement
);
11822 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.PendingElement
);
11823 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.LabelElement
);
11825 /* Static properties */
11827 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
11835 * An `enter` event is emitted when the user presses 'enter' inside the text box.
11837 * Not emitted if the input is multiline.
11845 * Handle icon mouse down events.
11848 * @param {jQuery.Event} e Mouse down event
11851 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
11852 if ( e
.which
=== 1 ) {
11853 this.$input
[ 0 ].focus();
11859 * Handle indicator mouse down events.
11862 * @param {jQuery.Event} e Mouse down event
11865 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
11866 if ( e
.which
=== 1 ) {
11867 this.$input
[ 0 ].focus();
11873 * Handle key press events.
11876 * @param {jQuery.Event} e Key press event
11877 * @fires enter If enter key is pressed and input is not multiline
11879 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
11880 if ( e
.which
=== OO
.ui
.Keys
.ENTER
&& !this.multiline
) {
11881 this.emit( 'enter', e
);
11886 * Handle element attach events.
11889 * @param {jQuery.Event} e Element attach event
11891 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
11892 // Any previously calculated size is now probably invalid if we reattached elsewhere
11893 this.valCache
= null;
11895 this.positionLabel();
11901 OO
.ui
.TextInputWidget
.prototype.onEdit = function () {
11905 return OO
.ui
.TextInputWidget
.super.prototype.onEdit
.call( this );
11911 OO
.ui
.TextInputWidget
.prototype.setValue = function ( value
) {
11913 OO
.ui
.TextInputWidget
.super.prototype.setValue
.call( this, value
);
11915 this.setValidityFlag();
11921 * Check if the input is {@link #readOnly read-only}.
11923 * @return {boolean}
11925 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
11926 return this.readOnly
;
11930 * Set the {@link #readOnly read-only} state of the input.
11932 * @param {boolean} state Make input read-only
11935 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
11936 this.readOnly
= !!state
;
11937 this.$input
.prop( 'readOnly', this.readOnly
);
11942 * Support function for making #onElementAttach work across browsers.
11944 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
11945 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
11947 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
11948 * first time that the element gets attached to the documented.
11950 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
11951 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
11952 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
11955 if ( MutationObserver
) {
11956 // The new way. If only it wasn't so ugly.
11958 if ( this.$element
.closest( 'html' ).length
) {
11959 // Widget is attached already, do nothing. This breaks the functionality of this function when
11960 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
11961 // would require observation of the whole document, which would hurt performance of other,
11962 // more important code.
11966 // Find topmost node in the tree
11967 topmostNode
= this.$element
[0];
11968 while ( topmostNode
.parentNode
) {
11969 topmostNode
= topmostNode
.parentNode
;
11972 // We have no way to detect the $element being attached somewhere without observing the entire
11973 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
11974 // parent node of $element, and instead detect when $element is removed from it (and thus
11975 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
11976 // doesn't get attached, we end up back here and create the parent.
11978 mutationObserver
= new MutationObserver( function ( mutations
) {
11979 var i
, j
, removedNodes
;
11980 for ( i
= 0; i
< mutations
.length
; i
++ ) {
11981 removedNodes
= mutations
[ i
].removedNodes
;
11982 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
11983 if ( removedNodes
[ j
] === topmostNode
) {
11984 setTimeout( onRemove
, 0 );
11991 onRemove = function () {
11992 // If the node was attached somewhere else, report it
11993 if ( widget
.$element
.closest( 'html' ).length
) {
11994 widget
.onElementAttach();
11996 mutationObserver
.disconnect();
11997 widget
.installParentChangeDetector();
12000 // Create a fake parent and observe it
12001 fakeParentNode
= $( '<div>' ).append( this.$element
)[0];
12002 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
12004 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
12005 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
12006 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
12011 * Automatically adjust the size of the text input.
12013 * This only affects #multiline inputs that are {@link #autosize autosized}.
12017 OO
.ui
.TextInputWidget
.prototype.adjustSize = function () {
12018 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
, idealHeight
;
12020 if ( this.multiline
&& this.autosize
&& this.$input
.val() !== this.valCache
) {
12022 .val( this.$input
.val() )
12023 .attr( 'rows', '' )
12024 // Set inline height property to 0 to measure scroll height
12025 .css( 'height', 0 );
12027 this.$clone
.removeClass( 'oo-ui-element-hidden' );
12029 this.valCache
= this.$input
.val();
12031 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
12033 // Remove inline height property to measure natural heights
12034 this.$clone
.css( 'height', '' );
12035 innerHeight
= this.$clone
.innerHeight();
12036 outerHeight
= this.$clone
.outerHeight();
12038 // Measure max rows height
12040 .attr( 'rows', this.maxRows
)
12041 .css( 'height', 'auto' )
12043 maxInnerHeight
= this.$clone
.innerHeight();
12045 // Difference between reported innerHeight and scrollHeight with no scrollbars present
12046 // Equals 1 on Blink-based browsers and 0 everywhere else
12047 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
12048 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
12050 this.$clone
.addClass( 'oo-ui-element-hidden' );
12052 // Only apply inline height when expansion beyond natural height is needed
12053 if ( idealHeight
> innerHeight
) {
12054 // Use the difference between the inner and outer height as a buffer
12055 this.$input
.css( 'height', idealHeight
+ ( outerHeight
- innerHeight
) );
12057 this.$input
.css( 'height', '' );
12067 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
12068 return config
.multiline
? $( '<textarea>' ) : $( '<input type="' + config
.type
+ '" />' );
12072 * Check if the input supports multiple lines.
12074 * @return {boolean}
12076 OO
.ui
.TextInputWidget
.prototype.isMultiline = function () {
12077 return !!this.multiline
;
12081 * Check if the input automatically adjusts its size.
12083 * @return {boolean}
12085 OO
.ui
.TextInputWidget
.prototype.isAutosizing = function () {
12086 return !!this.autosize
;
12090 * Select the entire text of the input.
12094 OO
.ui
.TextInputWidget
.prototype.select = function () {
12095 this.$input
.select();
12100 * Set the validation pattern.
12102 * The validation pattern is either a regular expression or the symbolic name of a pattern
12103 * defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
12104 * value must contain only numbers).
12106 * @param {RegExp|string|null} validate Regular expression or the symbolic name of a
12107 * pattern (either ‘integer’ or ‘non-empty’) defined by the class.
12109 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
12110 if ( validate
instanceof RegExp
) {
12111 this.validate
= validate
;
12113 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
12118 * Sets the 'invalid' flag appropriately.
12120 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function () {
12122 this.isValid().done( function ( valid
) {
12123 widget
.setFlags( { invalid
: !valid
} );
12128 * Check if a value is valid.
12130 * This method returns a promise that resolves with a boolean `true` if the current value is
12131 * considered valid according to the supplied {@link #validate validation pattern}.
12133 * @return {jQuery.Deferred} A promise that resolves to a boolean `true` if the value is valid.
12135 OO
.ui
.TextInputWidget
.prototype.isValid = function () {
12136 return $.Deferred().resolve( !!this.getValue().match( this.validate
) ).promise();
12140 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
12142 * @param {string} labelPosition Label position, 'before' or 'after'
12145 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
12146 this.labelPosition
= labelPosition
;
12147 this.updatePosition();
12152 * Deprecated alias of #setLabelPosition
12154 * @deprecated Use setLabelPosition instead.
12156 OO
.ui
.TextInputWidget
.prototype.setPosition
=
12157 OO
.ui
.TextInputWidget
.prototype.setLabelPosition
;
12160 * Update the position of the inline label.
12162 * This method is called by #setLabelPosition, and can also be called on its own if
12163 * something causes the label to be mispositioned.
12168 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
12169 var after
= this.labelPosition
=== 'after';
12172 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
12173 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
12175 if ( this.label
) {
12176 this.positionLabel();
12183 * Position the label by setting the correct padding on the input.
12188 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
12189 // Clear old values
12191 // Clear old values if present
12193 'padding-right': '',
12197 if ( this.label
) {
12198 this.$element
.append( this.$label
);
12200 this.$label
.detach();
12204 var after
= this.labelPosition
=== 'after',
12205 rtl
= this.$element
.css( 'direction' ) === 'rtl',
12206 property
= after
=== rtl
? 'padding-left' : 'padding-right';
12208 this.$input
.css( property
, this.$label
.outerWidth( true ) );
12214 * ComboBoxWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
12215 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
12216 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
12218 * - by typing a value in the text input field. If the value exactly matches the value of a menu
12219 * option, that option will appear to be selected.
12220 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
12223 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
12226 * // Example: A ComboBoxWidget.
12227 * var comboBox = new OO.ui.ComboBoxWidget( {
12228 * label: 'ComboBoxWidget',
12229 * input: { value: 'Option One' },
12232 * new OO.ui.MenuOptionWidget( {
12233 * data: 'Option 1',
12234 * label: 'Option One'
12236 * new OO.ui.MenuOptionWidget( {
12237 * data: 'Option 2',
12238 * label: 'Option Two'
12240 * new OO.ui.MenuOptionWidget( {
12241 * data: 'Option 3',
12242 * label: 'Option Three'
12244 * new OO.ui.MenuOptionWidget( {
12245 * data: 'Option 4',
12246 * label: 'Option Four'
12248 * new OO.ui.MenuOptionWidget( {
12249 * data: 'Option 5',
12250 * label: 'Option Five'
12255 * $( 'body' ).append( comboBox.$element );
12257 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
12260 * @extends OO.ui.Widget
12261 * @mixins OO.ui.TabIndexedElement
12264 * @param {Object} [config] Configuration options
12265 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
12266 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
12267 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
12268 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
12269 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
12271 OO
.ui
.ComboBoxWidget
= function OoUiComboBoxWidget( config
) {
12272 // Configuration initialization
12273 config
= config
|| {};
12275 // Parent constructor
12276 OO
.ui
.ComboBoxWidget
.super.call( this, config
);
12278 // Properties (must be set before TabIndexedElement constructor call)
12279 this.$indicator
= this.$( '<span>' );
12281 // Mixin constructors
12282 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$indicator
} ) );
12285 this.$overlay
= config
.$overlay
|| this.$element
;
12286 this.input
= new OO
.ui
.TextInputWidget( $.extend(
12289 $indicator
: this.$indicator
,
12290 disabled
: this.isDisabled()
12294 this.input
.$input
.eq( 0 ).attr( {
12296 'aria-autocomplete': 'list'
12298 this.menu
= new OO
.ui
.TextInputMenuSelectWidget( this.input
, $.extend(
12302 disabled
: this.isDisabled()
12308 this.$indicator
.on( {
12309 click
: this.onClick
.bind( this ),
12310 keypress
: this.onKeyPress
.bind( this )
12312 this.input
.connect( this, {
12313 change
: 'onInputChange',
12314 enter
: 'onInputEnter'
12316 this.menu
.connect( this, {
12317 choose
: 'onMenuChoose',
12318 add
: 'onMenuItemsChange',
12319 remove
: 'onMenuItemsChange'
12323 this.$element
.addClass( 'oo-ui-comboBoxWidget' ).append( this.input
.$element
);
12324 this.$overlay
.append( this.menu
.$element
);
12325 this.onMenuItemsChange();
12330 OO
.inheritClass( OO
.ui
.ComboBoxWidget
, OO
.ui
.Widget
);
12331 OO
.mixinClass( OO
.ui
.ComboBoxWidget
, OO
.ui
.TabIndexedElement
);
12336 * Get the combobox's menu.
12337 * @return {OO.ui.TextInputMenuSelectWidget} Menu widget
12339 OO
.ui
.ComboBoxWidget
.prototype.getMenu = function () {
12344 * Handle input change events.
12347 * @param {string} value New value
12349 OO
.ui
.ComboBoxWidget
.prototype.onInputChange = function ( value
) {
12350 var match
= this.menu
.getItemFromData( value
);
12352 this.menu
.selectItem( match
);
12353 if ( this.menu
.getHighlightedItem() ) {
12354 this.menu
.highlightItem( match
);
12357 if ( !this.isDisabled() ) {
12358 this.menu
.toggle( true );
12363 * Handle mouse click events.
12367 * @param {jQuery.Event} e Mouse click event
12369 OO
.ui
.ComboBoxWidget
.prototype.onClick = function ( e
) {
12370 if ( !this.isDisabled() && e
.which
=== 1 ) {
12371 this.menu
.toggle();
12372 this.input
.$input
[ 0 ].focus();
12378 * Handle key press events.
12382 * @param {jQuery.Event} e Key press event
12384 OO
.ui
.ComboBoxWidget
.prototype.onKeyPress = function ( e
) {
12385 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
12386 this.menu
.toggle();
12387 this.input
.$input
[ 0 ].focus();
12393 * Handle input enter events.
12397 OO
.ui
.ComboBoxWidget
.prototype.onInputEnter = function () {
12398 if ( !this.isDisabled() ) {
12399 this.menu
.toggle( false );
12404 * Handle menu choose events.
12407 * @param {OO.ui.OptionWidget} item Chosen item
12409 OO
.ui
.ComboBoxWidget
.prototype.onMenuChoose = function ( item
) {
12410 this.input
.setValue( item
.getData() );
12414 * Handle menu item change events.
12418 OO
.ui
.ComboBoxWidget
.prototype.onMenuItemsChange = function () {
12419 var match
= this.menu
.getItemFromData( this.input
.getValue() );
12420 this.menu
.selectItem( match
);
12421 if ( this.menu
.getHighlightedItem() ) {
12422 this.menu
.highlightItem( match
);
12424 this.$element
.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu
.isEmpty() );
12430 OO
.ui
.ComboBoxWidget
.prototype.setDisabled = function ( disabled
) {
12432 OO
.ui
.ComboBoxWidget
.super.prototype.setDisabled
.call( this, disabled
);
12434 if ( this.input
) {
12435 this.input
.setDisabled( this.isDisabled() );
12438 this.menu
.setDisabled( this.isDisabled() );
12445 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
12446 * be configured with a `label` option that is set to a string, a label node, or a function:
12448 * - String: a plaintext string
12449 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
12450 * label that includes a link or special styling, such as a gray color or additional graphical elements.
12451 * - Function: a function that will produce a string in the future. Functions are used
12452 * in cases where the value of the label is not currently defined.
12454 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
12455 * will come into focus when the label is clicked.
12458 * // Examples of LabelWidgets
12459 * var label1 = new OO.ui.LabelWidget( {
12460 * label: 'plaintext label'
12462 * var label2 = new OO.ui.LabelWidget( {
12463 * label: $( '<a href="default.html">jQuery label</a>' )
12465 * // Create a fieldset layout with fields for each example
12466 * var fieldset = new OO.ui.FieldsetLayout();
12467 * fieldset.addItems( [
12468 * new OO.ui.FieldLayout( label1 ),
12469 * new OO.ui.FieldLayout( label2 )
12471 * $( 'body' ).append( fieldset.$element );
12475 * @extends OO.ui.Widget
12476 * @mixins OO.ui.LabelElement
12479 * @param {Object} [config] Configuration options
12480 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
12481 * Clicking the label will focus the specified input field.
12483 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
12484 // Configuration initialization
12485 config
= config
|| {};
12487 // Parent constructor
12488 OO
.ui
.LabelWidget
.super.call( this, config
);
12490 // Mixin constructors
12491 OO
.ui
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
12492 OO
.ui
.TitledElement
.call( this, config
);
12495 this.input
= config
.input
;
12498 if ( this.input
instanceof OO
.ui
.InputWidget
) {
12499 this.$element
.on( 'click', this.onClick
.bind( this ) );
12503 this.$element
.addClass( 'oo-ui-labelWidget' );
12508 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
12509 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.LabelElement
);
12510 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.TitledElement
);
12512 /* Static Properties */
12514 OO
.ui
.LabelWidget
.static.tagName
= 'span';
12519 * Handles label mouse click events.
12522 * @param {jQuery.Event} e Mouse click event
12524 OO
.ui
.LabelWidget
.prototype.onClick = function () {
12525 this.input
.simulateLabelClick();
12530 * OptionWidgets are special elements that can be selected and configured with data. The
12531 * data is often unique for each option, but it does not have to be. OptionWidgets are used
12532 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
12533 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
12535 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
12538 * @extends OO.ui.Widget
12539 * @mixins OO.ui.LabelElement
12540 * @mixins OO.ui.FlaggedElement
12543 * @param {Object} [config] Configuration options
12545 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
12546 // Configuration initialization
12547 config
= config
|| {};
12549 // Parent constructor
12550 OO
.ui
.OptionWidget
.super.call( this, config
);
12552 // Mixin constructors
12553 OO
.ui
.ItemWidget
.call( this );
12554 OO
.ui
.LabelElement
.call( this, config
);
12555 OO
.ui
.FlaggedElement
.call( this, config
);
12558 this.selected
= false;
12559 this.highlighted
= false;
12560 this.pressed
= false;
12564 .data( 'oo-ui-optionWidget', this )
12565 .attr( 'role', 'option' )
12566 .addClass( 'oo-ui-optionWidget' )
12567 .append( this.$label
);
12572 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
12573 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.ItemWidget
);
12574 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.LabelElement
);
12575 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.FlaggedElement
);
12577 /* Static Properties */
12579 OO
.ui
.OptionWidget
.static.selectable
= true;
12581 OO
.ui
.OptionWidget
.static.highlightable
= true;
12583 OO
.ui
.OptionWidget
.static.pressable
= true;
12585 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
12590 * Check if the option can be selected.
12592 * @return {boolean} Item is selectable
12594 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
12595 return this.constructor.static.selectable
&& !this.isDisabled();
12599 * Check if the option can be highlighted. A highlight indicates that the option
12600 * may be selected when a user presses enter or clicks. Disabled items cannot
12603 * @return {boolean} Item is highlightable
12605 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
12606 return this.constructor.static.highlightable
&& !this.isDisabled();
12610 * Check if the option can be pressed. The pressed state occurs when a user mouses
12611 * down on an item, but has not yet let go of the mouse.
12613 * @return {boolean} Item is pressable
12615 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
12616 return this.constructor.static.pressable
&& !this.isDisabled();
12620 * Check if the option is selected.
12622 * @return {boolean} Item is selected
12624 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
12625 return this.selected
;
12629 * Check if the option is highlighted. A highlight indicates that the
12630 * item may be selected when a user presses enter or clicks.
12632 * @return {boolean} Item is highlighted
12634 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
12635 return this.highlighted
;
12639 * Check if the option is pressed. The pressed state occurs when a user mouses
12640 * down on an item, but has not yet let go of the mouse. The item may appear
12641 * selected, but it will not be selected until the user releases the mouse.
12643 * @return {boolean} Item is pressed
12645 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
12646 return this.pressed
;
12650 * Set the option’s selected state. In general, all modifications to the selection
12651 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
12652 * method instead of this method.
12654 * @param {boolean} [state=false] Select option
12657 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
12658 if ( this.constructor.static.selectable
) {
12659 this.selected
= !!state
;
12661 .toggleClass( 'oo-ui-optionWidget-selected', state
)
12662 .attr( 'aria-selected', state
.toString() );
12663 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
12664 this.scrollElementIntoView();
12666 this.updateThemeClasses();
12672 * Set the option’s highlighted state. In general, all programmatic
12673 * modifications to the highlight should be handled by the
12674 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
12675 * method instead of this method.
12677 * @param {boolean} [state=false] Highlight option
12680 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
12681 if ( this.constructor.static.highlightable
) {
12682 this.highlighted
= !!state
;
12683 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
12684 this.updateThemeClasses();
12690 * Set the option’s pressed state. In general, all
12691 * programmatic modifications to the pressed state should be handled by the
12692 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
12693 * method instead of this method.
12695 * @param {boolean} [state=false] Press option
12698 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
12699 if ( this.constructor.static.pressable
) {
12700 this.pressed
= !!state
;
12701 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
12702 this.updateThemeClasses();
12708 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
12709 * with an {@link OO.ui.IconElement icon} and/or {@link OO.ui.IndicatorElement indicator}.
12710 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
12711 * options. For more information about options and selects, please see the
12712 * [OOjs UI documentation on MediaWiki][1].
12715 * // Decorated options in a select widget
12716 * var select = new OO.ui.SelectWidget( {
12718 * new OO.ui.DecoratedOptionWidget( {
12720 * label: 'Option with icon',
12723 * new OO.ui.DecoratedOptionWidget( {
12725 * label: 'Option with indicator',
12726 * indicator: 'next'
12730 * $( 'body' ).append( select.$element );
12732 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
12735 * @extends OO.ui.OptionWidget
12736 * @mixins OO.ui.IconElement
12737 * @mixins OO.ui.IndicatorElement
12740 * @param {Object} [config] Configuration options
12742 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
12743 // Parent constructor
12744 OO
.ui
.DecoratedOptionWidget
.super.call( this, config
);
12746 // Mixin constructors
12747 OO
.ui
.IconElement
.call( this, config
);
12748 OO
.ui
.IndicatorElement
.call( this, config
);
12752 .addClass( 'oo-ui-decoratedOptionWidget' )
12753 .prepend( this.$icon
)
12754 .append( this.$indicator
);
12759 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
12760 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.IconElement
);
12761 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.IndicatorElement
);
12764 * ButtonOptionWidget is a special type of {@link OO.ui.ButtonElement button element} that
12765 * can be selected and configured with data. The class is
12766 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
12767 * [OOjs UI documentation on MediaWiki] [1] for more information.
12769 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
12772 * @extends OO.ui.DecoratedOptionWidget
12773 * @mixins OO.ui.ButtonElement
12774 * @mixins OO.ui.TabIndexedElement
12777 * @param {Object} [config] Configuration options
12779 OO
.ui
.ButtonOptionWidget
= function OoUiButtonOptionWidget( config
) {
12780 // Configuration initialization
12781 config
= $.extend( { tabIndex
: -1 }, config
);
12783 // Parent constructor
12784 OO
.ui
.ButtonOptionWidget
.super.call( this, config
);
12786 // Mixin constructors
12787 OO
.ui
.ButtonElement
.call( this, config
);
12788 OO
.ui
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
12791 this.$element
.addClass( 'oo-ui-buttonOptionWidget' );
12792 this.$button
.append( this.$element
.contents() );
12793 this.$element
.append( this.$button
);
12798 OO
.inheritClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
12799 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.ButtonElement
);
12800 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.TabIndexedElement
);
12802 /* Static Properties */
12804 // Allow button mouse down events to pass through so they can be handled by the parent select widget
12805 OO
.ui
.ButtonOptionWidget
.static.cancelButtonMouseDownEvents
= false;
12807 OO
.ui
.ButtonOptionWidget
.static.highlightable
= false;
12814 OO
.ui
.ButtonOptionWidget
.prototype.setSelected = function ( state
) {
12815 OO
.ui
.ButtonOptionWidget
.super.prototype.setSelected
.call( this, state
);
12817 if ( this.constructor.static.selectable
) {
12818 this.setActive( state
);
12825 * RadioOptionWidget is an option widget that looks like a radio button.
12826 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
12827 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
12829 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
12832 * @extends OO.ui.OptionWidget
12835 * @param {Object} [config] Configuration options
12837 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
12838 // Configuration initialization
12839 config
= config
|| {};
12841 // Properties (must be done before parent constructor which calls #setDisabled)
12842 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
12844 // Parent constructor
12845 OO
.ui
.RadioOptionWidget
.super.call( this, config
);
12849 .addClass( 'oo-ui-radioOptionWidget' )
12850 .prepend( this.radio
.$element
);
12855 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
12857 /* Static Properties */
12859 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
12861 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
12863 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
12865 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
12872 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
12873 OO
.ui
.RadioOptionWidget
.super.prototype.setSelected
.call( this, state
);
12875 this.radio
.setSelected( state
);
12883 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
12884 OO
.ui
.RadioOptionWidget
.super.prototype.setDisabled
.call( this, disabled
);
12886 this.radio
.setDisabled( this.isDisabled() );
12892 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
12893 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
12894 * the [OOjs UI documentation on MediaWiki] [1] for more information.
12896 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
12899 * @extends OO.ui.DecoratedOptionWidget
12902 * @param {Object} [config] Configuration options
12904 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
12905 // Configuration initialization
12906 config
= $.extend( { icon
: 'check' }, config
);
12908 // Parent constructor
12909 OO
.ui
.MenuOptionWidget
.super.call( this, config
);
12913 .attr( 'role', 'menuitem' )
12914 .addClass( 'oo-ui-menuOptionWidget' );
12919 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
12921 /* Static Properties */
12923 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
12926 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
12927 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
12930 * var myDropdown = new OO.ui.DropdownWidget( {
12933 * new OO.ui.MenuSectionOptionWidget( {
12936 * new OO.ui.MenuOptionWidget( {
12938 * label: 'Welsh Corgi'
12940 * new OO.ui.MenuOptionWidget( {
12942 * label: 'Standard Poodle'
12944 * new OO.ui.MenuSectionOptionWidget( {
12947 * new OO.ui.MenuOptionWidget( {
12954 * $( 'body' ).append( myDropdown.$element );
12958 * @extends OO.ui.DecoratedOptionWidget
12961 * @param {Object} [config] Configuration options
12963 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
12964 // Parent constructor
12965 OO
.ui
.MenuSectionOptionWidget
.super.call( this, config
);
12968 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' );
12973 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
12975 /* Static Properties */
12977 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
12979 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
12982 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
12984 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
12985 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
12989 * @extends OO.ui.DecoratedOptionWidget
12992 * @param {Object} [config] Configuration options
12993 * @cfg {number} [level] Indentation level
12994 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
12996 OO
.ui
.OutlineOptionWidget
= function OoUiOutlineOptionWidget( config
) {
12997 // Configuration initialization
12998 config
= config
|| {};
13000 // Parent constructor
13001 OO
.ui
.OutlineOptionWidget
.super.call( this, config
);
13005 this.movable
= !!config
.movable
;
13006 this.removable
= !!config
.removable
;
13009 this.$element
.addClass( 'oo-ui-outlineOptionWidget' );
13010 this.setLevel( config
.level
);
13015 OO
.inheritClass( OO
.ui
.OutlineOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
13017 /* Static Properties */
13019 OO
.ui
.OutlineOptionWidget
.static.highlightable
= false;
13021 OO
.ui
.OutlineOptionWidget
.static.scrollIntoViewOnSelect
= true;
13023 OO
.ui
.OutlineOptionWidget
.static.levelClass
= 'oo-ui-outlineOptionWidget-level-';
13025 OO
.ui
.OutlineOptionWidget
.static.levels
= 3;
13030 * Check if item is movable.
13032 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
13034 * @return {boolean} Item is movable
13036 OO
.ui
.OutlineOptionWidget
.prototype.isMovable = function () {
13037 return this.movable
;
13041 * Check if item is removable.
13043 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
13045 * @return {boolean} Item is removable
13047 OO
.ui
.OutlineOptionWidget
.prototype.isRemovable = function () {
13048 return this.removable
;
13052 * Get indentation level.
13054 * @return {number} Indentation level
13056 OO
.ui
.OutlineOptionWidget
.prototype.getLevel = function () {
13063 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
13065 * @param {boolean} movable Item is movable
13068 OO
.ui
.OutlineOptionWidget
.prototype.setMovable = function ( movable
) {
13069 this.movable
= !!movable
;
13070 this.updateThemeClasses();
13075 * Set removability.
13077 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
13079 * @param {boolean} movable Item is removable
13082 OO
.ui
.OutlineOptionWidget
.prototype.setRemovable = function ( removable
) {
13083 this.removable
= !!removable
;
13084 this.updateThemeClasses();
13089 * Set indentation level.
13091 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
13094 OO
.ui
.OutlineOptionWidget
.prototype.setLevel = function ( level
) {
13095 var levels
= this.constructor.static.levels
,
13096 levelClass
= this.constructor.static.levelClass
,
13099 this.level
= level
? Math
.max( 0, Math
.min( levels
- 1, level
) ) : 0;
13101 if ( this.level
=== i
) {
13102 this.$element
.addClass( levelClass
+ i
);
13104 this.$element
.removeClass( levelClass
+ i
);
13107 this.updateThemeClasses();
13113 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
13114 * By default, each popup has an anchor that points toward its origin.
13115 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
13118 * // A popup widget.
13119 * var popup = new OO.ui.PopupWidget( {
13120 * $content: $( '<p>Hi there!</p>' ),
13125 * $( 'body' ).append( popup.$element );
13126 * // To display the popup, toggle the visibility to 'true'.
13127 * popup.toggle( true );
13129 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
13132 * @extends OO.ui.Widget
13133 * @mixins OO.ui.LabelElement
13136 * @param {Object} [config] Configuration options
13137 * @cfg {number} [width=320] Width of popup in pixels
13138 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
13139 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
13140 * @cfg {string} [align='center'] Alignment of the popup: `center`, `left`, or `right`.
13141 * If the popup is right-aligned, the right edge of the popup is aligned to the anchor.
13142 * For left-aligned popups, the left edge is aligned to the anchor.
13143 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
13144 * See the [OOjs UI docs on MediaWiki][3] for an example.
13145 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
13146 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
13147 * @cfg {jQuery} [$content] Content to append to the popup's body
13148 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
13149 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
13150 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
13152 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
13153 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
13155 * @cfg {boolean} [padded] Add padding to the popup's body
13157 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
13158 // Configuration initialization
13159 config
= config
|| {};
13161 // Parent constructor
13162 OO
.ui
.PopupWidget
.super.call( this, config
);
13164 // Properties (must be set before ClippableElement constructor call)
13165 this.$body
= $( '<div>' );
13167 // Mixin constructors
13168 OO
.ui
.LabelElement
.call( this, config
);
13169 OO
.ui
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$body
} ) );
13172 this.$popup
= $( '<div>' );
13173 this.$head
= $( '<div>' );
13174 this.$anchor
= $( '<div>' );
13175 // If undefined, will be computed lazily in updateDimensions()
13176 this.$container
= config
.$container
;
13177 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
13178 this.autoClose
= !!config
.autoClose
;
13179 this.$autoCloseIgnore
= config
.$autoCloseIgnore
;
13180 this.transitionTimeout
= null;
13181 this.anchor
= null;
13182 this.width
= config
.width
!== undefined ? config
.width
: 320;
13183 this.height
= config
.height
!== undefined ? config
.height
: null;
13184 this.align
= config
.align
|| 'center';
13185 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
13186 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
13187 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
13190 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
13193 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
13194 this.$body
.addClass( 'oo-ui-popupWidget-body' );
13195 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
13197 .addClass( 'oo-ui-popupWidget-head' )
13198 .append( this.$label
, this.closeButton
.$element
);
13199 if ( !config
.head
) {
13200 this.$head
.addClass( 'oo-ui-element-hidden' );
13203 .addClass( 'oo-ui-popupWidget-popup' )
13204 .append( this.$head
, this.$body
);
13206 .addClass( 'oo-ui-popupWidget' )
13207 .append( this.$popup
, this.$anchor
);
13208 // Move content, which was added to #$element by OO.ui.Widget, to the body
13209 if ( config
.$content
instanceof jQuery
) {
13210 this.$body
.append( config
.$content
);
13212 if ( config
.padded
) {
13213 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
13216 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
13217 // that reference properties not initialized at that time of parent class construction
13218 // TODO: Find a better way to handle post-constructor setup
13219 this.visible
= false;
13220 this.$element
.addClass( 'oo-ui-element-hidden' );
13225 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
13226 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.LabelElement
);
13227 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.ClippableElement
);
13232 * Handles mouse down events.
13235 * @param {MouseEvent} e Mouse down event
13237 OO
.ui
.PopupWidget
.prototype.onMouseDown = function ( e
) {
13239 this.isVisible() &&
13240 !$.contains( this.$element
[ 0 ], e
.target
) &&
13241 ( !this.$autoCloseIgnore
|| !this.$autoCloseIgnore
.has( e
.target
).length
)
13243 this.toggle( false );
13248 * Bind mouse down listener.
13252 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
13253 // Capture clicks outside popup
13254 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler
, true );
13258 * Handles close button click events.
13262 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
13263 if ( this.isVisible() ) {
13264 this.toggle( false );
13269 * Unbind mouse down listener.
13273 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
13274 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler
, true );
13278 * Handles key down events.
13281 * @param {KeyboardEvent} e Key down event
13283 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
13285 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
13288 this.toggle( false );
13289 e
.preventDefault();
13290 e
.stopPropagation();
13295 * Bind key down listener.
13299 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
13300 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
13304 * Unbind key down listener.
13308 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
13309 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
13313 * Show, hide, or toggle the visibility of the anchor.
13315 * @param {boolean} [show] Show anchor, omit to toggle
13317 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
13318 show
= show
=== undefined ? !this.anchored
: !!show
;
13320 if ( this.anchored
!== show
) {
13322 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
13324 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
13326 this.anchored
= show
;
13331 * Check if the anchor is visible.
13333 * @return {boolean} Anchor is visible
13335 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
13336 return this.anchor
;
13342 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
13343 show
= show
=== undefined ? !this.isVisible() : !!show
;
13345 var change
= show
!== this.isVisible();
13348 OO
.ui
.PopupWidget
.super.prototype.toggle
.call( this, show
);
13352 if ( this.autoClose
) {
13353 this.bindMouseDownListener();
13354 this.bindKeyDownListener();
13356 this.updateDimensions();
13357 this.toggleClipping( true );
13359 this.toggleClipping( false );
13360 if ( this.autoClose
) {
13361 this.unbindMouseDownListener();
13362 this.unbindKeyDownListener();
13371 * Set the size of the popup.
13373 * Changing the size may also change the popup's position depending on the alignment.
13375 * @param {number} width Width in pixels
13376 * @param {number} height Height in pixels
13377 * @param {boolean} [transition=false] Use a smooth transition
13380 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
13381 this.width
= width
;
13382 this.height
= height
!== undefined ? height
: null;
13383 if ( this.isVisible() ) {
13384 this.updateDimensions( transition
);
13389 * Update the size and position.
13391 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
13392 * be called automatically.
13394 * @param {boolean} [transition=false] Use a smooth transition
13397 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
13398 var popupOffset
, originOffset
, containerLeft
, containerWidth
, containerRight
,
13399 popupLeft
, popupRight
, overlapLeft
, overlapRight
, anchorWidth
,
13402 if ( !this.$container
) {
13403 // Lazy-initialize $container if not specified in constructor
13404 this.$container
= $( this.getClosestScrollableElementContainer() );
13407 // Set height and width before measuring things, since it might cause our measurements
13408 // to change (e.g. due to scrollbars appearing or disappearing)
13411 height
: this.height
!== null ? this.height
: 'auto'
13414 // Compute initial popupOffset based on alignment
13415 popupOffset
= this.width
* ( { left
: 0, center
: -0.5, right
: -1 } )[ this.align
];
13417 // Figure out if this will cause the popup to go beyond the edge of the container
13418 originOffset
= this.$element
.offset().left
;
13419 containerLeft
= this.$container
.offset().left
;
13420 containerWidth
= this.$container
.innerWidth();
13421 containerRight
= containerLeft
+ containerWidth
;
13422 popupLeft
= popupOffset
- this.containerPadding
;
13423 popupRight
= popupOffset
+ this.containerPadding
+ this.width
+ this.containerPadding
;
13424 overlapLeft
= ( originOffset
+ popupLeft
) - containerLeft
;
13425 overlapRight
= containerRight
- ( originOffset
+ popupRight
);
13427 // Adjust offset to make the popup not go beyond the edge, if needed
13428 if ( overlapRight
< 0 ) {
13429 popupOffset
+= overlapRight
;
13430 } else if ( overlapLeft
< 0 ) {
13431 popupOffset
-= overlapLeft
;
13434 // Adjust offset to avoid anchor being rendered too close to the edge
13435 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
13436 // TODO: Find a measurement that works for CSS anchors and image anchors
13437 anchorWidth
= this.$anchor
[ 0 ].scrollWidth
* 2;
13438 if ( popupOffset
+ this.width
< anchorWidth
) {
13439 popupOffset
= anchorWidth
- this.width
;
13440 } else if ( -popupOffset
< anchorWidth
) {
13441 popupOffset
= -anchorWidth
;
13444 // Prevent transition from being interrupted
13445 clearTimeout( this.transitionTimeout
);
13446 if ( transition
) {
13447 // Enable transition
13448 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
13451 // Position body relative to anchor
13452 this.$popup
.css( 'margin-left', popupOffset
);
13454 if ( transition
) {
13455 // Prevent transitioning after transition is complete
13456 this.transitionTimeout
= setTimeout( function () {
13457 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
13460 // Prevent transitioning immediately
13461 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
13464 // Reevaluate clipping state since we've relocated and resized the popup
13471 * Progress bars visually display the status of an operation, such as a download,
13472 * and can be either determinate or indeterminate:
13474 * - **determinate** process bars show the percent of an operation that is complete.
13476 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
13477 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
13478 * not use percentages.
13480 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
13483 * // Examples of determinate and indeterminate progress bars.
13484 * var progressBar1 = new OO.ui.ProgressBarWidget( {
13487 * var progressBar2 = new OO.ui.ProgressBarWidget();
13489 * // Create a FieldsetLayout to layout progress bars
13490 * var fieldset = new OO.ui.FieldsetLayout;
13491 * fieldset.addItems( [
13492 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
13493 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
13495 * $( 'body' ).append( fieldset.$element );
13498 * @extends OO.ui.Widget
13501 * @param {Object} [config] Configuration options
13502 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
13503 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
13504 * By default, the progress bar is indeterminate.
13506 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
13507 // Configuration initialization
13508 config
= config
|| {};
13510 // Parent constructor
13511 OO
.ui
.ProgressBarWidget
.super.call( this, config
);
13514 this.$bar
= $( '<div>' );
13515 this.progress
= null;
13518 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
13519 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
13522 role
: 'progressbar',
13523 'aria-valuemin': 0,
13524 'aria-valuemax': 100
13526 .addClass( 'oo-ui-progressBarWidget' )
13527 .append( this.$bar
);
13532 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
13534 /* Static Properties */
13536 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
13541 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
13543 * @return {number|boolean} Progress percent
13545 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
13546 return this.progress
;
13550 * Set the percent of the process completed or `false` for an indeterminate process.
13552 * @param {number|boolean} progress Progress percent or `false` for indeterminate
13554 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
13555 this.progress
= progress
;
13557 if ( progress
!== false ) {
13558 this.$bar
.css( 'width', this.progress
+ '%' );
13559 this.$element
.attr( 'aria-valuenow', this.progress
);
13561 this.$bar
.css( 'width', '' );
13562 this.$element
.removeAttr( 'aria-valuenow' );
13564 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress
);
13568 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
13569 * and a {@link OO.ui.TextInputMenuSelectWidget menu} of search results, which is displayed beneath the query
13570 * field. Unlike {@link OO.ui.LookupElement lookup menus}, search result menus are always visible to the user.
13571 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
13572 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
13574 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
13575 * the [OOjs UI demos][1] for an example.
13577 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
13580 * @extends OO.ui.Widget
13583 * @param {Object} [config] Configuration options
13584 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
13585 * @cfg {string} [value] Initial query value
13587 OO
.ui
.SearchWidget
= function OoUiSearchWidget( config
) {
13588 // Configuration initialization
13589 config
= config
|| {};
13591 // Parent constructor
13592 OO
.ui
.SearchWidget
.super.call( this, config
);
13595 this.query
= new OO
.ui
.TextInputWidget( {
13597 placeholder
: config
.placeholder
,
13598 value
: config
.value
13600 this.results
= new OO
.ui
.SelectWidget();
13601 this.$query
= $( '<div>' );
13602 this.$results
= $( '<div>' );
13605 this.query
.connect( this, {
13606 change
: 'onQueryChange',
13607 enter
: 'onQueryEnter'
13609 this.results
.connect( this, {
13610 highlight
: 'onResultsHighlight',
13611 select
: 'onResultsSelect'
13613 this.query
.$input
.on( 'keydown', this.onQueryKeydown
.bind( this ) );
13617 .addClass( 'oo-ui-searchWidget-query' )
13618 .append( this.query
.$element
);
13620 .addClass( 'oo-ui-searchWidget-results' )
13621 .append( this.results
.$element
);
13623 .addClass( 'oo-ui-searchWidget' )
13624 .append( this.$results
, this.$query
);
13629 OO
.inheritClass( OO
.ui
.SearchWidget
, OO
.ui
.Widget
);
13634 * A 'highlight' event is emitted when an item is highlighted. The highlight indicates which
13635 * item will be selected. When a user mouses over a menu item, it is highlighted. If a search
13636 * string is typed into the query field instead, the first menu item that matches the query
13637 * will be highlighted.
13640 * @deprecated Connect straight to getResults() events instead
13641 * @param {Object|null} item Item data or null if no item is highlighted
13645 * A 'select' event is emitted when an item is selected. A menu item is selected when it is clicked,
13646 * or when a user types a search query, a menu result is highlighted, and the user presses enter.
13649 * @deprecated Connect straight to getResults() events instead
13650 * @param {Object|null} item Item data or null if no item is selected
13656 * Handle query key down events.
13659 * @param {jQuery.Event} e Key down event
13661 OO
.ui
.SearchWidget
.prototype.onQueryKeydown = function ( e
) {
13662 var highlightedItem
, nextItem
,
13663 dir
= e
.which
=== OO
.ui
.Keys
.DOWN
? 1 : ( e
.which
=== OO
.ui
.Keys
.UP
? -1 : 0 );
13666 highlightedItem
= this.results
.getHighlightedItem();
13667 if ( !highlightedItem
) {
13668 highlightedItem
= this.results
.getSelectedItem();
13670 nextItem
= this.results
.getRelativeSelectableItem( highlightedItem
, dir
);
13671 this.results
.highlightItem( nextItem
);
13672 nextItem
.scrollElementIntoView();
13677 * Handle select widget select events.
13679 * Clears existing results. Subclasses should repopulate items according to new query.
13682 * @param {string} value New value
13684 OO
.ui
.SearchWidget
.prototype.onQueryChange = function () {
13686 this.results
.clearItems();
13690 * Handle select widget enter key events.
13692 * Selects highlighted item.
13695 * @param {string} value New value
13697 OO
.ui
.SearchWidget
.prototype.onQueryEnter = function () {
13699 this.results
.selectItem( this.results
.getHighlightedItem() );
13703 * Handle select widget highlight events.
13706 * @deprecated Connect straight to getResults() events instead
13707 * @param {OO.ui.OptionWidget} item Highlighted item
13710 OO
.ui
.SearchWidget
.prototype.onResultsHighlight = function ( item
) {
13711 this.emit( 'highlight', item
? item
.getData() : null );
13715 * Handle select widget select events.
13718 * @deprecated Connect straight to getResults() events instead
13719 * @param {OO.ui.OptionWidget} item Selected item
13722 OO
.ui
.SearchWidget
.prototype.onResultsSelect = function ( item
) {
13723 this.emit( 'select', item
? item
.getData() : null );
13727 * Get the query input.
13729 * @return {OO.ui.TextInputWidget} Query input
13731 OO
.ui
.SearchWidget
.prototype.getQuery = function () {
13736 * Get the search results menu.
13738 * @return {OO.ui.SelectWidget} Menu of search results
13740 OO
.ui
.SearchWidget
.prototype.getResults = function () {
13741 return this.results
;
13745 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
13746 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
13747 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
13750 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
13751 * information, please see the [OOjs UI documentation on MediaWiki][1].
13754 * // Example of a select widget with three options
13755 * var select = new OO.ui.SelectWidget( {
13757 * new OO.ui.OptionWidget( {
13759 * label: 'Option One',
13761 * new OO.ui.OptionWidget( {
13763 * label: 'Option Two',
13765 * new OO.ui.OptionWidget( {
13767 * label: 'Option Three',
13771 * $( 'body' ).append( select.$element );
13773 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
13776 * @extends OO.ui.Widget
13777 * @mixins OO.ui.GroupElement
13780 * @param {Object} [config] Configuration options
13781 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
13782 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
13783 * the [OOjs UI documentation on MediaWiki] [2] for examples.
13784 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
13786 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
13787 // Configuration initialization
13788 config
= config
|| {};
13790 // Parent constructor
13791 OO
.ui
.SelectWidget
.super.call( this, config
);
13793 // Mixin constructors
13794 OO
.ui
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
13797 this.pressed
= false;
13798 this.selecting
= null;
13799 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
13800 this.onMouseMoveHandler
= this.onMouseMove
.bind( this );
13801 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
13804 this.$element
.on( {
13805 mousedown
: this.onMouseDown
.bind( this ),
13806 mouseover
: this.onMouseOver
.bind( this ),
13807 mouseleave
: this.onMouseLeave
.bind( this )
13812 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
13813 .attr( 'role', 'listbox' );
13814 if ( Array
.isArray( config
.items
) ) {
13815 this.addItems( config
.items
);
13821 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
13823 // Need to mixin base class as well
13824 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.GroupElement
);
13825 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.GroupWidget
);
13832 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
13834 * @param {OO.ui.OptionWidget|null} item Highlighted item
13840 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
13841 * pressed state of an option.
13843 * @param {OO.ui.OptionWidget|null} item Pressed item
13849 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
13851 * @param {OO.ui.OptionWidget|null} item Selected item
13856 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
13857 * @param {OO.ui.OptionWidget} item Chosen item
13863 * An `add` event is emitted when options are added to the select with the #addItems method.
13865 * @param {OO.ui.OptionWidget[]} items Added items
13866 * @param {number} index Index of insertion point
13872 * A `remove` event is emitted when options are removed from the select with the #clearItems
13873 * or #removeItems methods.
13875 * @param {OO.ui.OptionWidget[]} items Removed items
13881 * Handle mouse down events.
13884 * @param {jQuery.Event} e Mouse down event
13886 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
13889 if ( !this.isDisabled() && e
.which
=== 1 ) {
13890 this.togglePressed( true );
13891 item
= this.getTargetItem( e
);
13892 if ( item
&& item
.isSelectable() ) {
13893 this.pressItem( item
);
13894 this.selecting
= item
;
13895 this.getElementDocument().addEventListener(
13897 this.onMouseUpHandler
,
13900 this.getElementDocument().addEventListener(
13902 this.onMouseMoveHandler
,
13911 * Handle mouse up events.
13914 * @param {jQuery.Event} e Mouse up event
13916 OO
.ui
.SelectWidget
.prototype.onMouseUp = function ( e
) {
13919 this.togglePressed( false );
13920 if ( !this.selecting
) {
13921 item
= this.getTargetItem( e
);
13922 if ( item
&& item
.isSelectable() ) {
13923 this.selecting
= item
;
13926 if ( !this.isDisabled() && e
.which
=== 1 && this.selecting
) {
13927 this.pressItem( null );
13928 this.chooseItem( this.selecting
);
13929 this.selecting
= null;
13932 this.getElementDocument().removeEventListener(
13934 this.onMouseUpHandler
,
13937 this.getElementDocument().removeEventListener(
13939 this.onMouseMoveHandler
,
13947 * Handle mouse move events.
13950 * @param {jQuery.Event} e Mouse move event
13952 OO
.ui
.SelectWidget
.prototype.onMouseMove = function ( e
) {
13955 if ( !this.isDisabled() && this.pressed
) {
13956 item
= this.getTargetItem( e
);
13957 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
13958 this.pressItem( item
);
13959 this.selecting
= item
;
13966 * Handle mouse over events.
13969 * @param {jQuery.Event} e Mouse over event
13971 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
13974 if ( !this.isDisabled() ) {
13975 item
= this.getTargetItem( e
);
13976 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
13982 * Handle mouse leave events.
13985 * @param {jQuery.Event} e Mouse over event
13987 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
13988 if ( !this.isDisabled() ) {
13989 this.highlightItem( null );
13995 * Handle key down events.
13998 * @param {jQuery.Event} e Key down event
14000 OO
.ui
.SelectWidget
.prototype.onKeyDown = function ( e
) {
14003 currentItem
= this.getHighlightedItem() || this.getSelectedItem();
14005 if ( !this.isDisabled() && this.isVisible() ) {
14006 switch ( e
.keyCode
) {
14007 case OO
.ui
.Keys
.ENTER
:
14008 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
14009 // Was only highlighted, now let's select it. No-op if already selected.
14010 this.chooseItem( currentItem
);
14014 case OO
.ui
.Keys
.UP
:
14015 case OO
.ui
.Keys
.LEFT
:
14016 nextItem
= this.getRelativeSelectableItem( currentItem
, -1 );
14019 case OO
.ui
.Keys
.DOWN
:
14020 case OO
.ui
.Keys
.RIGHT
:
14021 nextItem
= this.getRelativeSelectableItem( currentItem
, 1 );
14024 case OO
.ui
.Keys
.ESCAPE
:
14025 case OO
.ui
.Keys
.TAB
:
14026 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
14027 currentItem
.setHighlighted( false );
14029 this.unbindKeyDownListener();
14030 // Don't prevent tabbing away / defocusing
14036 if ( nextItem
.constructor.static.highlightable
) {
14037 this.highlightItem( nextItem
);
14039 this.chooseItem( nextItem
);
14041 nextItem
.scrollElementIntoView();
14045 // Can't just return false, because e is not always a jQuery event
14046 e
.preventDefault();
14047 e
.stopPropagation();
14053 * Bind key down listener.
14057 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
14058 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler
, true );
14062 * Unbind key down listener.
14066 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
14067 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler
, true );
14071 * Get the closest item to a jQuery.Event.
14074 * @param {jQuery.Event} e
14075 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
14077 OO
.ui
.SelectWidget
.prototype.getTargetItem = function ( e
) {
14078 var $item
= $( e
.target
).closest( '.oo-ui-optionWidget' );
14079 if ( $item
.length
) {
14080 return $item
.data( 'oo-ui-optionWidget' );
14086 * Get selected item.
14088 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
14090 OO
.ui
.SelectWidget
.prototype.getSelectedItem = function () {
14093 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
14094 if ( this.items
[ i
].isSelected() ) {
14095 return this.items
[ i
];
14102 * Get highlighted item.
14104 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
14106 OO
.ui
.SelectWidget
.prototype.getHighlightedItem = function () {
14109 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
14110 if ( this.items
[ i
].isHighlighted() ) {
14111 return this.items
[ i
];
14118 * Toggle pressed state.
14120 * Press is a state that occurs when a user mouses down on an item, but
14121 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
14122 * until the user releases the mouse.
14124 * @param {boolean} pressed An option is being pressed
14126 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
14127 if ( pressed
=== undefined ) {
14128 pressed
= !this.pressed
;
14130 if ( pressed
!== this.pressed
) {
14132 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
14133 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
14134 this.pressed
= pressed
;
14139 * Highlight an option. If the `item` param is omitted, no options will be highlighted
14140 * and any existing highlight will be removed. The highlight is mutually exclusive.
14142 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
14146 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
14147 var i
, len
, highlighted
,
14150 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
14151 highlighted
= this.items
[ i
] === item
;
14152 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
14153 this.items
[ i
].setHighlighted( highlighted
);
14158 this.emit( 'highlight', item
);
14165 * Programmatically select an option by its reference. If the `item` parameter is omitted,
14166 * all options will be deselected.
14168 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
14172 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
14173 var i
, len
, selected
,
14176 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
14177 selected
= this.items
[ i
] === item
;
14178 if ( this.items
[ i
].isSelected() !== selected
) {
14179 this.items
[ i
].setSelected( selected
);
14184 this.emit( 'select', item
);
14193 * Press is a state that occurs when a user mouses down on an item, but has not
14194 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
14195 * releases the mouse.
14197 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
14201 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
14202 var i
, len
, pressed
,
14205 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
14206 pressed
= this.items
[ i
] === item
;
14207 if ( this.items
[ i
].isPressed() !== pressed
) {
14208 this.items
[ i
].setPressed( pressed
);
14213 this.emit( 'press', item
);
14222 * Note that ‘choose’ should never be modified programmatically. A user can choose
14223 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
14224 * use the #selectItem method.
14226 * This method is identical to #selectItem, but may vary in subclasses that take additional action
14227 * when users choose an item with the keyboard or mouse.
14229 * @param {OO.ui.OptionWidget} item Item to choose
14233 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
14234 this.selectItem( item
);
14235 this.emit( 'choose', item
);
14241 * Get an option by its position relative to the specified item (or to the start of the option array,
14242 * if item is `null`). The direction in which to search through the option array is specified with a
14243 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
14244 * `null` if there are no options in the array.
14246 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
14247 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
14248 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
14250 OO
.ui
.SelectWidget
.prototype.getRelativeSelectableItem = function ( item
, direction
) {
14251 var currentIndex
, nextIndex
, i
,
14252 increase
= direction
> 0 ? 1 : -1,
14253 len
= this.items
.length
;
14255 if ( item
instanceof OO
.ui
.OptionWidget
) {
14256 currentIndex
= $.inArray( item
, this.items
);
14257 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
14259 // If no item is selected and moving forward, start at the beginning.
14260 // If moving backward, start at the end.
14261 nextIndex
= direction
> 0 ? 0 : len
- 1;
14264 for ( i
= 0; i
< len
; i
++ ) {
14265 item
= this.items
[ nextIndex
];
14266 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() ) {
14269 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
14275 * Get the next selectable item or `null` if there are no selectable items.
14276 * Disabled options and menu-section markers and breaks are not selectable.
14278 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
14280 OO
.ui
.SelectWidget
.prototype.getFirstSelectableItem = function () {
14283 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
14284 item
= this.items
[ i
];
14285 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() ) {
14294 * Add an array of options to the select. Optionally, an index number can be used to
14295 * specify an insertion point.
14297 * @param {OO.ui.OptionWidget[]} items Items to add
14298 * @param {number} [index] Index to insert items after
14302 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
14304 OO
.ui
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
14306 // Always provide an index, even if it was omitted
14307 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
14313 * Remove the specified array of options from the select. Options will be detached
14314 * from the DOM, not removed, so they can be reused later. To remove all options from
14315 * the select, you may wish to use the #clearItems method instead.
14317 * @param {OO.ui.OptionWidget[]} items Items to remove
14321 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
14324 // Deselect items being removed
14325 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
14327 if ( item
.isSelected() ) {
14328 this.selectItem( null );
14333 OO
.ui
.GroupWidget
.prototype.removeItems
.call( this, items
);
14335 this.emit( 'remove', items
);
14341 * Clear all options from the select. Options will be detached from the DOM, not removed,
14342 * so that they can be reused later. To remove a subset of options from the select, use
14343 * the #removeItems method.
14348 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
14349 var items
= this.items
.slice();
14352 OO
.ui
.GroupWidget
.prototype.clearItems
.call( this );
14355 this.selectItem( null );
14357 this.emit( 'remove', items
);
14363 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
14364 * button options and is used together with
14365 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
14366 * highlighting, choosing, and selecting mutually exclusive options. Please see
14367 * the [OOjs UI documentation on MediaWiki] [1] for more information.
14370 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
14371 * var option1 = new OO.ui.ButtonOptionWidget( {
14373 * label: 'Option 1',
14374 * title: 'Button option 1'
14377 * var option2 = new OO.ui.ButtonOptionWidget( {
14379 * label: 'Option 2',
14380 * title: 'Button option 2'
14383 * var option3 = new OO.ui.ButtonOptionWidget( {
14385 * label: 'Option 3',
14386 * title: 'Button option 3'
14389 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
14390 * items: [ option1, option2, option3 ]
14392 * $( 'body' ).append( buttonSelect.$element );
14394 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14397 * @extends OO.ui.SelectWidget
14398 * @mixins OO.ui.TabIndexedElement
14401 * @param {Object} [config] Configuration options
14403 OO
.ui
.ButtonSelectWidget
= function OoUiButtonSelectWidget( config
) {
14404 // Parent constructor
14405 OO
.ui
.ButtonSelectWidget
.super.call( this, config
);
14407 // Mixin constructors
14408 OO
.ui
.TabIndexedElement
.call( this, config
);
14411 this.$element
.on( {
14412 focus
: this.bindKeyDownListener
.bind( this ),
14413 blur
: this.unbindKeyDownListener
.bind( this )
14417 this.$element
.addClass( 'oo-ui-buttonSelectWidget' );
14422 OO
.inheritClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.SelectWidget
);
14423 OO
.mixinClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.TabIndexedElement
);
14426 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
14427 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
14428 * an interface for adding, removing and selecting options.
14429 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
14432 * // A RadioSelectWidget with RadioOptions.
14433 * var option1 = new OO.ui.RadioOptionWidget( {
14435 * label: 'Selected radio option'
14438 * var option2 = new OO.ui.RadioOptionWidget( {
14440 * label: 'Unselected radio option'
14443 * var radioSelect=new OO.ui.RadioSelectWidget( {
14444 * items: [ option1, option2 ]
14447 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
14448 * radioSelect.selectItem( option1 );
14450 * $( 'body' ).append( radioSelect.$element );
14452 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14456 * @extends OO.ui.SelectWidget
14457 * @mixins OO.ui.TabIndexedElement
14460 * @param {Object} [config] Configuration options
14462 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
14463 // Parent constructor
14464 OO
.ui
.RadioSelectWidget
.super.call( this, config
);
14466 // Mixin constructors
14467 OO
.ui
.TabIndexedElement
.call( this, config
);
14470 this.$element
.on( {
14471 focus
: this.bindKeyDownListener
.bind( this ),
14472 blur
: this.unbindKeyDownListener
.bind( this )
14476 this.$element
.addClass( 'oo-ui-radioSelectWidget' );
14481 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
14482 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.TabIndexedElement
);
14485 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
14486 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
14487 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxWidget ComboBoxWidget},
14488 * and {@link OO.ui.LookupElement LookupElement} for examples of widgets that contain menus.
14489 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
14490 * and customized to be opened, closed, and displayed as needed.
14492 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
14493 * mouse outside the menu.
14495 * Menus also have support for keyboard interaction:
14497 * - Enter/Return key: choose and select a menu option
14498 * - Up-arrow key: highlight the previous menu option
14499 * - Down-arrow key: highlight the next menu option
14500 * - Esc key: hide the menu
14502 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
14503 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14506 * @extends OO.ui.SelectWidget
14507 * @mixins OO.ui.ClippableElement
14510 * @param {Object} [config] Configuration options
14511 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
14512 * the text the user types. This config is used by {@link OO.ui.ComboBoxWidget ComboBoxWidget}
14513 * and {@link OO.ui.LookupElement LookupElement}
14514 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu’s active state. If the user clicks the mouse
14515 * anywhere on the page outside of this widget, the menu is hidden.
14516 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
14518 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
14519 // Configuration initialization
14520 config
= config
|| {};
14522 // Parent constructor
14523 OO
.ui
.MenuSelectWidget
.super.call( this, config
);
14525 // Mixin constructors
14526 OO
.ui
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
14529 this.newItems
= null;
14530 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
14531 this.$input
= config
.input
? config
.input
.$input
: null;
14532 this.$widget
= config
.widget
? config
.widget
.$element
: null;
14533 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
14537 .addClass( 'oo-ui-menuSelectWidget' )
14538 .attr( 'role', 'menu' );
14540 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
14541 // that reference properties not initialized at that time of parent class construction
14542 // TODO: Find a better way to handle post-constructor setup
14543 this.visible
= false;
14544 this.$element
.addClass( 'oo-ui-element-hidden' );
14549 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
14550 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.ClippableElement
);
14555 * Handles document mouse down events.
14558 * @param {jQuery.Event} e Key down event
14560 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
14562 !OO
.ui
.contains( this.$element
[ 0 ], e
.target
, true ) &&
14563 ( !this.$widget
|| !OO
.ui
.contains( this.$widget
[ 0 ], e
.target
, true ) )
14565 this.toggle( false );
14572 OO
.ui
.MenuSelectWidget
.prototype.onKeyDown = function ( e
) {
14573 var currentItem
= this.getHighlightedItem() || this.getSelectedItem();
14575 if ( !this.isDisabled() && this.isVisible() ) {
14576 switch ( e
.keyCode
) {
14577 case OO
.ui
.Keys
.LEFT
:
14578 case OO
.ui
.Keys
.RIGHT
:
14579 // Do nothing if a text field is associated, arrow keys will be handled natively
14580 if ( !this.$input
) {
14581 OO
.ui
.MenuSelectWidget
.super.prototype.onKeyDown
.call( this, e
);
14584 case OO
.ui
.Keys
.ESCAPE
:
14585 case OO
.ui
.Keys
.TAB
:
14586 if ( currentItem
) {
14587 currentItem
.setHighlighted( false );
14589 this.toggle( false );
14590 // Don't prevent tabbing away, prevent defocusing
14591 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
14592 e
.preventDefault();
14593 e
.stopPropagation();
14597 OO
.ui
.MenuSelectWidget
.super.prototype.onKeyDown
.call( this, e
);
14606 OO
.ui
.MenuSelectWidget
.prototype.bindKeyDownListener = function () {
14607 if ( this.$input
) {
14608 this.$input
.on( 'keydown', this.onKeyDownHandler
);
14610 OO
.ui
.MenuSelectWidget
.super.prototype.bindKeyDownListener
.call( this );
14617 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyDownListener = function () {
14618 if ( this.$input
) {
14619 this.$input
.off( 'keydown', this.onKeyDownHandler
);
14621 OO
.ui
.MenuSelectWidget
.super.prototype.unbindKeyDownListener
.call( this );
14628 * When a user chooses an item, the menu is closed.
14630 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
14631 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
14632 * @param {OO.ui.OptionWidget} item Item to choose
14635 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
14636 OO
.ui
.MenuSelectWidget
.super.prototype.chooseItem
.call( this, item
);
14637 this.toggle( false );
14644 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
14648 OO
.ui
.MenuSelectWidget
.super.prototype.addItems
.call( this, items
, index
);
14651 if ( !this.newItems
) {
14652 this.newItems
= [];
14655 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
14657 if ( this.isVisible() ) {
14658 // Defer fitting label until item has been attached
14661 this.newItems
.push( item
);
14665 // Reevaluate clipping
14674 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
14676 OO
.ui
.MenuSelectWidget
.super.prototype.removeItems
.call( this, items
);
14678 // Reevaluate clipping
14687 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
14689 OO
.ui
.MenuSelectWidget
.super.prototype.clearItems
.call( this );
14691 // Reevaluate clipping
14700 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
14701 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
14704 change
= visible
!== this.isVisible();
14707 OO
.ui
.MenuSelectWidget
.super.prototype.toggle
.call( this, visible
);
14711 this.bindKeyDownListener();
14713 if ( this.newItems
&& this.newItems
.length
) {
14714 for ( i
= 0, len
= this.newItems
.length
; i
< len
; i
++ ) {
14715 this.newItems
[ i
].fitLabel();
14717 this.newItems
= null;
14719 this.toggleClipping( true );
14722 if ( this.autoHide
) {
14723 this.getElementDocument().addEventListener(
14724 'mousedown', this.onDocumentMouseDownHandler
, true
14728 this.unbindKeyDownListener();
14729 this.getElementDocument().removeEventListener(
14730 'mousedown', this.onDocumentMouseDownHandler
, true
14732 this.toggleClipping( false );
14740 * TextInputMenuSelectWidget is a menu that is specially designed to be positioned beneath
14741 * a {@link OO.ui.TextInputWidget text input} field. The menu's position is automatically
14742 * calculated and maintained when the menu is toggled or the window is resized.
14743 * See OO.ui.ComboBoxWidget for an example of a widget that uses this class.
14746 * @extends OO.ui.MenuSelectWidget
14749 * @param {OO.ui.TextInputWidget} inputWidget Text input widget to provide menu for
14750 * @param {Object} [config] Configuration options
14751 * @cfg {jQuery} [$container=input.$element] Element to render menu under
14753 OO
.ui
.TextInputMenuSelectWidget
= function OoUiTextInputMenuSelectWidget( inputWidget
, config
) {
14754 // Allow passing positional parameters inside the config object
14755 if ( OO
.isPlainObject( inputWidget
) && config
=== undefined ) {
14756 config
= inputWidget
;
14757 inputWidget
= config
.inputWidget
;
14760 // Configuration initialization
14761 config
= config
|| {};
14763 // Parent constructor
14764 OO
.ui
.TextInputMenuSelectWidget
.super.call( this, config
);
14767 this.inputWidget
= inputWidget
;
14768 this.$container
= config
.$container
|| this.inputWidget
.$element
;
14769 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
14772 this.$element
.addClass( 'oo-ui-textInputMenuSelectWidget' );
14777 OO
.inheritClass( OO
.ui
.TextInputMenuSelectWidget
, OO
.ui
.MenuSelectWidget
);
14782 * Handle window resize event.
14785 * @param {jQuery.Event} e Window resize event
14787 OO
.ui
.TextInputMenuSelectWidget
.prototype.onWindowResize = function () {
14794 OO
.ui
.TextInputMenuSelectWidget
.prototype.toggle = function ( visible
) {
14795 visible
= visible
=== undefined ? !this.isVisible() : !!visible
;
14797 var change
= visible
!== this.isVisible();
14799 if ( change
&& visible
) {
14800 // Make sure the width is set before the parent method runs.
14801 // After this we have to call this.position(); again to actually
14802 // position ourselves correctly.
14807 OO
.ui
.TextInputMenuSelectWidget
.super.prototype.toggle
.call( this, visible
);
14810 if ( this.isVisible() ) {
14812 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler
);
14814 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler
);
14822 * Position the menu.
14827 OO
.ui
.TextInputMenuSelectWidget
.prototype.position = function () {
14828 var $container
= this.$container
,
14829 pos
= OO
.ui
.Element
.static.getRelativePosition( $container
, this.$element
.offsetParent() );
14831 // Position under input
14832 pos
.top
+= $container
.height();
14833 this.$element
.css( pos
);
14836 this.setIdealSize( $container
.width() );
14837 // We updated the position, so re-evaluate the clipping state
14844 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
14845 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
14847 * ####Currently, this class is only used by {@link OO.ui.BookletLayout BookletLayouts}.####
14850 * @extends OO.ui.SelectWidget
14851 * @mixins OO.ui.TabIndexedElement
14854 * @param {Object} [config] Configuration options
14856 OO
.ui
.OutlineSelectWidget
= function OoUiOutlineSelectWidget( config
) {
14857 // Parent constructor
14858 OO
.ui
.OutlineSelectWidget
.super.call( this, config
);
14860 // Mixin constructors
14861 OO
.ui
.TabIndexedElement
.call( this, config
);
14864 this.$element
.on( {
14865 focus
: this.bindKeyDownListener
.bind( this ),
14866 blur
: this.unbindKeyDownListener
.bind( this )
14870 this.$element
.addClass( 'oo-ui-outlineSelectWidget' );
14875 OO
.inheritClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.SelectWidget
);
14876 OO
.mixinClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.TabIndexedElement
);
14879 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
14880 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
14881 * visually by a slider in the leftmost position.
14884 * // Toggle switches in the 'off' and 'on' position.
14885 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
14886 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
14890 * // Create a FieldsetLayout to layout and label switches
14891 * var fieldset = new OO.ui.FieldsetLayout( {
14892 * label: 'Toggle switches'
14894 * fieldset.addItems( [
14895 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
14896 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
14898 * $( 'body' ).append( fieldset.$element );
14901 * @extends OO.ui.Widget
14902 * @mixins OO.ui.ToggleWidget
14903 * @mixins OO.ui.TabIndexedElement
14906 * @param {Object} [config] Configuration options
14907 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
14908 * By default, the toggle switch is in the 'off' position.
14910 OO
.ui
.ToggleSwitchWidget
= function OoUiToggleSwitchWidget( config
) {
14911 // Parent constructor
14912 OO
.ui
.ToggleSwitchWidget
.super.call( this, config
);
14914 // Mixin constructors
14915 OO
.ui
.ToggleWidget
.call( this, config
);
14916 OO
.ui
.TabIndexedElement
.call( this, config
);
14919 this.dragging
= false;
14920 this.dragStart
= null;
14921 this.sliding
= false;
14922 this.$glow
= $( '<span>' );
14923 this.$grip
= $( '<span>' );
14926 this.$element
.on( {
14927 click
: this.onClick
.bind( this ),
14928 keypress
: this.onKeyPress
.bind( this )
14932 this.$glow
.addClass( 'oo-ui-toggleSwitchWidget-glow' );
14933 this.$grip
.addClass( 'oo-ui-toggleSwitchWidget-grip' );
14935 .addClass( 'oo-ui-toggleSwitchWidget' )
14936 .attr( 'role', 'checkbox' )
14937 .append( this.$glow
, this.$grip
);
14942 OO
.inheritClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.Widget
);
14943 OO
.mixinClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.ToggleWidget
);
14944 OO
.mixinClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.TabIndexedElement
);
14949 * Handle mouse click events.
14952 * @param {jQuery.Event} e Mouse click event
14954 OO
.ui
.ToggleSwitchWidget
.prototype.onClick = function ( e
) {
14955 if ( !this.isDisabled() && e
.which
=== 1 ) {
14956 this.setValue( !this.value
);
14962 * Handle key press events.
14965 * @param {jQuery.Event} e Key press event
14967 OO
.ui
.ToggleSwitchWidget
.prototype.onKeyPress = function ( e
) {
14968 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
14969 this.setValue( !this.value
);