3 * https://www.mediawiki.org/wiki/OOjs_UI
5 * Copyright 2011–2015 OOjs UI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
9 * Date: 2015-09-08T20:55:55Z
16 * Namespace for all classes, static methods and static properties.
53 * Generate a unique ID for element
55 * @return {String} [id]
57 OO
.ui
.generateElementId = function () {
59 return 'oojsui-' + OO
.ui
.elementId
;
63 * Check if an element is focusable.
64 * Inspired from :focusable in jQueryUI v1.11.4 - 2015-04-14
66 * @param {jQuery} element Element to test
69 OO
.ui
.isFocusableElement = function ( $element
) {
70 var node
= $element
[ 0 ],
71 nodeName
= node
.nodeName
.toLowerCase(),
72 // Check if the element have tabindex set
73 isInElementGroup
= /^(input|select|textarea|button|object)$/.test( nodeName
),
74 // Check if the element is a link with href or if it has tabindex
76 ( nodeName
=== 'a' && node
.href
) ||
77 !isNaN( $element
.attr( 'tabindex' ) )
79 // Check if the element is visible
81 // This is quicker than calling $element.is( ':visible' )
82 $.expr
.filters
.visible( node
) &&
83 // Check that all parents are visible
84 !$element
.parents().addBack().filter( function () {
85 return $.css( this, 'visibility' ) === 'hidden';
88 isTabOk
= isNaN( $element
.attr( 'tabindex' ) ) || +$element
.attr( 'tabindex' ) >= 0;
91 ( isInElementGroup
? !node
.disabled
: isOtherElement
) &&
97 * Get the user's language and any fallback languages.
99 * These language codes are used to localize user interface elements in the user's language.
101 * In environments that provide a localization system, this function should be overridden to
102 * return the user's language(s). The default implementation returns English (en) only.
104 * @return {string[]} Language codes, in descending order of priority
106 OO
.ui
.getUserLanguages = function () {
111 * Get a value in an object keyed by language code.
113 * @param {Object.<string,Mixed>} obj Object keyed by language code
114 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
115 * @param {string} [fallback] Fallback code, used if no matching language can be found
116 * @return {Mixed} Local value
118 OO
.ui
.getLocalValue = function ( obj
, lang
, fallback
) {
121 // Requested language
125 // Known user language
126 langs
= OO
.ui
.getUserLanguages();
127 for ( i
= 0, len
= langs
.length
; i
< len
; i
++ ) {
134 if ( obj
[ fallback
] ) {
135 return obj
[ fallback
];
137 // First existing language
138 for ( lang
in obj
) {
146 * Check if a node is contained within another node
148 * Similar to jQuery#contains except a list of containers can be supplied
149 * and a boolean argument allows you to include the container in the match list
151 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
152 * @param {HTMLElement} contained Node to find
153 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
154 * @return {boolean} The node is in the list of target nodes
156 OO
.ui
.contains = function ( containers
, contained
, matchContainers
) {
158 if ( !Array
.isArray( containers
) ) {
159 containers
= [ containers
];
161 for ( i
= containers
.length
- 1; i
>= 0; i
-- ) {
162 if ( ( matchContainers
&& contained
=== containers
[ i
] ) || $.contains( containers
[ i
], contained
) ) {
170 * Return a function, that, as long as it continues to be invoked, will not
171 * be triggered. The function will be called after it stops being called for
172 * N milliseconds. If `immediate` is passed, trigger the function on the
173 * leading edge, instead of the trailing.
175 * Ported from: http://underscorejs.org/underscore.js
177 * @param {Function} func
178 * @param {number} wait
179 * @param {boolean} immediate
182 OO
.ui
.debounce = function ( func
, wait
, immediate
) {
187 later = function () {
190 func
.apply( context
, args
);
193 if ( immediate
&& !timeout
) {
194 func
.apply( context
, args
);
196 clearTimeout( timeout
);
197 timeout
= setTimeout( later
, wait
);
202 * Proxy for `node.addEventListener( eventName, handler, true )`, if the browser supports it.
203 * Otherwise falls back to non-capturing event listeners.
205 * @param {HTMLElement} node
206 * @param {string} eventName
207 * @param {Function} handler
209 OO
.ui
.addCaptureEventListener = function ( node
, eventName
, handler
) {
210 if ( node
.addEventListener
) {
211 node
.addEventListener( eventName
, handler
, true );
213 node
.attachEvent( 'on' + eventName
, handler
);
218 * Proxy for `node.removeEventListener( eventName, handler, true )`, if the browser supports it.
219 * Otherwise falls back to non-capturing event listeners.
221 * @param {HTMLElement} node
222 * @param {string} eventName
223 * @param {Function} handler
225 OO
.ui
.removeCaptureEventListener = function ( node
, eventName
, handler
) {
226 if ( node
.addEventListener
) {
227 node
.removeEventListener( eventName
, handler
, true );
229 node
.detachEvent( 'on' + eventName
, handler
);
234 * Reconstitute a JavaScript object corresponding to a widget created by
235 * the PHP implementation.
237 * This is an alias for `OO.ui.Element.static.infuse()`.
239 * @param {string|HTMLElement|jQuery} idOrNode
240 * A DOM id (if a string) or node for the widget to infuse.
241 * @return {OO.ui.Element}
242 * The `OO.ui.Element` corresponding to this (infusable) document node.
244 OO
.ui
.infuse = function ( idOrNode
) {
245 return OO
.ui
.Element
.static.infuse( idOrNode
);
250 * Message store for the default implementation of OO.ui.msg
252 * Environments that provide a localization system should not use this, but should override
253 * OO.ui.msg altogether.
258 // Tool tip for a button that moves items in a list down one place
259 'ooui-outline-control-move-down': 'Move item down',
260 // Tool tip for a button that moves items in a list up one place
261 'ooui-outline-control-move-up': 'Move item up',
262 // Tool tip for a button that removes items from a list
263 'ooui-outline-control-remove': 'Remove item',
264 // Label for the toolbar group that contains a list of all other available tools
265 'ooui-toolbar-more': 'More',
266 // Label for the fake tool that expands the full list of tools in a toolbar group
267 'ooui-toolgroup-expand': 'More',
268 // Label for the fake tool that collapses the full list of tools in a toolbar group
269 'ooui-toolgroup-collapse': 'Fewer',
270 // Default label for the accept button of a confirmation dialog
271 'ooui-dialog-message-accept': 'OK',
272 // Default label for the reject button of a confirmation dialog
273 'ooui-dialog-message-reject': 'Cancel',
274 // Title for process dialog error description
275 'ooui-dialog-process-error': 'Something went wrong',
276 // Label for process dialog dismiss error button, visible when describing errors
277 'ooui-dialog-process-dismiss': 'Dismiss',
278 // Label for process dialog retry action button, visible when describing only recoverable errors
279 'ooui-dialog-process-retry': 'Try again',
280 // Label for process dialog retry action button, visible when describing only warnings
281 'ooui-dialog-process-continue': 'Continue',
282 // Label for the file selection widget's select file button
283 'ooui-selectfile-button-select': 'Select a file',
284 // Label for the file selection widget if file selection is not supported
285 'ooui-selectfile-not-supported': 'File selection is not supported',
286 // Label for the file selection widget when no file is currently selected
287 'ooui-selectfile-placeholder': 'No file is selected',
288 // Label for the file selection widget's drop target
289 'ooui-selectfile-dragdrop-placeholder': 'Drop file here',
290 // Semicolon separator
291 'ooui-semicolon-separator': '; '
295 * Get a localized message.
297 * In environments that provide a localization system, this function should be overridden to
298 * return the message translated in the user's language. The default implementation always returns
301 * After the message key, message parameters may optionally be passed. In the default implementation,
302 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
303 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
304 * they support unnamed, ordered message parameters.
307 * @param {string} key Message key
308 * @param {Mixed...} [params] Message parameters
309 * @return {string} Translated message with parameters substituted
311 OO
.ui
.msg = function ( key
) {
312 var message
= messages
[ key
],
313 params
= Array
.prototype.slice
.call( arguments
, 1 );
314 if ( typeof message
=== 'string' ) {
315 // Perform $1 substitution
316 message
= message
.replace( /\$(\d+)/g, function ( unused
, n
) {
317 var i
= parseInt( n
, 10 );
318 return params
[ i
- 1 ] !== undefined ? params
[ i
- 1 ] : '$' + n
;
321 // Return placeholder if message not found
322 message
= '[' + key
+ ']';
328 * Package a message and arguments for deferred resolution.
330 * Use this when you are statically specifying a message and the message may not yet be present.
332 * @param {string} key Message key
333 * @param {Mixed...} [params] Message parameters
334 * @return {Function} Function that returns the resolved message when executed
336 OO
.ui
.deferMsg = function () {
337 var args
= arguments
;
339 return OO
.ui
.msg
.apply( OO
.ui
, args
);
346 * If the message is a function it will be executed, otherwise it will pass through directly.
348 * @param {Function|string} msg Deferred message, or message text
349 * @return {string} Resolved message
351 OO
.ui
.resolveMsg = function ( msg
) {
352 if ( $.isFunction( msg
) ) {
359 * @param {string} url
362 OO
.ui
.isSafeUrl = function ( url
) {
364 // Keep in sync with php/Tag.php
366 'bitcoin:', 'ftp:', 'ftps:', 'geo:', 'git:', 'gopher:', 'http:', 'https:', 'irc:', 'ircs:',
367 'magnet:', 'mailto:', 'mms:', 'news:', 'nntp:', 'redis:', 'sftp:', 'sip:', 'sips:', 'sms:', 'ssh:',
368 'svn:', 'tel:', 'telnet:', 'urn:', 'worldwind:', 'xmpp:'
371 if ( url
.indexOf( ':' ) === -1 ) {
376 protocol
= url
.split( ':', 1 )[ 0 ] + ':';
377 if ( !protocol
.match( /^([A-za-z0-9\+\.\-])+:/ ) ) {
378 // Not a valid protocol, safe
382 // Safe if in the whitelist
383 return whitelist
.indexOf( protocol
) !== -1;
393 * Namespace for OOjs UI mixins.
395 * Mixins are named according to the type of object they are intended to
396 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
397 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
398 * is intended to be mixed in to an instance of OO.ui.Widget.
406 * PendingElement is a mixin that is used to create elements that notify users that something is happening
407 * and that they should wait before proceeding. The pending state is visually represented with a pending
408 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
409 * field of a {@link OO.ui.TextInputWidget text input widget}.
411 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
412 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
413 * in process dialogs.
416 * function MessageDialog( config ) {
417 * MessageDialog.parent.call( this, config );
419 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
421 * MessageDialog.static.actions = [
422 * { action: 'save', label: 'Done', flags: 'primary' },
423 * { label: 'Cancel', flags: 'safe' }
426 * MessageDialog.prototype.initialize = function () {
427 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
428 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
429 * this.content.$element.append( '<p>Click the \'Done\' action widget to see its pending state. Note that action widgets can be marked pending in message dialogs but not process dialogs.</p>' );
430 * this.$body.append( this.content.$element );
432 * MessageDialog.prototype.getBodyHeight = function () {
435 * MessageDialog.prototype.getActionProcess = function ( action ) {
437 * if ( action === 'save' ) {
438 * dialog.getActions().get({actions: 'save'})[0].pushPending();
439 * return new OO.ui.Process()
441 * .next( function () {
442 * dialog.getActions().get({actions: 'save'})[0].popPending();
445 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
448 * var windowManager = new OO.ui.WindowManager();
449 * $( 'body' ).append( windowManager.$element );
451 * var dialog = new MessageDialog();
452 * windowManager.addWindows( [ dialog ] );
453 * windowManager.openWindow( dialog );
459 * @param {Object} [config] Configuration options
460 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
462 OO
.ui
.mixin
.PendingElement
= function OoUiMixinPendingElement( config
) {
463 // Configuration initialization
464 config
= config
|| {};
468 this.$pending
= null;
471 this.setPendingElement( config
.$pending
|| this.$element
);
476 OO
.initClass( OO
.ui
.mixin
.PendingElement
);
481 * Set the pending element (and clean up any existing one).
483 * @param {jQuery} $pending The element to set to pending.
485 OO
.ui
.mixin
.PendingElement
.prototype.setPendingElement = function ( $pending
) {
486 if ( this.$pending
) {
487 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
490 this.$pending
= $pending
;
491 if ( this.pending
> 0 ) {
492 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
497 * Check if an element is pending.
499 * @return {boolean} Element is pending
501 OO
.ui
.mixin
.PendingElement
.prototype.isPending = function () {
502 return !!this.pending
;
506 * Increase the pending counter. The pending state will remain active until the counter is zero
507 * (i.e., the number of calls to #pushPending and #popPending is the same).
511 OO
.ui
.mixin
.PendingElement
.prototype.pushPending = function () {
512 if ( this.pending
=== 0 ) {
513 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
514 this.updateThemeClasses();
522 * Decrease the pending counter. The pending state will remain active until the counter is zero
523 * (i.e., the number of calls to #pushPending and #popPending is the same).
527 OO
.ui
.mixin
.PendingElement
.prototype.popPending = function () {
528 if ( this.pending
=== 1 ) {
529 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
530 this.updateThemeClasses();
532 this.pending
= Math
.max( 0, this.pending
- 1 );
538 * ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them.
539 * Actions can be made available for specific contexts (modes) and circumstances
540 * (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
542 * ActionSets contain two types of actions:
544 * - 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.
545 * - Other: Other actions include all non-special visible actions.
547 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
550 * // Example: An action set used in a process dialog
551 * function MyProcessDialog( config ) {
552 * MyProcessDialog.parent.call( this, config );
554 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
555 * MyProcessDialog.static.title = 'An action set in a process dialog';
556 * // An action set that uses modes ('edit' and 'help' mode, in this example).
557 * MyProcessDialog.static.actions = [
558 * { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] },
559 * { action: 'help', modes: 'edit', label: 'Help' },
560 * { modes: 'edit', label: 'Cancel', flags: 'safe' },
561 * { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
564 * MyProcessDialog.prototype.initialize = function () {
565 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
566 * this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
567 * 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>' );
568 * this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
569 * 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>' );
570 * this.stackLayout = new OO.ui.StackLayout( {
571 * items: [ this.panel1, this.panel2 ]
573 * this.$body.append( this.stackLayout.$element );
575 * MyProcessDialog.prototype.getSetupProcess = function ( data ) {
576 * return MyProcessDialog.parent.prototype.getSetupProcess.call( this, data )
577 * .next( function () {
578 * this.actions.setMode( 'edit' );
581 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
582 * if ( action === 'help' ) {
583 * this.actions.setMode( 'help' );
584 * this.stackLayout.setItem( this.panel2 );
585 * } else if ( action === 'back' ) {
586 * this.actions.setMode( 'edit' );
587 * this.stackLayout.setItem( this.panel1 );
588 * } else if ( action === 'continue' ) {
590 * return new OO.ui.Process( function () {
594 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
596 * MyProcessDialog.prototype.getBodyHeight = function () {
597 * return this.panel1.$element.outerHeight( true );
599 * var windowManager = new OO.ui.WindowManager();
600 * $( 'body' ).append( windowManager.$element );
601 * var dialog = new MyProcessDialog( {
604 * windowManager.addWindows( [ dialog ] );
605 * windowManager.openWindow( dialog );
607 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
611 * @mixins OO.EventEmitter
614 * @param {Object} [config] Configuration options
616 OO
.ui
.ActionSet
= function OoUiActionSet( config
) {
617 // Configuration initialization
618 config
= config
|| {};
620 // Mixin constructors
621 OO
.EventEmitter
.call( this );
626 actions
: 'getAction',
630 this.categorized
= {};
633 this.organized
= false;
634 this.changing
= false;
635 this.changed
= false;
640 OO
.mixinClass( OO
.ui
.ActionSet
, OO
.EventEmitter
);
642 /* Static Properties */
645 * Symbolic name of the flags used to identify special actions. Special actions are displayed in the
646 * header of a {@link OO.ui.ProcessDialog process dialog}.
647 * See the [OOjs UI documentation on MediaWiki][2] for more information and examples.
649 * [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
656 OO
.ui
.ActionSet
.static.specialFlags
= [ 'safe', 'primary' ];
663 * A 'click' event is emitted when an action is clicked.
665 * @param {OO.ui.ActionWidget} action Action that was clicked
671 * A 'resize' event is emitted when an action widget is resized.
673 * @param {OO.ui.ActionWidget} action Action that was resized
679 * An 'add' event is emitted when actions are {@link #method-add added} to the action set.
681 * @param {OO.ui.ActionWidget[]} added Actions added
687 * A 'remove' event is emitted when actions are {@link #method-remove removed}
688 * or {@link #clear cleared}.
690 * @param {OO.ui.ActionWidget[]} added Actions removed
696 * A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
697 * or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed.
704 * Handle action change events.
709 OO
.ui
.ActionSet
.prototype.onActionChange = function () {
710 this.organized
= false;
711 if ( this.changing
) {
714 this.emit( 'change' );
719 * Check if an action is one of the special actions.
721 * @param {OO.ui.ActionWidget} action Action to check
722 * @return {boolean} Action is special
724 OO
.ui
.ActionSet
.prototype.isSpecial = function ( action
) {
727 for ( flag
in this.special
) {
728 if ( action
=== this.special
[ flag
] ) {
737 * Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
740 * @param {Object} [filters] Filters to use, omit to get all actions
741 * @param {string|string[]} [filters.actions] Actions that action widgets must have
742 * @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
743 * @param {string|string[]} [filters.modes] Modes that action widgets must have
744 * @param {boolean} [filters.visible] Action widgets must be visible
745 * @param {boolean} [filters.disabled] Action widgets must be disabled
746 * @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
748 OO
.ui
.ActionSet
.prototype.get = function ( filters
) {
749 var i
, len
, list
, category
, actions
, index
, match
, matches
;
754 // Collect category candidates
756 for ( category
in this.categorized
) {
757 list
= filters
[ category
];
759 if ( !Array
.isArray( list
) ) {
762 for ( i
= 0, len
= list
.length
; i
< len
; i
++ ) {
763 actions
= this.categorized
[ category
][ list
[ i
] ];
764 if ( Array
.isArray( actions
) ) {
765 matches
.push
.apply( matches
, actions
);
770 // Remove by boolean filters
771 for ( i
= 0, len
= matches
.length
; i
< len
; i
++ ) {
772 match
= matches
[ i
];
774 ( filters
.visible
!== undefined && match
.isVisible() !== filters
.visible
) ||
775 ( filters
.disabled
!== undefined && match
.isDisabled() !== filters
.disabled
)
777 matches
.splice( i
, 1 );
783 for ( i
= 0, len
= matches
.length
; i
< len
; i
++ ) {
784 match
= matches
[ i
];
785 index
= matches
.lastIndexOf( match
);
786 while ( index
!== i
) {
787 matches
.splice( index
, 1 );
789 index
= matches
.lastIndexOf( match
);
794 return this.list
.slice();
798 * Get 'special' actions.
800 * Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'.
801 * Special flags can be configured in subclasses by changing the static #specialFlags property.
803 * @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
805 OO
.ui
.ActionSet
.prototype.getSpecial = function () {
807 return $.extend( {}, this.special
);
811 * Get 'other' actions.
813 * Other actions include all non-special visible action widgets.
815 * @return {OO.ui.ActionWidget[]} 'Other' action widgets
817 OO
.ui
.ActionSet
.prototype.getOthers = function () {
819 return this.others
.slice();
823 * Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
824 * to be available in the specified mode will be made visible. All other actions will be hidden.
826 * @param {string} mode The mode. Only actions configured to be available in the specified
827 * mode will be made visible.
832 OO
.ui
.ActionSet
.prototype.setMode = function ( mode
) {
835 this.changing
= true;
836 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
837 action
= this.list
[ i
];
838 action
.toggle( action
.hasMode( mode
) );
841 this.organized
= false;
842 this.changing
= false;
843 this.emit( 'change' );
849 * Set the abilities of the specified actions.
851 * Action widgets that are configured with the specified actions will be enabled
852 * or disabled based on the boolean values specified in the `actions`
855 * @param {Object.<string,boolean>} actions A list keyed by action name with boolean
856 * values that indicate whether or not the action should be enabled.
859 OO
.ui
.ActionSet
.prototype.setAbilities = function ( actions
) {
860 var i
, len
, action
, item
;
862 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
863 item
= this.list
[ i
];
864 action
= item
.getAction();
865 if ( actions
[ action
] !== undefined ) {
866 item
.setDisabled( !actions
[ action
] );
874 * Executes a function once per action.
876 * When making changes to multiple actions, use this method instead of iterating over the actions
877 * manually to defer emitting a #change event until after all actions have been changed.
879 * @param {Object|null} actions Filters to use to determine which actions to iterate over; see #get
880 * @param {Function} callback Callback to run for each action; callback is invoked with three
881 * arguments: the action, the action's index, the list of actions being iterated over
884 OO
.ui
.ActionSet
.prototype.forEach = function ( filter
, callback
) {
885 this.changed
= false;
886 this.changing
= true;
887 this.get( filter
).forEach( callback
);
888 this.changing
= false;
889 if ( this.changed
) {
890 this.emit( 'change' );
897 * Add action widgets to the action set.
899 * @param {OO.ui.ActionWidget[]} actions Action widgets to add
904 OO
.ui
.ActionSet
.prototype.add = function ( actions
) {
907 this.changing
= true;
908 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
909 action
= actions
[ i
];
910 action
.connect( this, {
911 click
: [ 'emit', 'click', action
],
912 resize
: [ 'emit', 'resize', action
],
913 toggle
: [ 'onActionChange' ]
915 this.list
.push( action
);
917 this.organized
= false;
918 this.emit( 'add', actions
);
919 this.changing
= false;
920 this.emit( 'change' );
926 * Remove action widgets from the set.
928 * To remove all actions, you may wish to use the #clear method instead.
930 * @param {OO.ui.ActionWidget[]} actions Action widgets to remove
935 OO
.ui
.ActionSet
.prototype.remove = function ( actions
) {
936 var i
, len
, index
, action
;
938 this.changing
= true;
939 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
940 action
= actions
[ i
];
941 index
= this.list
.indexOf( action
);
942 if ( index
!== -1 ) {
943 action
.disconnect( this );
944 this.list
.splice( index
, 1 );
947 this.organized
= false;
948 this.emit( 'remove', actions
);
949 this.changing
= false;
950 this.emit( 'change' );
956 * Remove all action widets from the set.
958 * To remove only specified actions, use the {@link #method-remove remove} method instead.
964 OO
.ui
.ActionSet
.prototype.clear = function () {
966 removed
= this.list
.slice();
968 this.changing
= true;
969 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
970 action
= this.list
[ i
];
971 action
.disconnect( this );
976 this.organized
= false;
977 this.emit( 'remove', removed
);
978 this.changing
= false;
979 this.emit( 'change' );
987 * This is called whenever organized information is requested. It will only reorganize the actions
988 * if something has changed since the last time it ran.
993 OO
.ui
.ActionSet
.prototype.organize = function () {
994 var i
, iLen
, j
, jLen
, flag
, action
, category
, list
, item
, special
,
995 specialFlags
= this.constructor.static.specialFlags
;
997 if ( !this.organized
) {
998 this.categorized
= {};
1001 for ( i
= 0, iLen
= this.list
.length
; i
< iLen
; i
++ ) {
1002 action
= this.list
[ i
];
1003 if ( action
.isVisible() ) {
1004 // Populate categories
1005 for ( category
in this.categories
) {
1006 if ( !this.categorized
[ category
] ) {
1007 this.categorized
[ category
] = {};
1009 list
= action
[ this.categories
[ category
] ]();
1010 if ( !Array
.isArray( list
) ) {
1013 for ( j
= 0, jLen
= list
.length
; j
< jLen
; j
++ ) {
1015 if ( !this.categorized
[ category
][ item
] ) {
1016 this.categorized
[ category
][ item
] = [];
1018 this.categorized
[ category
][ item
].push( action
);
1021 // Populate special/others
1023 for ( j
= 0, jLen
= specialFlags
.length
; j
< jLen
; j
++ ) {
1024 flag
= specialFlags
[ j
];
1025 if ( !this.special
[ flag
] && action
.hasFlag( flag
) ) {
1026 this.special
[ flag
] = action
;
1032 this.others
.push( action
);
1036 this.organized
= true;
1043 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
1044 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
1045 * connected to them and can't be interacted with.
1051 * @param {Object} [config] Configuration options
1052 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
1053 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
1055 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
1056 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
1057 * @cfg {string} [text] Text to insert
1058 * @cfg {Array} [content] An array of content elements to append (after #text).
1059 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
1060 * Instances of OO.ui.Element will have their $element appended.
1061 * @cfg {jQuery} [$content] Content elements to append (after #text)
1062 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
1063 * Data can also be specified with the #setData method.
1065 OO
.ui
.Element
= function OoUiElement( config
) {
1066 // Configuration initialization
1067 config
= config
|| {};
1071 this.visible
= true;
1072 this.data
= config
.data
;
1073 this.$element
= config
.$element
||
1074 $( document
.createElement( this.getTagName() ) );
1075 this.elementGroup
= null;
1076 this.debouncedUpdateThemeClassesHandler
= OO
.ui
.debounce( this.debouncedUpdateThemeClasses
);
1079 if ( Array
.isArray( config
.classes
) ) {
1080 this.$element
.addClass( config
.classes
.join( ' ' ) );
1083 this.$element
.attr( 'id', config
.id
);
1085 if ( config
.text
) {
1086 this.$element
.text( config
.text
);
1088 if ( config
.content
) {
1089 // The `content` property treats plain strings as text; use an
1090 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
1091 // appropriate $element appended.
1092 this.$element
.append( config
.content
.map( function ( v
) {
1093 if ( typeof v
=== 'string' ) {
1094 // Escape string so it is properly represented in HTML.
1095 return document
.createTextNode( v
);
1096 } else if ( v
instanceof OO
.ui
.HtmlSnippet
) {
1098 return v
.toString();
1099 } else if ( v
instanceof OO
.ui
.Element
) {
1105 if ( config
.$content
) {
1106 // The `$content` property treats plain strings as HTML.
1107 this.$element
.append( config
.$content
);
1113 OO
.initClass( OO
.ui
.Element
);
1115 /* Static Properties */
1118 * The name of the HTML tag used by the element.
1120 * The static value may be ignored if the #getTagName method is overridden.
1124 * @property {string}
1126 OO
.ui
.Element
.static.tagName
= 'div';
1128 /* Static Methods */
1131 * Reconstitute a JavaScript object corresponding to a widget created
1132 * by the PHP implementation.
1134 * @param {string|HTMLElement|jQuery} idOrNode
1135 * A DOM id (if a string) or node for the widget to infuse.
1136 * @return {OO.ui.Element}
1137 * The `OO.ui.Element` corresponding to this (infusable) document node.
1138 * For `Tag` objects emitted on the HTML side (used occasionally for content)
1139 * the value returned is a newly-created Element wrapping around the existing
1142 OO
.ui
.Element
.static.infuse = function ( idOrNode
) {
1143 var obj
= OO
.ui
.Element
.static.unsafeInfuse( idOrNode
, false );
1144 // Verify that the type matches up.
1145 // FIXME: uncomment after T89721 is fixed (see T90929)
1147 if ( !( obj instanceof this['class'] ) ) {
1148 throw new Error( 'Infusion type mismatch!' );
1155 * Implementation helper for `infuse`; skips the type check and has an
1156 * extra property so that only the top-level invocation touches the DOM.
1158 * @param {string|HTMLElement|jQuery} idOrNode
1159 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
1160 * when the top-level widget of this infusion is inserted into DOM,
1161 * replacing the original node; or false for top-level invocation.
1162 * @return {OO.ui.Element}
1164 OO
.ui
.Element
.static.unsafeInfuse = function ( idOrNode
, domPromise
) {
1165 // look for a cached result of a previous infusion.
1166 var id
, $elem
, data
, cls
, parts
, parent
, obj
, top
, state
;
1167 if ( typeof idOrNode
=== 'string' ) {
1169 $elem
= $( document
.getElementById( id
) );
1171 $elem
= $( idOrNode
);
1172 id
= $elem
.attr( 'id' );
1174 if ( !$elem
.length
) {
1175 throw new Error( 'Widget not found: ' + id
);
1177 data
= $elem
.data( 'ooui-infused' ) || $elem
[ 0 ].oouiInfused
;
1180 if ( data
=== true ) {
1181 throw new Error( 'Circular dependency! ' + id
);
1185 data
= $elem
.attr( 'data-ooui' );
1187 throw new Error( 'No infusion data found: ' + id
);
1190 data
= $.parseJSON( data
);
1194 if ( !( data
&& data
._
) ) {
1195 throw new Error( 'No valid infusion data found: ' + id
);
1197 if ( data
._
=== 'Tag' ) {
1198 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
1199 return new OO
.ui
.Element( { $element
: $elem
} );
1201 parts
= data
._
.split( '.' );
1202 cls
= OO
.getProp
.apply( OO
, [ window
].concat( parts
) );
1203 if ( cls
=== undefined ) {
1204 // The PHP output might be old and not including the "OO.ui" prefix
1205 // TODO: Remove this back-compat after next major release
1206 cls
= OO
.getProp
.apply( OO
, [ OO
.ui
].concat( parts
) );
1207 if ( cls
=== undefined ) {
1208 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
1212 // Verify that we're creating an OO.ui.Element instance
1213 parent
= cls
.parent
;
1215 while ( parent
!== undefined ) {
1216 if ( parent
=== OO
.ui
.Element
) {
1221 parent
= parent
.parent
;
1224 if ( parent
!== OO
.ui
.Element
) {
1225 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
1228 if ( domPromise
=== false ) {
1230 domPromise
= top
.promise();
1232 $elem
.data( 'ooui-infused', true ); // prevent loops
1233 data
.id
= id
; // implicit
1234 data
= OO
.copy( data
, null, function deserialize( value
) {
1235 if ( OO
.isPlainObject( value
) ) {
1237 return OO
.ui
.Element
.static.unsafeInfuse( value
.tag
, domPromise
);
1240 return new OO
.ui
.HtmlSnippet( value
.html
);
1244 // jscs:disable requireCapitalizedConstructors
1245 obj
= new cls( data
); // rebuild widget
1246 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
1247 state
= obj
.gatherPreInfuseState( $elem
);
1248 // now replace old DOM with this new DOM.
1250 $elem
.replaceWith( obj
.$element
);
1251 // This element is now gone from the DOM, but if anyone is holding a reference to it,
1252 // let's allow them to OO.ui.infuse() it and do what they expect (T105828).
1253 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
1254 $elem
[ 0 ].oouiInfused
= obj
;
1257 obj
.$element
.data( 'ooui-infused', obj
);
1258 // set the 'data-ooui' attribute so we can identify infused widgets
1259 obj
.$element
.attr( 'data-ooui', '' );
1260 // restore dynamic state after the new element is inserted into DOM
1261 domPromise
.done( obj
.restorePreInfuseState
.bind( obj
, state
) );
1266 * Get a jQuery function within a specific document.
1269 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
1270 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
1272 * @return {Function} Bound jQuery function
1274 OO
.ui
.Element
.static.getJQuery = function ( context
, $iframe
) {
1275 function wrapper( selector
) {
1276 return $( selector
, wrapper
.context
);
1279 wrapper
.context
= this.getDocument( context
);
1282 wrapper
.$iframe
= $iframe
;
1289 * Get the document of an element.
1292 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
1293 * @return {HTMLDocument|null} Document object
1295 OO
.ui
.Element
.static.getDocument = function ( obj
) {
1296 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
1297 return ( obj
[ 0 ] && obj
[ 0 ].ownerDocument
) ||
1298 // Empty jQuery selections might have a context
1301 obj
.ownerDocument
||
1305 ( obj
.nodeType
=== 9 && obj
) ||
1310 * Get the window of an element or document.
1313 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
1314 * @return {Window} Window object
1316 OO
.ui
.Element
.static.getWindow = function ( obj
) {
1317 var doc
= this.getDocument( obj
);
1319 // Standard Document.defaultView is IE9+
1320 return doc
.parentWindow
|| doc
.defaultView
;
1324 * Get the direction of an element or document.
1327 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
1328 * @return {string} Text direction, either 'ltr' or 'rtl'
1330 OO
.ui
.Element
.static.getDir = function ( obj
) {
1333 if ( obj
instanceof jQuery
) {
1336 isDoc
= obj
.nodeType
=== 9;
1337 isWin
= obj
.document
!== undefined;
1338 if ( isDoc
|| isWin
) {
1344 return $( obj
).css( 'direction' );
1348 * Get the offset between two frames.
1350 * TODO: Make this function not use recursion.
1353 * @param {Window} from Window of the child frame
1354 * @param {Window} [to=window] Window of the parent frame
1355 * @param {Object} [offset] Offset to start with, used internally
1356 * @return {Object} Offset object, containing left and top properties
1358 OO
.ui
.Element
.static.getFrameOffset = function ( from, to
, offset
) {
1359 var i
, len
, frames
, frame
, rect
;
1365 offset
= { top
: 0, left
: 0 };
1367 if ( from.parent
=== from ) {
1371 // Get iframe element
1372 frames
= from.parent
.document
.getElementsByTagName( 'iframe' );
1373 for ( i
= 0, len
= frames
.length
; i
< len
; i
++ ) {
1374 if ( frames
[ i
].contentWindow
=== from ) {
1375 frame
= frames
[ i
];
1380 // Recursively accumulate offset values
1382 rect
= frame
.getBoundingClientRect();
1383 offset
.left
+= rect
.left
;
1384 offset
.top
+= rect
.top
;
1385 if ( from !== to
) {
1386 this.getFrameOffset( from.parent
, offset
);
1393 * Get the offset between two elements.
1395 * The two elements may be in a different frame, but in that case the frame $element is in must
1396 * be contained in the frame $anchor is in.
1399 * @param {jQuery} $element Element whose position to get
1400 * @param {jQuery} $anchor Element to get $element's position relative to
1401 * @return {Object} Translated position coordinates, containing top and left properties
1403 OO
.ui
.Element
.static.getRelativePosition = function ( $element
, $anchor
) {
1404 var iframe
, iframePos
,
1405 pos
= $element
.offset(),
1406 anchorPos
= $anchor
.offset(),
1407 elementDocument
= this.getDocument( $element
),
1408 anchorDocument
= this.getDocument( $anchor
);
1410 // If $element isn't in the same document as $anchor, traverse up
1411 while ( elementDocument
!== anchorDocument
) {
1412 iframe
= elementDocument
.defaultView
.frameElement
;
1414 throw new Error( '$element frame is not contained in $anchor frame' );
1416 iframePos
= $( iframe
).offset();
1417 pos
.left
+= iframePos
.left
;
1418 pos
.top
+= iframePos
.top
;
1419 elementDocument
= iframe
.ownerDocument
;
1421 pos
.left
-= anchorPos
.left
;
1422 pos
.top
-= anchorPos
.top
;
1427 * Get element border sizes.
1430 * @param {HTMLElement} el Element to measure
1431 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1433 OO
.ui
.Element
.static.getBorders = function ( el
) {
1434 var doc
= el
.ownerDocument
,
1436 // Standard Document.defaultView is IE9+
1437 win
= doc
.parentWindow
|| doc
.defaultView
,
1438 style
= win
&& win
.getComputedStyle
?
1439 win
.getComputedStyle( el
, null ) :
1441 // Standard getComputedStyle() is IE9+
1444 top
= parseFloat( style
? style
.borderTopWidth
: $el
.css( 'borderTopWidth' ) ) || 0,
1445 left
= parseFloat( style
? style
.borderLeftWidth
: $el
.css( 'borderLeftWidth' ) ) || 0,
1446 bottom
= parseFloat( style
? style
.borderBottomWidth
: $el
.css( 'borderBottomWidth' ) ) || 0,
1447 right
= parseFloat( style
? style
.borderRightWidth
: $el
.css( 'borderRightWidth' ) ) || 0;
1458 * Get dimensions of an element or window.
1461 * @param {HTMLElement|Window} el Element to measure
1462 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1464 OO
.ui
.Element
.static.getDimensions = function ( el
) {
1466 doc
= el
.ownerDocument
|| el
.document
,
1468 // Standard Document.defaultView is IE9+
1469 win
= doc
.parentWindow
|| doc
.defaultView
;
1471 if ( win
=== el
|| el
=== doc
.documentElement
) {
1474 borders
: { top
: 0, left
: 0, bottom
: 0, right
: 0 },
1476 top
: $win
.scrollTop(),
1477 left
: $win
.scrollLeft()
1479 scrollbar
: { right
: 0, bottom
: 0 },
1483 bottom
: $win
.innerHeight(),
1484 right
: $win
.innerWidth()
1490 borders
: this.getBorders( el
),
1492 top
: $el
.scrollTop(),
1493 left
: $el
.scrollLeft()
1496 right
: $el
.innerWidth() - el
.clientWidth
,
1497 bottom
: $el
.innerHeight() - el
.clientHeight
1499 rect
: el
.getBoundingClientRect()
1505 * Get scrollable object parent
1507 * documentElement can't be used to get or set the scrollTop
1508 * property on Blink. Changing and testing its value lets us
1509 * use 'body' or 'documentElement' based on what is working.
1511 * https://code.google.com/p/chromium/issues/detail?id=303131
1514 * @param {HTMLElement} el Element to find scrollable parent for
1515 * @return {HTMLElement} Scrollable parent
1517 OO
.ui
.Element
.static.getRootScrollableElement = function ( el
) {
1518 var scrollTop
, body
;
1520 if ( OO
.ui
.scrollableElement
=== undefined ) {
1521 body
= el
.ownerDocument
.body
;
1522 scrollTop
= body
.scrollTop
;
1525 if ( body
.scrollTop
=== 1 ) {
1526 body
.scrollTop
= scrollTop
;
1527 OO
.ui
.scrollableElement
= 'body';
1529 OO
.ui
.scrollableElement
= 'documentElement';
1533 return el
.ownerDocument
[ OO
.ui
.scrollableElement
];
1537 * Get closest scrollable container.
1539 * Traverses up until either a scrollable element or the root is reached, in which case the window
1543 * @param {HTMLElement} el Element to find scrollable container for
1544 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1545 * @return {HTMLElement} Closest scrollable container
1547 OO
.ui
.Element
.static.getClosestScrollableContainer = function ( el
, dimension
) {
1549 // props = [ 'overflow' ] doesn't work due to https://bugzilla.mozilla.org/show_bug.cgi?id=889091
1550 props
= [ 'overflow-x', 'overflow-y' ],
1551 $parent
= $( el
).parent();
1553 if ( dimension
=== 'x' || dimension
=== 'y' ) {
1554 props
= [ 'overflow-' + dimension
];
1557 while ( $parent
.length
) {
1558 if ( $parent
[ 0 ] === this.getRootScrollableElement( el
) ) {
1559 return $parent
[ 0 ];
1563 val
= $parent
.css( props
[ i
] );
1564 if ( val
=== 'auto' || val
=== 'scroll' ) {
1565 return $parent
[ 0 ];
1568 $parent
= $parent
.parent();
1570 return this.getDocument( el
).body
;
1574 * Scroll element into view.
1577 * @param {HTMLElement} el Element to scroll into view
1578 * @param {Object} [config] Configuration options
1579 * @param {string} [config.duration] jQuery animation duration value
1580 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1581 * to scroll in both directions
1582 * @param {Function} [config.complete] Function to call when scrolling completes
1584 OO
.ui
.Element
.static.scrollIntoView = function ( el
, config
) {
1585 var rel
, anim
, callback
, sc
, $sc
, eld
, scd
, $win
;
1587 // Configuration initialization
1588 config
= config
|| {};
1591 callback
= typeof config
.complete
=== 'function' && config
.complete
;
1592 sc
= this.getClosestScrollableContainer( el
, config
.direction
);
1594 eld
= this.getDimensions( el
);
1595 scd
= this.getDimensions( sc
);
1596 $win
= $( this.getWindow( el
) );
1598 // Compute the distances between the edges of el and the edges of the scroll viewport
1599 if ( $sc
.is( 'html, body' ) ) {
1600 // If the scrollable container is the root, this is easy
1603 bottom
: $win
.innerHeight() - eld
.rect
.bottom
,
1604 left
: eld
.rect
.left
,
1605 right
: $win
.innerWidth() - eld
.rect
.right
1608 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1610 top
: eld
.rect
.top
- ( scd
.rect
.top
+ scd
.borders
.top
),
1611 bottom
: scd
.rect
.bottom
- scd
.borders
.bottom
- scd
.scrollbar
.bottom
- eld
.rect
.bottom
,
1612 left
: eld
.rect
.left
- ( scd
.rect
.left
+ scd
.borders
.left
),
1613 right
: scd
.rect
.right
- scd
.borders
.right
- scd
.scrollbar
.right
- eld
.rect
.right
1617 if ( !config
.direction
|| config
.direction
=== 'y' ) {
1618 if ( rel
.top
< 0 ) {
1619 anim
.scrollTop
= scd
.scroll
.top
+ rel
.top
;
1620 } else if ( rel
.top
> 0 && rel
.bottom
< 0 ) {
1621 anim
.scrollTop
= scd
.scroll
.top
+ Math
.min( rel
.top
, -rel
.bottom
);
1624 if ( !config
.direction
|| config
.direction
=== 'x' ) {
1625 if ( rel
.left
< 0 ) {
1626 anim
.scrollLeft
= scd
.scroll
.left
+ rel
.left
;
1627 } else if ( rel
.left
> 0 && rel
.right
< 0 ) {
1628 anim
.scrollLeft
= scd
.scroll
.left
+ Math
.min( rel
.left
, -rel
.right
);
1631 if ( !$.isEmptyObject( anim
) ) {
1632 $sc
.stop( true ).animate( anim
, config
.duration
|| 'fast' );
1634 $sc
.queue( function ( next
) {
1647 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1648 * and reserve space for them, because it probably doesn't.
1650 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1651 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1652 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1653 * and then reattach (or show) them back.
1656 * @param {HTMLElement} el Element to reconsider the scrollbars on
1658 OO
.ui
.Element
.static.reconsiderScrollbars = function ( el
) {
1659 var i
, len
, scrollLeft
, scrollTop
, nodes
= [];
1660 // Save scroll position
1661 scrollLeft
= el
.scrollLeft
;
1662 scrollTop
= el
.scrollTop
;
1663 // Detach all children
1664 while ( el
.firstChild
) {
1665 nodes
.push( el
.firstChild
);
1666 el
.removeChild( el
.firstChild
);
1669 void el
.offsetHeight
;
1670 // Reattach all children
1671 for ( i
= 0, len
= nodes
.length
; i
< len
; i
++ ) {
1672 el
.appendChild( nodes
[ i
] );
1674 // Restore scroll position (no-op if scrollbars disappeared)
1675 el
.scrollLeft
= scrollLeft
;
1676 el
.scrollTop
= scrollTop
;
1682 * Toggle visibility of an element.
1684 * @param {boolean} [show] Make element visible, omit to toggle visibility
1688 OO
.ui
.Element
.prototype.toggle = function ( show
) {
1689 show
= show
=== undefined ? !this.visible
: !!show
;
1691 if ( show
!== this.isVisible() ) {
1692 this.visible
= show
;
1693 this.$element
.toggleClass( 'oo-ui-element-hidden', !this.visible
);
1694 this.emit( 'toggle', show
);
1701 * Check if element is visible.
1703 * @return {boolean} element is visible
1705 OO
.ui
.Element
.prototype.isVisible = function () {
1706 return this.visible
;
1712 * @return {Mixed} Element data
1714 OO
.ui
.Element
.prototype.getData = function () {
1721 * @param {Mixed} Element data
1724 OO
.ui
.Element
.prototype.setData = function ( data
) {
1730 * Check if element supports one or more methods.
1732 * @param {string|string[]} methods Method or list of methods to check
1733 * @return {boolean} All methods are supported
1735 OO
.ui
.Element
.prototype.supports = function ( methods
) {
1739 methods
= Array
.isArray( methods
) ? methods
: [ methods
];
1740 for ( i
= 0, len
= methods
.length
; i
< len
; i
++ ) {
1741 if ( $.isFunction( this[ methods
[ i
] ] ) ) {
1746 return methods
.length
=== support
;
1750 * Update the theme-provided classes.
1752 * @localdoc This is called in element mixins and widget classes any time state changes.
1753 * Updating is debounced, minimizing overhead of changing multiple attributes and
1754 * guaranteeing that theme updates do not occur within an element's constructor
1756 OO
.ui
.Element
.prototype.updateThemeClasses = function () {
1757 this.debouncedUpdateThemeClassesHandler();
1762 * @localdoc This method is called directly from the QUnit tests instead of #updateThemeClasses, to
1763 * make them synchronous.
1765 OO
.ui
.Element
.prototype.debouncedUpdateThemeClasses = function () {
1766 OO
.ui
.theme
.updateElementClasses( this );
1770 * Get the HTML tag name.
1772 * Override this method to base the result on instance information.
1774 * @return {string} HTML tag name
1776 OO
.ui
.Element
.prototype.getTagName = function () {
1777 return this.constructor.static.tagName
;
1781 * Check if the element is attached to the DOM
1782 * @return {boolean} The element is attached to the DOM
1784 OO
.ui
.Element
.prototype.isElementAttached = function () {
1785 return $.contains( this.getElementDocument(), this.$element
[ 0 ] );
1789 * Get the DOM document.
1791 * @return {HTMLDocument} Document object
1793 OO
.ui
.Element
.prototype.getElementDocument = function () {
1794 // Don't cache this in other ways either because subclasses could can change this.$element
1795 return OO
.ui
.Element
.static.getDocument( this.$element
);
1799 * Get the DOM window.
1801 * @return {Window} Window object
1803 OO
.ui
.Element
.prototype.getElementWindow = function () {
1804 return OO
.ui
.Element
.static.getWindow( this.$element
);
1808 * Get closest scrollable container.
1810 OO
.ui
.Element
.prototype.getClosestScrollableElementContainer = function () {
1811 return OO
.ui
.Element
.static.getClosestScrollableContainer( this.$element
[ 0 ] );
1815 * Get group element is in.
1817 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1819 OO
.ui
.Element
.prototype.getElementGroup = function () {
1820 return this.elementGroup
;
1824 * Set group element is in.
1826 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1829 OO
.ui
.Element
.prototype.setElementGroup = function ( group
) {
1830 this.elementGroup
= group
;
1835 * Scroll element into view.
1837 * @param {Object} [config] Configuration options
1839 OO
.ui
.Element
.prototype.scrollElementIntoView = function ( config
) {
1840 return OO
.ui
.Element
.static.scrollIntoView( this.$element
[ 0 ], config
);
1844 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of a HTML DOM node
1845 * (and its children) that represent an Element of the same type and configuration as the current
1846 * one, generated by the PHP implementation.
1848 * This method is called just before `node` is detached from the DOM. The return value of this
1849 * function will be passed to #restorePreInfuseState after this widget's #$element is inserted into
1850 * DOM to replace `node`.
1853 * @param {HTMLElement} node
1856 OO
.ui
.Element
.prototype.gatherPreInfuseState = function () {
1861 * Restore the pre-infusion dynamic state for this widget.
1863 * This method is called after #$element has been inserted into DOM. The parameter is the return
1864 * value of #gatherPreInfuseState.
1867 * @param {Object} state
1869 OO
.ui
.Element
.prototype.restorePreInfuseState = function () {
1873 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1874 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1875 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1876 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1877 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1881 * @extends OO.ui.Element
1882 * @mixins OO.EventEmitter
1885 * @param {Object} [config] Configuration options
1887 OO
.ui
.Layout
= function OoUiLayout( config
) {
1888 // Configuration initialization
1889 config
= config
|| {};
1891 // Parent constructor
1892 OO
.ui
.Layout
.parent
.call( this, config
);
1894 // Mixin constructors
1895 OO
.EventEmitter
.call( this );
1898 this.$element
.addClass( 'oo-ui-layout' );
1903 OO
.inheritClass( OO
.ui
.Layout
, OO
.ui
.Element
);
1904 OO
.mixinClass( OO
.ui
.Layout
, OO
.EventEmitter
);
1907 * Widgets are compositions of one or more OOjs UI elements that users can both view
1908 * and interact with. All widgets can be configured and modified via a standard API,
1909 * and their state can change dynamically according to a model.
1913 * @extends OO.ui.Element
1914 * @mixins OO.EventEmitter
1917 * @param {Object} [config] Configuration options
1918 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1919 * appearance reflects this state.
1921 OO
.ui
.Widget
= function OoUiWidget( config
) {
1922 // Initialize config
1923 config
= $.extend( { disabled
: false }, config
);
1925 // Parent constructor
1926 OO
.ui
.Widget
.parent
.call( this, config
);
1928 // Mixin constructors
1929 OO
.EventEmitter
.call( this );
1932 this.disabled
= null;
1933 this.wasDisabled
= null;
1936 this.$element
.addClass( 'oo-ui-widget' );
1937 this.setDisabled( !!config
.disabled
);
1942 OO
.inheritClass( OO
.ui
.Widget
, OO
.ui
.Element
);
1943 OO
.mixinClass( OO
.ui
.Widget
, OO
.EventEmitter
);
1945 /* Static Properties */
1948 * Whether this widget will behave reasonably when wrapped in a HTML `<label>`. If this is true,
1949 * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click
1954 * @property {boolean}
1956 OO
.ui
.Widget
.static.supportsSimpleLabel
= false;
1963 * A 'disable' event is emitted when a widget is disabled.
1965 * @param {boolean} disabled Widget is disabled
1971 * A 'toggle' event is emitted when the visibility of the widget changes.
1973 * @param {boolean} visible Widget is visible
1979 * Check if the widget is disabled.
1981 * @return {boolean} Widget is disabled
1983 OO
.ui
.Widget
.prototype.isDisabled = function () {
1984 return this.disabled
;
1988 * Set the 'disabled' state of the widget.
1990 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1992 * @param {boolean} disabled Disable widget
1995 OO
.ui
.Widget
.prototype.setDisabled = function ( disabled
) {
1998 this.disabled
= !!disabled
;
1999 isDisabled
= this.isDisabled();
2000 if ( isDisabled
!== this.wasDisabled
) {
2001 this.$element
.toggleClass( 'oo-ui-widget-disabled', isDisabled
);
2002 this.$element
.toggleClass( 'oo-ui-widget-enabled', !isDisabled
);
2003 this.$element
.attr( 'aria-disabled', isDisabled
.toString() );
2004 this.emit( 'disable', isDisabled
);
2005 this.updateThemeClasses();
2007 this.wasDisabled
= isDisabled
;
2013 * Update the disabled state, in case of changes in parent widget.
2017 OO
.ui
.Widget
.prototype.updateDisabled = function () {
2018 this.setDisabled( this.disabled
);
2023 * A window is a container for elements that are in a child frame. They are used with
2024 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
2025 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
2026 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
2027 * the window manager will choose a sensible fallback.
2029 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
2030 * different processes are executed:
2032 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
2033 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
2036 * - {@link #getSetupProcess} method is called and its result executed
2037 * - {@link #getReadyProcess} method is called and its result executed
2039 * **opened**: The window is now open
2041 * **closing**: The closing stage begins when the window manager's
2042 * {@link OO.ui.WindowManager#closeWindow closeWindow}
2043 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
2045 * - {@link #getHoldProcess} method is called and its result executed
2046 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
2048 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
2049 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
2050 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
2051 * processing can complete. Always assume window processes are executed asynchronously.
2053 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2055 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
2059 * @extends OO.ui.Element
2060 * @mixins OO.EventEmitter
2063 * @param {Object} [config] Configuration options
2064 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
2065 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
2067 OO
.ui
.Window
= function OoUiWindow( config
) {
2068 // Configuration initialization
2069 config
= config
|| {};
2071 // Parent constructor
2072 OO
.ui
.Window
.parent
.call( this, config
);
2074 // Mixin constructors
2075 OO
.EventEmitter
.call( this );
2078 this.manager
= null;
2079 this.size
= config
.size
|| this.constructor.static.size
;
2080 this.$frame
= $( '<div>' );
2081 this.$overlay
= $( '<div>' );
2082 this.$content
= $( '<div>' );
2085 this.$overlay
.addClass( 'oo-ui-window-overlay' );
2087 .addClass( 'oo-ui-window-content' )
2088 .attr( 'tabindex', 0 );
2090 .addClass( 'oo-ui-window-frame' )
2091 .append( this.$content
);
2094 .addClass( 'oo-ui-window' )
2095 .append( this.$frame
, this.$overlay
);
2097 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
2098 // that reference properties not initialized at that time of parent class construction
2099 // TODO: Find a better way to handle post-constructor setup
2100 this.visible
= false;
2101 this.$element
.addClass( 'oo-ui-element-hidden' );
2106 OO
.inheritClass( OO
.ui
.Window
, OO
.ui
.Element
);
2107 OO
.mixinClass( OO
.ui
.Window
, OO
.EventEmitter
);
2109 /* Static Properties */
2112 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
2114 * The static size is used if no #size is configured during construction.
2118 * @property {string}
2120 OO
.ui
.Window
.static.size
= 'medium';
2125 * Handle mouse down events.
2128 * @param {jQuery.Event} e Mouse down event
2130 OO
.ui
.Window
.prototype.onMouseDown = function ( e
) {
2131 // Prevent clicking on the click-block from stealing focus
2132 if ( e
.target
=== this.$element
[ 0 ] ) {
2138 * Check if the window has been initialized.
2140 * Initialization occurs when a window is added to a manager.
2142 * @return {boolean} Window has been initialized
2144 OO
.ui
.Window
.prototype.isInitialized = function () {
2145 return !!this.manager
;
2149 * Check if the window is visible.
2151 * @return {boolean} Window is visible
2153 OO
.ui
.Window
.prototype.isVisible = function () {
2154 return this.visible
;
2158 * Check if the window is opening.
2160 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
2163 * @return {boolean} Window is opening
2165 OO
.ui
.Window
.prototype.isOpening = function () {
2166 return this.manager
.isOpening( this );
2170 * Check if the window is closing.
2172 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
2174 * @return {boolean} Window is closing
2176 OO
.ui
.Window
.prototype.isClosing = function () {
2177 return this.manager
.isClosing( this );
2181 * Check if the window is opened.
2183 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
2185 * @return {boolean} Window is opened
2187 OO
.ui
.Window
.prototype.isOpened = function () {
2188 return this.manager
.isOpened( this );
2192 * Get the window manager.
2194 * All windows must be attached to a window manager, which is used to open
2195 * and close the window and control its presentation.
2197 * @return {OO.ui.WindowManager} Manager of window
2199 OO
.ui
.Window
.prototype.getManager = function () {
2200 return this.manager
;
2204 * Get the symbolic name of the window size (e.g., `small` or `medium`).
2206 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
2208 OO
.ui
.Window
.prototype.getSize = function () {
2209 var viewport
= OO
.ui
.Element
.static.getDimensions( this.getElementWindow() ),
2210 sizes
= this.manager
.constructor.static.sizes
,
2213 if ( !sizes
[ size
] ) {
2214 size
= this.manager
.constructor.static.defaultSize
;
2216 if ( size
!== 'full' && viewport
.rect
.right
- viewport
.rect
.left
< sizes
[ size
].width
) {
2224 * Get the size properties associated with the current window size
2226 * @return {Object} Size properties
2228 OO
.ui
.Window
.prototype.getSizeProperties = function () {
2229 return this.manager
.constructor.static.sizes
[ this.getSize() ];
2233 * Disable transitions on window's frame for the duration of the callback function, then enable them
2237 * @param {Function} callback Function to call while transitions are disabled
2239 OO
.ui
.Window
.prototype.withoutSizeTransitions = function ( callback
) {
2240 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2241 // Disable transitions first, otherwise we'll get values from when the window was animating.
2243 styleObj
= this.$frame
[ 0 ].style
;
2244 oldTransition
= styleObj
.transition
|| styleObj
.OTransition
|| styleObj
.MsTransition
||
2245 styleObj
.MozTransition
|| styleObj
.WebkitTransition
;
2246 styleObj
.transition
= styleObj
.OTransition
= styleObj
.MsTransition
=
2247 styleObj
.MozTransition
= styleObj
.WebkitTransition
= 'none';
2249 // Force reflow to make sure the style changes done inside callback really are not transitioned
2250 this.$frame
.height();
2251 styleObj
.transition
= styleObj
.OTransition
= styleObj
.MsTransition
=
2252 styleObj
.MozTransition
= styleObj
.WebkitTransition
= oldTransition
;
2256 * Get the height of the full window contents (i.e., the window head, body and foot together).
2258 * What consistitutes the head, body, and foot varies depending on the window type.
2259 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
2260 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
2261 * and special actions in the head, and dialog content in the body.
2263 * To get just the height of the dialog body, use the #getBodyHeight method.
2265 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
2267 OO
.ui
.Window
.prototype.getContentHeight = function () {
2270 bodyStyleObj
= this.$body
[ 0 ].style
,
2271 frameStyleObj
= this.$frame
[ 0 ].style
;
2273 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2274 // Disable transitions first, otherwise we'll get values from when the window was animating.
2275 this.withoutSizeTransitions( function () {
2276 var oldHeight
= frameStyleObj
.height
,
2277 oldPosition
= bodyStyleObj
.position
;
2278 frameStyleObj
.height
= '1px';
2279 // Force body to resize to new width
2280 bodyStyleObj
.position
= 'relative';
2281 bodyHeight
= win
.getBodyHeight();
2282 frameStyleObj
.height
= oldHeight
;
2283 bodyStyleObj
.position
= oldPosition
;
2287 // Add buffer for border
2288 ( this.$frame
.outerHeight() - this.$frame
.innerHeight() ) +
2289 // Use combined heights of children
2290 ( this.$head
.outerHeight( true ) + bodyHeight
+ this.$foot
.outerHeight( true ) )
2295 * Get the height of the window body.
2297 * To get the height of the full window contents (the window body, head, and foot together),
2298 * use #getContentHeight.
2300 * When this function is called, the window will temporarily have been resized
2301 * to height=1px, so .scrollHeight measurements can be taken accurately.
2303 * @return {number} Height of the window body in pixels
2305 OO
.ui
.Window
.prototype.getBodyHeight = function () {
2306 return this.$body
[ 0 ].scrollHeight
;
2310 * Get the directionality of the frame (right-to-left or left-to-right).
2312 * @return {string} Directionality: `'ltr'` or `'rtl'`
2314 OO
.ui
.Window
.prototype.getDir = function () {
2315 return OO
.ui
.Element
.static.getDir( this.$content
) || 'ltr';
2319 * Get the 'setup' process.
2321 * The setup process is used to set up a window for use in a particular context,
2322 * based on the `data` argument. This method is called during the opening phase of the window’s
2325 * Override this method to add additional steps to the ‘setup’ process the parent method provides
2326 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2329 * To add window content that persists between openings, you may wish to use the #initialize method
2333 * @param {Object} [data] Window opening data
2334 * @return {OO.ui.Process} Setup process
2336 OO
.ui
.Window
.prototype.getSetupProcess = function () {
2337 return new OO
.ui
.Process();
2341 * Get the ‘ready’ process.
2343 * The ready process is used to ready a window for use in a particular
2344 * context, based on the `data` argument. This method is called during the opening phase of
2345 * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
2347 * Override this method to add additional steps to the ‘ready’ process the parent method
2348 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
2349 * methods of OO.ui.Process.
2352 * @param {Object} [data] Window opening data
2353 * @return {OO.ui.Process} Ready process
2355 OO
.ui
.Window
.prototype.getReadyProcess = function () {
2356 return new OO
.ui
.Process();
2360 * Get the 'hold' process.
2362 * The hold proccess is used to keep a window from being used in a particular context,
2363 * based on the `data` argument. This method is called during the closing phase of the window’s
2366 * Override this method to add additional steps to the 'hold' process the parent method provides
2367 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2371 * @param {Object} [data] Window closing data
2372 * @return {OO.ui.Process} Hold process
2374 OO
.ui
.Window
.prototype.getHoldProcess = function () {
2375 return new OO
.ui
.Process();
2379 * Get the ‘teardown’ process.
2381 * The teardown process is used to teardown a window after use. During teardown,
2382 * user interactions within the window are conveyed and the window is closed, based on the `data`
2383 * argument. This method is called during the closing phase of the window’s lifecycle.
2385 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
2386 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2390 * @param {Object} [data] Window closing data
2391 * @return {OO.ui.Process} Teardown process
2393 OO
.ui
.Window
.prototype.getTeardownProcess = function () {
2394 return new OO
.ui
.Process();
2398 * Set the window manager.
2400 * This will cause the window to initialize. Calling it more than once will cause an error.
2402 * @param {OO.ui.WindowManager} manager Manager for this window
2403 * @throws {Error} An error is thrown if the method is called more than once
2406 OO
.ui
.Window
.prototype.setManager = function ( manager
) {
2407 if ( this.manager
) {
2408 throw new Error( 'Cannot set window manager, window already has a manager' );
2411 this.manager
= manager
;
2418 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2420 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2424 OO
.ui
.Window
.prototype.setSize = function ( size
) {
2431 * Update the window size.
2433 * @throws {Error} An error is thrown if the window is not attached to a window manager
2436 OO
.ui
.Window
.prototype.updateSize = function () {
2437 if ( !this.manager
) {
2438 throw new Error( 'Cannot update window size, must be attached to a manager' );
2441 this.manager
.updateWindowSize( this );
2447 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2448 * when the window is opening. In general, setDimensions should not be called directly.
2450 * To set the size of the window, use the #setSize method.
2452 * @param {Object} dim CSS dimension properties
2453 * @param {string|number} [dim.width] Width
2454 * @param {string|number} [dim.minWidth] Minimum width
2455 * @param {string|number} [dim.maxWidth] Maximum width
2456 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2457 * @param {string|number} [dim.minWidth] Minimum height
2458 * @param {string|number} [dim.maxWidth] Maximum height
2461 OO
.ui
.Window
.prototype.setDimensions = function ( dim
) {
2464 styleObj
= this.$frame
[ 0 ].style
;
2466 // Calculate the height we need to set using the correct width
2467 if ( dim
.height
=== undefined ) {
2468 this.withoutSizeTransitions( function () {
2469 var oldWidth
= styleObj
.width
;
2470 win
.$frame
.css( 'width', dim
.width
|| '' );
2471 height
= win
.getContentHeight();
2472 styleObj
.width
= oldWidth
;
2475 height
= dim
.height
;
2479 width
: dim
.width
|| '',
2480 minWidth
: dim
.minWidth
|| '',
2481 maxWidth
: dim
.maxWidth
|| '',
2482 height
: height
|| '',
2483 minHeight
: dim
.minHeight
|| '',
2484 maxHeight
: dim
.maxHeight
|| ''
2491 * Initialize window contents.
2493 * Before the window is opened for the first time, #initialize is called so that content that
2494 * persists between openings can be added to the window.
2496 * To set up a window with new content each time the window opens, use #getSetupProcess.
2498 * @throws {Error} An error is thrown if the window is not attached to a window manager
2501 OO
.ui
.Window
.prototype.initialize = function () {
2502 if ( !this.manager
) {
2503 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2507 this.$head
= $( '<div>' );
2508 this.$body
= $( '<div>' );
2509 this.$foot
= $( '<div>' );
2510 this.$document
= $( this.getElementDocument() );
2513 this.$element
.on( 'mousedown', this.onMouseDown
.bind( this ) );
2516 this.$head
.addClass( 'oo-ui-window-head' );
2517 this.$body
.addClass( 'oo-ui-window-body' );
2518 this.$foot
.addClass( 'oo-ui-window-foot' );
2519 this.$content
.append( this.$head
, this.$body
, this.$foot
);
2527 * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
2528 * method, which returns a promise resolved when the window is done opening.
2530 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2532 * @param {Object} [data] Window opening data
2533 * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
2534 * if the window fails to open. When the promise is resolved successfully, the first argument of the
2535 * value is a new promise, which is resolved when the window begins closing.
2536 * @throws {Error} An error is thrown if the window is not attached to a window manager
2538 OO
.ui
.Window
.prototype.open = function ( data
) {
2539 if ( !this.manager
) {
2540 throw new Error( 'Cannot open window, must be attached to a manager' );
2543 return this.manager
.openWindow( this, data
);
2549 * This method is a wrapper around a call to the window
2550 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
2551 * which returns a closing promise resolved when the window is done closing.
2553 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2554 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2555 * the window closes.
2557 * @param {Object} [data] Window closing data
2558 * @return {jQuery.Promise} Promise resolved when window is closed
2559 * @throws {Error} An error is thrown if the window is not attached to a window manager
2561 OO
.ui
.Window
.prototype.close = function ( data
) {
2562 if ( !this.manager
) {
2563 throw new Error( 'Cannot close window, must be attached to a manager' );
2566 return this.manager
.closeWindow( this, data
);
2572 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2575 * @param {Object} [data] Window opening data
2576 * @return {jQuery.Promise} Promise resolved when window is setup
2578 OO
.ui
.Window
.prototype.setup = function ( data
) {
2580 deferred
= $.Deferred();
2582 this.toggle( true );
2584 this.getSetupProcess( data
).execute().done( function () {
2585 // Force redraw by asking the browser to measure the elements' widths
2586 win
.$element
.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2587 win
.$content
.addClass( 'oo-ui-window-content-setup' ).width();
2591 return deferred
.promise();
2597 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2600 * @param {Object} [data] Window opening data
2601 * @return {jQuery.Promise} Promise resolved when window is ready
2603 OO
.ui
.Window
.prototype.ready = function ( data
) {
2605 deferred
= $.Deferred();
2607 this.$content
.focus();
2608 this.getReadyProcess( data
).execute().done( function () {
2609 // Force redraw by asking the browser to measure the elements' widths
2610 win
.$element
.addClass( 'oo-ui-window-ready' ).width();
2611 win
.$content
.addClass( 'oo-ui-window-content-ready' ).width();
2615 return deferred
.promise();
2621 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2624 * @param {Object} [data] Window closing data
2625 * @return {jQuery.Promise} Promise resolved when window is held
2627 OO
.ui
.Window
.prototype.hold = function ( data
) {
2629 deferred
= $.Deferred();
2631 this.getHoldProcess( data
).execute().done( function () {
2632 // Get the focused element within the window's content
2633 var $focus
= win
.$content
.find( OO
.ui
.Element
.static.getDocument( win
.$content
).activeElement
);
2635 // Blur the focused element
2636 if ( $focus
.length
) {
2640 // Force redraw by asking the browser to measure the elements' widths
2641 win
.$element
.removeClass( 'oo-ui-window-ready' ).width();
2642 win
.$content
.removeClass( 'oo-ui-window-content-ready' ).width();
2646 return deferred
.promise();
2652 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2655 * @param {Object} [data] Window closing data
2656 * @return {jQuery.Promise} Promise resolved when window is torn down
2658 OO
.ui
.Window
.prototype.teardown = function ( data
) {
2661 return this.getTeardownProcess( data
).execute()
2662 .done( function () {
2663 // Force redraw by asking the browser to measure the elements' widths
2664 win
.$element
.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2665 win
.$content
.removeClass( 'oo-ui-window-content-setup' ).width();
2666 win
.toggle( false );
2671 * The Dialog class serves as the base class for the other types of dialogs.
2672 * Unless extended to include controls, the rendered dialog box is a simple window
2673 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2674 * which opens, closes, and controls the presentation of the window. See the
2675 * [OOjs UI documentation on MediaWiki] [1] for more information.
2678 * // A simple dialog window.
2679 * function MyDialog( config ) {
2680 * MyDialog.parent.call( this, config );
2682 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2683 * MyDialog.prototype.initialize = function () {
2684 * MyDialog.parent.prototype.initialize.call( this );
2685 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2686 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2687 * this.$body.append( this.content.$element );
2689 * MyDialog.prototype.getBodyHeight = function () {
2690 * return this.content.$element.outerHeight( true );
2692 * var myDialog = new MyDialog( {
2695 * // Create and append a window manager, which opens and closes the window.
2696 * var windowManager = new OO.ui.WindowManager();
2697 * $( 'body' ).append( windowManager.$element );
2698 * windowManager.addWindows( [ myDialog ] );
2699 * // Open the window!
2700 * windowManager.openWindow( myDialog );
2702 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2706 * @extends OO.ui.Window
2707 * @mixins OO.ui.mixin.PendingElement
2710 * @param {Object} [config] Configuration options
2712 OO
.ui
.Dialog
= function OoUiDialog( config
) {
2713 // Parent constructor
2714 OO
.ui
.Dialog
.parent
.call( this, config
);
2716 // Mixin constructors
2717 OO
.ui
.mixin
.PendingElement
.call( this );
2720 this.actions
= new OO
.ui
.ActionSet();
2721 this.attachedActions
= [];
2722 this.currentAction
= null;
2723 this.onDialogKeyDownHandler
= this.onDialogKeyDown
.bind( this );
2726 this.actions
.connect( this, {
2727 click
: 'onActionClick',
2728 resize
: 'onActionResize',
2729 change
: 'onActionsChange'
2734 .addClass( 'oo-ui-dialog' )
2735 .attr( 'role', 'dialog' );
2740 OO
.inheritClass( OO
.ui
.Dialog
, OO
.ui
.Window
);
2741 OO
.mixinClass( OO
.ui
.Dialog
, OO
.ui
.mixin
.PendingElement
);
2743 /* Static Properties */
2746 * Symbolic name of dialog.
2748 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2749 * Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
2751 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2756 * @property {string}
2758 OO
.ui
.Dialog
.static.name
= '';
2763 * The title can be specified as a plaintext string, a {@link OO.ui.mixin.LabelElement Label} node, or a function
2764 * that will produce a Label node or string. The title can also be specified with data passed to the
2765 * constructor (see #getSetupProcess). In this case, the static value will be overriden.
2770 * @property {jQuery|string|Function}
2772 OO
.ui
.Dialog
.static.title
= '';
2775 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2777 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2778 * value will be overriden.
2780 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
2784 * @property {Object[]}
2786 OO
.ui
.Dialog
.static.actions
= [];
2789 * Close the dialog when the 'Esc' key is pressed.
2794 * @property {boolean}
2796 OO
.ui
.Dialog
.static.escapable
= true;
2801 * Handle frame document key down events.
2804 * @param {jQuery.Event} e Key down event
2806 OO
.ui
.Dialog
.prototype.onDialogKeyDown = function ( e
) {
2807 if ( e
.which
=== OO
.ui
.Keys
.ESCAPE
) {
2810 e
.stopPropagation();
2815 * Handle action resized events.
2818 * @param {OO.ui.ActionWidget} action Action that was resized
2820 OO
.ui
.Dialog
.prototype.onActionResize = function () {
2821 // Override in subclass
2825 * Handle action click events.
2828 * @param {OO.ui.ActionWidget} action Action that was clicked
2830 OO
.ui
.Dialog
.prototype.onActionClick = function ( action
) {
2831 if ( !this.isPending() ) {
2832 this.executeAction( action
.getAction() );
2837 * Handle actions change event.
2841 OO
.ui
.Dialog
.prototype.onActionsChange = function () {
2842 this.detachActions();
2843 if ( !this.isClosing() ) {
2844 this.attachActions();
2849 * Get the set of actions used by the dialog.
2851 * @return {OO.ui.ActionSet}
2853 OO
.ui
.Dialog
.prototype.getActions = function () {
2854 return this.actions
;
2858 * Get a process for taking action.
2860 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
2861 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
2862 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
2865 * @param {string} [action] Symbolic name of action
2866 * @return {OO.ui.Process} Action process
2868 OO
.ui
.Dialog
.prototype.getActionProcess = function ( action
) {
2869 return new OO
.ui
.Process()
2870 .next( function () {
2872 // An empty action always closes the dialog without data, which should always be
2873 // safe and make no changes
2882 * @param {Object} [data] Dialog opening data
2883 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
2884 * the {@link #static-title static title}
2885 * @param {Object[]} [data.actions] List of configuration options for each
2886 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
2888 OO
.ui
.Dialog
.prototype.getSetupProcess = function ( data
) {
2892 return OO
.ui
.Dialog
.parent
.prototype.getSetupProcess
.call( this, data
)
2893 .next( function () {
2894 var config
= this.constructor.static,
2895 actions
= data
.actions
!== undefined ? data
.actions
: config
.actions
;
2897 this.title
.setLabel(
2898 data
.title
!== undefined ? data
.title
: this.constructor.static.title
2900 this.actions
.add( this.getActionWidgets( actions
) );
2902 if ( this.constructor.static.escapable
) {
2903 this.$element
.on( 'keydown', this.onDialogKeyDownHandler
);
2911 OO
.ui
.Dialog
.prototype.getTeardownProcess = function ( data
) {
2913 return OO
.ui
.Dialog
.parent
.prototype.getTeardownProcess
.call( this, data
)
2914 .first( function () {
2915 if ( this.constructor.static.escapable
) {
2916 this.$element
.off( 'keydown', this.onDialogKeyDownHandler
);
2919 this.actions
.clear();
2920 this.currentAction
= null;
2927 OO
.ui
.Dialog
.prototype.initialize = function () {
2931 OO
.ui
.Dialog
.parent
.prototype.initialize
.call( this );
2933 titleId
= OO
.ui
.generateElementId();
2936 this.title
= new OO
.ui
.LabelWidget( {
2941 this.$content
.addClass( 'oo-ui-dialog-content' );
2942 this.$element
.attr( 'aria-labelledby', titleId
);
2943 this.setPendingElement( this.$head
);
2947 * Get action widgets from a list of configs
2949 * @param {Object[]} actions Action widget configs
2950 * @return {OO.ui.ActionWidget[]} Action widgets
2952 OO
.ui
.Dialog
.prototype.getActionWidgets = function ( actions
) {
2953 var i
, len
, widgets
= [];
2954 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
2956 new OO
.ui
.ActionWidget( actions
[ i
] )
2963 * Attach action actions.
2967 OO
.ui
.Dialog
.prototype.attachActions = function () {
2968 // Remember the list of potentially attached actions
2969 this.attachedActions
= this.actions
.get();
2973 * Detach action actions.
2978 OO
.ui
.Dialog
.prototype.detachActions = function () {
2981 // Detach all actions that may have been previously attached
2982 for ( i
= 0, len
= this.attachedActions
.length
; i
< len
; i
++ ) {
2983 this.attachedActions
[ i
].$element
.detach();
2985 this.attachedActions
= [];
2989 * Execute an action.
2991 * @param {string} action Symbolic name of action to execute
2992 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
2994 OO
.ui
.Dialog
.prototype.executeAction = function ( action
) {
2996 this.currentAction
= action
;
2997 return this.getActionProcess( action
).execute()
2998 .always( this.popPending
.bind( this ) );
3002 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
3003 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
3004 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
3005 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
3006 * pertinent data and reused.
3008 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
3009 * `opened`, and `closing`, which represent the primary stages of the cycle:
3011 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
3012 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
3014 * - an `opening` event is emitted with an `opening` promise
3015 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
3016 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
3017 * window and its result executed
3018 * - a `setup` progress notification is emitted from the `opening` promise
3019 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
3020 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
3021 * window and its result executed
3022 * - a `ready` progress notification is emitted from the `opening` promise
3023 * - the `opening` promise is resolved with an `opened` promise
3025 * **Opened**: the window is now open.
3027 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
3028 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
3029 * to close the window.
3031 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
3032 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
3033 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
3034 * window and its result executed
3035 * - a `hold` progress notification is emitted from the `closing` promise
3036 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
3037 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
3038 * window and its result executed
3039 * - a `teardown` progress notification is emitted from the `closing` promise
3040 * - the `closing` promise is resolved. The window is now closed
3042 * See the [OOjs UI documentation on MediaWiki][1] for more information.
3044 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3047 * @extends OO.ui.Element
3048 * @mixins OO.EventEmitter
3051 * @param {Object} [config] Configuration options
3052 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
3053 * Note that window classes that are instantiated with a factory must have
3054 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
3055 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
3057 OO
.ui
.WindowManager
= function OoUiWindowManager( config
) {
3058 // Configuration initialization
3059 config
= config
|| {};
3061 // Parent constructor
3062 OO
.ui
.WindowManager
.parent
.call( this, config
);
3064 // Mixin constructors
3065 OO
.EventEmitter
.call( this );
3068 this.factory
= config
.factory
;
3069 this.modal
= config
.modal
=== undefined || !!config
.modal
;
3071 this.opening
= null;
3073 this.closing
= null;
3074 this.preparingToOpen
= null;
3075 this.preparingToClose
= null;
3076 this.currentWindow
= null;
3077 this.globalEvents
= false;
3078 this.$ariaHidden
= null;
3079 this.onWindowResizeTimeout
= null;
3080 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
3081 this.afterWindowResizeHandler
= this.afterWindowResize
.bind( this );
3085 .addClass( 'oo-ui-windowManager' )
3086 .toggleClass( 'oo-ui-windowManager-modal', this.modal
);
3091 OO
.inheritClass( OO
.ui
.WindowManager
, OO
.ui
.Element
);
3092 OO
.mixinClass( OO
.ui
.WindowManager
, OO
.EventEmitter
);
3097 * An 'opening' event is emitted when the window begins to be opened.
3100 * @param {OO.ui.Window} win Window that's being opened
3101 * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
3102 * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
3103 * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
3104 * @param {Object} data Window opening data
3108 * A 'closing' event is emitted when the window begins to be closed.
3111 * @param {OO.ui.Window} win Window that's being closed
3112 * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
3113 * is closed successfully. The promise emits `hold` and `teardown` notifications when those
3114 * processes are complete. When the `closing` promise is resolved, the first argument of its value
3115 * is the closing data.
3116 * @param {Object} data Window closing data
3120 * A 'resize' event is emitted when a window is resized.
3123 * @param {OO.ui.Window} win Window that was resized
3126 /* Static Properties */
3129 * Map of the symbolic name of each window size and its CSS properties.
3133 * @property {Object}
3135 OO
.ui
.WindowManager
.static.sizes
= {
3149 // These can be non-numeric because they are never used in calculations
3156 * Symbolic name of the default window size.
3158 * The default size is used if the window's requested size is not recognized.
3162 * @property {string}
3164 OO
.ui
.WindowManager
.static.defaultSize
= 'medium';
3169 * Handle window resize events.
3172 * @param {jQuery.Event} e Window resize event
3174 OO
.ui
.WindowManager
.prototype.onWindowResize = function () {
3175 clearTimeout( this.onWindowResizeTimeout
);
3176 this.onWindowResizeTimeout
= setTimeout( this.afterWindowResizeHandler
, 200 );
3180 * Handle window resize events.
3183 * @param {jQuery.Event} e Window resize event
3185 OO
.ui
.WindowManager
.prototype.afterWindowResize = function () {
3186 if ( this.currentWindow
) {
3187 this.updateWindowSize( this.currentWindow
);
3192 * Check if window is opening.
3194 * @return {boolean} Window is opening
3196 OO
.ui
.WindowManager
.prototype.isOpening = function ( win
) {
3197 return win
=== this.currentWindow
&& !!this.opening
&& this.opening
.state() === 'pending';
3201 * Check if window is closing.
3203 * @return {boolean} Window is closing
3205 OO
.ui
.WindowManager
.prototype.isClosing = function ( win
) {
3206 return win
=== this.currentWindow
&& !!this.closing
&& this.closing
.state() === 'pending';
3210 * Check if window is opened.
3212 * @return {boolean} Window is opened
3214 OO
.ui
.WindowManager
.prototype.isOpened = function ( win
) {
3215 return win
=== this.currentWindow
&& !!this.opened
&& this.opened
.state() === 'pending';
3219 * Check if a window is being managed.
3221 * @param {OO.ui.Window} win Window to check
3222 * @return {boolean} Window is being managed
3224 OO
.ui
.WindowManager
.prototype.hasWindow = function ( win
) {
3227 for ( name
in this.windows
) {
3228 if ( this.windows
[ name
] === win
) {
3237 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
3239 * @param {OO.ui.Window} win Window being opened
3240 * @param {Object} [data] Window opening data
3241 * @return {number} Milliseconds to wait
3243 OO
.ui
.WindowManager
.prototype.getSetupDelay = function () {
3248 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
3250 * @param {OO.ui.Window} win Window being opened
3251 * @param {Object} [data] Window opening data
3252 * @return {number} Milliseconds to wait
3254 OO
.ui
.WindowManager
.prototype.getReadyDelay = function () {
3259 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
3261 * @param {OO.ui.Window} win Window being closed
3262 * @param {Object} [data] Window closing data
3263 * @return {number} Milliseconds to wait
3265 OO
.ui
.WindowManager
.prototype.getHoldDelay = function () {
3270 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
3271 * executing the ‘teardown’ process.
3273 * @param {OO.ui.Window} win Window being closed
3274 * @param {Object} [data] Window closing data
3275 * @return {number} Milliseconds to wait
3277 OO
.ui
.WindowManager
.prototype.getTeardownDelay = function () {
3278 return this.modal
? 250 : 0;
3282 * Get a window by its symbolic name.
3284 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
3285 * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
3286 * for more information about using factories.
3287 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3289 * @param {string} name Symbolic name of the window
3290 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
3291 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
3292 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
3294 OO
.ui
.WindowManager
.prototype.getWindow = function ( name
) {
3295 var deferred
= $.Deferred(),
3296 win
= this.windows
[ name
];
3298 if ( !( win
instanceof OO
.ui
.Window
) ) {
3299 if ( this.factory
) {
3300 if ( !this.factory
.lookup( name
) ) {
3301 deferred
.reject( new OO
.ui
.Error(
3302 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
3305 win
= this.factory
.create( name
);
3306 this.addWindows( [ win
] );
3307 deferred
.resolve( win
);
3310 deferred
.reject( new OO
.ui
.Error(
3311 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
3315 deferred
.resolve( win
);
3318 return deferred
.promise();
3322 * Get current window.
3324 * @return {OO.ui.Window|null} Currently opening/opened/closing window
3326 OO
.ui
.WindowManager
.prototype.getCurrentWindow = function () {
3327 return this.currentWindow
;
3333 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
3334 * @param {Object} [data] Window opening data
3335 * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
3336 * See {@link #event-opening 'opening' event} for more information about `opening` promises.
3339 OO
.ui
.WindowManager
.prototype.openWindow = function ( win
, data
) {
3341 opening
= $.Deferred();
3343 // Argument handling
3344 if ( typeof win
=== 'string' ) {
3345 return this.getWindow( win
).then( function ( win
) {
3346 return manager
.openWindow( win
, data
);
3351 if ( !this.hasWindow( win
) ) {
3352 opening
.reject( new OO
.ui
.Error(
3353 'Cannot open window: window is not attached to manager'
3355 } else if ( this.preparingToOpen
|| this.opening
|| this.opened
) {
3356 opening
.reject( new OO
.ui
.Error(
3357 'Cannot open window: another window is opening or open'
3362 if ( opening
.state() !== 'rejected' ) {
3363 // If a window is currently closing, wait for it to complete
3364 this.preparingToOpen
= $.when( this.closing
);
3365 // Ensure handlers get called after preparingToOpen is set
3366 this.preparingToOpen
.done( function () {
3367 if ( manager
.modal
) {
3368 manager
.toggleGlobalEvents( true );
3369 manager
.toggleAriaIsolation( true );
3371 manager
.currentWindow
= win
;
3372 manager
.opening
= opening
;
3373 manager
.preparingToOpen
= null;
3374 manager
.emit( 'opening', win
, opening
, data
);
3375 setTimeout( function () {
3376 win
.setup( data
).then( function () {
3377 manager
.updateWindowSize( win
);
3378 manager
.opening
.notify( { state
: 'setup' } );
3379 setTimeout( function () {
3380 win
.ready( data
).then( function () {
3381 manager
.opening
.notify( { state
: 'ready' } );
3382 manager
.opening
= null;
3383 manager
.opened
= $.Deferred();
3384 opening
.resolve( manager
.opened
.promise(), data
);
3386 }, manager
.getReadyDelay() );
3388 }, manager
.getSetupDelay() );
3392 return opening
.promise();
3398 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3399 * @param {Object} [data] Window closing data
3400 * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
3401 * See {@link #event-closing 'closing' event} for more information about closing promises.
3402 * @throws {Error} An error is thrown if the window is not managed by the window manager.
3405 OO
.ui
.WindowManager
.prototype.closeWindow = function ( win
, data
) {
3407 closing
= $.Deferred(),
3410 // Argument handling
3411 if ( typeof win
=== 'string' ) {
3412 win
= this.windows
[ win
];
3413 } else if ( !this.hasWindow( win
) ) {
3419 closing
.reject( new OO
.ui
.Error(
3420 'Cannot close window: window is not attached to manager'
3422 } else if ( win
!== this.currentWindow
) {
3423 closing
.reject( new OO
.ui
.Error(
3424 'Cannot close window: window already closed with different data'
3426 } else if ( this.preparingToClose
|| this.closing
) {
3427 closing
.reject( new OO
.ui
.Error(
3428 'Cannot close window: window already closing with different data'
3433 if ( closing
.state() !== 'rejected' ) {
3434 // If the window is currently opening, close it when it's done
3435 this.preparingToClose
= $.when( this.opening
);
3436 // Ensure handlers get called after preparingToClose is set
3437 this.preparingToClose
.done( function () {
3438 manager
.closing
= closing
;
3439 manager
.preparingToClose
= null;
3440 manager
.emit( 'closing', win
, closing
, data
);
3441 opened
= manager
.opened
;
3442 manager
.opened
= null;
3443 opened
.resolve( closing
.promise(), data
);
3444 setTimeout( function () {
3445 win
.hold( data
).then( function () {
3446 closing
.notify( { state
: 'hold' } );
3447 setTimeout( function () {
3448 win
.teardown( data
).then( function () {
3449 closing
.notify( { state
: 'teardown' } );
3450 if ( manager
.modal
) {
3451 manager
.toggleGlobalEvents( false );
3452 manager
.toggleAriaIsolation( false );
3454 manager
.closing
= null;
3455 manager
.currentWindow
= null;
3456 closing
.resolve( data
);
3458 }, manager
.getTeardownDelay() );
3460 }, manager
.getHoldDelay() );
3464 return closing
.promise();
3468 * Add windows to the window manager.
3470 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
3471 * See the [OOjs ui documentation on MediaWiki] [2] for examples.
3472 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3474 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
3475 * by reference, symbolic name, or explicitly defined symbolic names.
3476 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
3477 * explicit nor a statically configured symbolic name.
3479 OO
.ui
.WindowManager
.prototype.addWindows = function ( windows
) {
3480 var i
, len
, win
, name
, list
;
3482 if ( Array
.isArray( windows
) ) {
3483 // Convert to map of windows by looking up symbolic names from static configuration
3485 for ( i
= 0, len
= windows
.length
; i
< len
; i
++ ) {
3486 name
= windows
[ i
].constructor.static.name
;
3487 if ( typeof name
!== 'string' ) {
3488 throw new Error( 'Cannot add window' );
3490 list
[ name
] = windows
[ i
];
3492 } else if ( OO
.isPlainObject( windows
) ) {
3497 for ( name
in list
) {
3499 this.windows
[ name
] = win
.toggle( false );
3500 this.$element
.append( win
.$element
);
3501 win
.setManager( this );
3506 * Remove the specified windows from the windows manager.
3508 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
3509 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
3510 * longer listens to events, use the #destroy method.
3512 * @param {string[]} names Symbolic names of windows to remove
3513 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3514 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
3516 OO
.ui
.WindowManager
.prototype.removeWindows = function ( names
) {
3517 var i
, len
, win
, name
, cleanupWindow
,
3520 cleanup = function ( name
, win
) {
3521 delete manager
.windows
[ name
];
3522 win
.$element
.detach();
3525 for ( i
= 0, len
= names
.length
; i
< len
; i
++ ) {
3527 win
= this.windows
[ name
];
3529 throw new Error( 'Cannot remove window' );
3531 cleanupWindow
= cleanup
.bind( null, name
, win
);
3532 promises
.push( this.closeWindow( name
).then( cleanupWindow
, cleanupWindow
) );
3535 return $.when
.apply( $, promises
);
3539 * Remove all windows from the window manager.
3541 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
3542 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
3543 * To remove just a subset of windows, use the #removeWindows method.
3545 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3547 OO
.ui
.WindowManager
.prototype.clearWindows = function () {
3548 return this.removeWindows( Object
.keys( this.windows
) );
3552 * Set dialog size. In general, this method should not be called directly.
3554 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3558 OO
.ui
.WindowManager
.prototype.updateWindowSize = function ( win
) {
3561 // Bypass for non-current, and thus invisible, windows
3562 if ( win
!== this.currentWindow
) {
3566 isFullscreen
= win
.getSize() === 'full';
3568 this.$element
.toggleClass( 'oo-ui-windowManager-fullscreen', isFullscreen
);
3569 this.$element
.toggleClass( 'oo-ui-windowManager-floating', !isFullscreen
);
3570 win
.setDimensions( win
.getSizeProperties() );
3572 this.emit( 'resize', win
);
3578 * Bind or unbind global events for scrolling.
3581 * @param {boolean} [on] Bind global events
3584 OO
.ui
.WindowManager
.prototype.toggleGlobalEvents = function ( on
) {
3585 var scrollWidth
, bodyMargin
,
3586 $body
= $( this.getElementDocument().body
),
3587 // We could have multiple window managers open so only modify
3588 // the body css at the bottom of the stack
3589 stackDepth
= $body
.data( 'windowManagerGlobalEvents' ) || 0 ;
3591 on
= on
=== undefined ? !!this.globalEvents
: !!on
;
3594 if ( !this.globalEvents
) {
3595 $( this.getElementWindow() ).on( {
3596 // Start listening for top-level window dimension changes
3597 'orientationchange resize': this.onWindowResizeHandler
3599 if ( stackDepth
=== 0 ) {
3600 scrollWidth
= window
.innerWidth
- document
.documentElement
.clientWidth
;
3601 bodyMargin
= parseFloat( $body
.css( 'margin-right' ) ) || 0;
3604 'margin-right': bodyMargin
+ scrollWidth
3608 this.globalEvents
= true;
3610 } else if ( this.globalEvents
) {
3611 $( this.getElementWindow() ).off( {
3612 // Stop listening for top-level window dimension changes
3613 'orientationchange resize': this.onWindowResizeHandler
3616 if ( stackDepth
=== 0 ) {
3622 this.globalEvents
= false;
3624 $body
.data( 'windowManagerGlobalEvents', stackDepth
);
3630 * Toggle screen reader visibility of content other than the window manager.
3633 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3636 OO
.ui
.WindowManager
.prototype.toggleAriaIsolation = function ( isolate
) {
3637 isolate
= isolate
=== undefined ? !this.$ariaHidden
: !!isolate
;
3640 if ( !this.$ariaHidden
) {
3641 // Hide everything other than the window manager from screen readers
3642 this.$ariaHidden
= $( 'body' )
3644 .not( this.$element
.parentsUntil( 'body' ).last() )
3645 .attr( 'aria-hidden', '' );
3647 } else if ( this.$ariaHidden
) {
3648 // Restore screen reader visibility
3649 this.$ariaHidden
.removeAttr( 'aria-hidden' );
3650 this.$ariaHidden
= null;
3657 * Destroy the window manager.
3659 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
3660 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
3663 OO
.ui
.WindowManager
.prototype.destroy = function () {
3664 this.toggleGlobalEvents( false );
3665 this.toggleAriaIsolation( false );
3666 this.clearWindows();
3667 this.$element
.remove();
3671 * Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong
3672 * in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the
3673 * appearance and functionality of the error interface.
3675 * The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error
3676 * is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget
3677 * that initiated the failed process will be disabled.
3679 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the
3682 * For an example of error interfaces, please see the [OOjs UI documentation on MediaWiki][1].
3684 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Processes_and_errors
3689 * @param {string|jQuery} message Description of error
3690 * @param {Object} [config] Configuration options
3691 * @cfg {boolean} [recoverable=true] Error is recoverable.
3692 * By default, errors are recoverable, and users can try the process again.
3693 * @cfg {boolean} [warning=false] Error is a warning.
3694 * If the error is a warning, the error interface will include a
3695 * 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning
3696 * is not triggered a second time if the user chooses to continue.
3698 OO
.ui
.Error
= function OoUiError( message
, config
) {
3699 // Allow passing positional parameters inside the config object
3700 if ( OO
.isPlainObject( message
) && config
=== undefined ) {
3702 message
= config
.message
;
3705 // Configuration initialization
3706 config
= config
|| {};
3709 this.message
= message
instanceof jQuery
? message
: String( message
);
3710 this.recoverable
= config
.recoverable
=== undefined || !!config
.recoverable
;
3711 this.warning
= !!config
.warning
;
3716 OO
.initClass( OO
.ui
.Error
);
3721 * Check if the error is recoverable.
3723 * If the error is recoverable, users are able to try the process again.
3725 * @return {boolean} Error is recoverable
3727 OO
.ui
.Error
.prototype.isRecoverable = function () {
3728 return this.recoverable
;
3732 * Check if the error is a warning.
3734 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
3736 * @return {boolean} Error is warning
3738 OO
.ui
.Error
.prototype.isWarning = function () {
3739 return this.warning
;
3743 * Get error message as DOM nodes.
3745 * @return {jQuery} Error message in DOM nodes
3747 OO
.ui
.Error
.prototype.getMessage = function () {
3748 return this.message
instanceof jQuery
?
3749 this.message
.clone() :
3750 $( '<div>' ).text( this.message
).contents();
3754 * Get the error message text.
3756 * @return {string} Error message
3758 OO
.ui
.Error
.prototype.getMessageText = function () {
3759 return this.message
instanceof jQuery
? this.message
.text() : this.message
;
3763 * Wraps an HTML snippet for use with configuration values which default
3764 * to strings. This bypasses the default html-escaping done to string
3770 * @param {string} [content] HTML content
3772 OO
.ui
.HtmlSnippet
= function OoUiHtmlSnippet( content
) {
3774 this.content
= content
;
3779 OO
.initClass( OO
.ui
.HtmlSnippet
);
3786 * @return {string} Unchanged HTML snippet.
3788 OO
.ui
.HtmlSnippet
.prototype.toString = function () {
3789 return this.content
;
3793 * A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
3796 * - **number**: the process will wait for the specified number of milliseconds before proceeding.
3797 * - **promise**: the process will continue to the next step when the promise is successfully resolved
3798 * or stop if the promise is rejected.
3799 * - **function**: the process will execute the function. The process will stop if the function returns
3800 * either a boolean `false` or a promise that is rejected; if the function returns a number, the process
3801 * will wait for that number of milliseconds before proceeding.
3803 * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
3804 * configured, users can dismiss the error and try the process again, or not. If a process is stopped,
3805 * its remaining steps will not be performed.
3810 * @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
3811 * that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
3812 * @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
3813 * a number or promise.
3814 * @return {Object} Step object, with `callback` and `context` properties
3816 OO
.ui
.Process = function ( step
, context
) {
3821 if ( step
!== undefined ) {
3822 this.next( step
, context
);
3828 OO
.initClass( OO
.ui
.Process
);
3833 * Start the process.
3835 * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
3836 * If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
3837 * and any remaining steps are not performed.
3839 OO
.ui
.Process
.prototype.execute = function () {
3840 var i
, len
, promise
;
3843 * Continue execution.
3846 * @param {Array} step A function and the context it should be called in
3847 * @return {Function} Function that continues the process
3849 function proceed( step
) {
3850 return function () {
3851 // Execute step in the correct context
3853 result
= step
.callback
.call( step
.context
);
3855 if ( result
=== false ) {
3856 // Use rejected promise for boolean false results
3857 return $.Deferred().reject( [] ).promise();
3859 if ( typeof result
=== 'number' ) {
3861 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3863 // Use a delayed promise for numbers, expecting them to be in milliseconds
3864 deferred
= $.Deferred();
3865 setTimeout( deferred
.resolve
, result
);
3866 return deferred
.promise();
3868 if ( result
instanceof OO
.ui
.Error
) {
3869 // Use rejected promise for error
3870 return $.Deferred().reject( [ result
] ).promise();
3872 if ( Array
.isArray( result
) && result
.length
&& result
[ 0 ] instanceof OO
.ui
.Error
) {
3873 // Use rejected promise for list of errors
3874 return $.Deferred().reject( result
).promise();
3876 // Duck-type the object to see if it can produce a promise
3877 if ( result
&& $.isFunction( result
.promise
) ) {
3878 // Use a promise generated from the result
3879 return result
.promise();
3881 // Use resolved promise for other results
3882 return $.Deferred().resolve().promise();
3886 if ( this.steps
.length
) {
3887 // Generate a chain reaction of promises
3888 promise
= proceed( this.steps
[ 0 ] )();
3889 for ( i
= 1, len
= this.steps
.length
; i
< len
; i
++ ) {
3890 promise
= promise
.then( proceed( this.steps
[ i
] ) );
3893 promise
= $.Deferred().resolve().promise();
3900 * Create a process step.
3903 * @param {number|jQuery.Promise|Function} step
3905 * - Number of milliseconds to wait before proceeding
3906 * - Promise that must be resolved before proceeding
3907 * - Function to execute
3908 * - If the function returns a boolean false the process will stop
3909 * - If the function returns a promise, the process will continue to the next
3910 * step when the promise is resolved or stop if the promise is rejected
3911 * - If the function returns a number, the process will wait for that number of
3912 * milliseconds before proceeding
3913 * @param {Object} [context=null] Execution context of the function. The context is
3914 * ignored if the step is a number or promise.
3915 * @return {Object} Step object, with `callback` and `context` properties
3917 OO
.ui
.Process
.prototype.createStep = function ( step
, context
) {
3918 if ( typeof step
=== 'number' || $.isFunction( step
.promise
) ) {
3920 callback: function () {
3926 if ( $.isFunction( step
) ) {
3932 throw new Error( 'Cannot create process step: number, promise or function expected' );
3936 * Add step to the beginning of the process.
3938 * @inheritdoc #createStep
3939 * @return {OO.ui.Process} this
3942 OO
.ui
.Process
.prototype.first = function ( step
, context
) {
3943 this.steps
.unshift( this.createStep( step
, context
) );
3948 * Add step to the end of the process.
3950 * @inheritdoc #createStep
3951 * @return {OO.ui.Process} this
3954 OO
.ui
.Process
.prototype.next = function ( step
, context
) {
3955 this.steps
.push( this.createStep( step
, context
) );
3960 * A ToolFactory creates tools on demand. All tools ({@link OO.ui.Tool Tools}, {@link OO.ui.PopupTool PopupTools},
3961 * and {@link OO.ui.ToolGroupTool ToolGroupTools}) must be registered with a tool factory. Tools are
3962 * registered by their symbolic name. See {@link OO.ui.Toolbar toolbars} for an example.
3964 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
3966 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
3969 * @extends OO.Factory
3972 OO
.ui
.ToolFactory
= function OoUiToolFactory() {
3973 // Parent constructor
3974 OO
.ui
.ToolFactory
.parent
.call( this );
3979 OO
.inheritClass( OO
.ui
.ToolFactory
, OO
.Factory
);
3984 * Get tools from the factory
3986 * @param {Array} include Included tools
3987 * @param {Array} exclude Excluded tools
3988 * @param {Array} promote Promoted tools
3989 * @param {Array} demote Demoted tools
3990 * @return {string[]} List of tools
3992 OO
.ui
.ToolFactory
.prototype.getTools = function ( include
, exclude
, promote
, demote
) {
3993 var i
, len
, included
, promoted
, demoted
,
3997 // Collect included and not excluded tools
3998 included
= OO
.simpleArrayDifference( this.extract( include
), this.extract( exclude
) );
4001 promoted
= this.extract( promote
, used
);
4002 demoted
= this.extract( demote
, used
);
4005 for ( i
= 0, len
= included
.length
; i
< len
; i
++ ) {
4006 if ( !used
[ included
[ i
] ] ) {
4007 auto
.push( included
[ i
] );
4011 return promoted
.concat( auto
).concat( demoted
);
4015 * Get a flat list of names from a list of names or groups.
4017 * Tools can be specified in the following ways:
4019 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
4020 * - All tools in a group: `{ group: 'group-name' }`
4021 * - All tools: `'*'`
4024 * @param {Array|string} collection List of tools
4025 * @param {Object} [used] Object with names that should be skipped as properties; extracted
4026 * names will be added as properties
4027 * @return {string[]} List of extracted names
4029 OO
.ui
.ToolFactory
.prototype.extract = function ( collection
, used
) {
4030 var i
, len
, item
, name
, tool
,
4033 if ( collection
=== '*' ) {
4034 for ( name
in this.registry
) {
4035 tool
= this.registry
[ name
];
4037 // Only add tools by group name when auto-add is enabled
4038 tool
.static.autoAddToCatchall
&&
4039 // Exclude already used tools
4040 ( !used
|| !used
[ name
] )
4044 used
[ name
] = true;
4048 } else if ( Array
.isArray( collection
) ) {
4049 for ( i
= 0, len
= collection
.length
; i
< len
; i
++ ) {
4050 item
= collection
[ i
];
4051 // Allow plain strings as shorthand for named tools
4052 if ( typeof item
=== 'string' ) {
4053 item
= { name
: item
};
4055 if ( OO
.isPlainObject( item
) ) {
4057 for ( name
in this.registry
) {
4058 tool
= this.registry
[ name
];
4060 // Include tools with matching group
4061 tool
.static.group
=== item
.group
&&
4062 // Only add tools by group name when auto-add is enabled
4063 tool
.static.autoAddToGroup
&&
4064 // Exclude already used tools
4065 ( !used
|| !used
[ name
] )
4069 used
[ name
] = true;
4073 // Include tools with matching name and exclude already used tools
4074 } else if ( item
.name
&& ( !used
|| !used
[ item
.name
] ) ) {
4075 names
.push( item
.name
);
4077 used
[ item
.name
] = true;
4087 * ToolGroupFactories create {@link OO.ui.ToolGroup toolgroups} on demand. The toolgroup classes must
4088 * specify a symbolic name and be registered with the factory. The following classes are registered by
4091 * - {@link OO.ui.BarToolGroup BarToolGroups} (‘bar’)
4092 * - {@link OO.ui.MenuToolGroup MenuToolGroups} (‘menu’)
4093 * - {@link OO.ui.ListToolGroup ListToolGroups} (‘list’)
4095 * See {@link OO.ui.Toolbar toolbars} for an example.
4097 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4099 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4101 * @extends OO.Factory
4104 OO
.ui
.ToolGroupFactory
= function OoUiToolGroupFactory() {
4105 var i
, l
, defaultClasses
;
4106 // Parent constructor
4107 OO
.Factory
.call( this );
4109 defaultClasses
= this.constructor.static.getDefaultClasses();
4111 // Register default toolgroups
4112 for ( i
= 0, l
= defaultClasses
.length
; i
< l
; i
++ ) {
4113 this.register( defaultClasses
[ i
] );
4119 OO
.inheritClass( OO
.ui
.ToolGroupFactory
, OO
.Factory
);
4121 /* Static Methods */
4124 * Get a default set of classes to be registered on construction.
4126 * @return {Function[]} Default classes
4128 OO
.ui
.ToolGroupFactory
.static.getDefaultClasses = function () {
4131 OO
.ui
.ListToolGroup
,
4143 * @param {Object} [config] Configuration options
4145 OO
.ui
.Theme
= function OoUiTheme( config
) {
4146 // Configuration initialization
4147 config
= config
|| {};
4152 OO
.initClass( OO
.ui
.Theme
);
4157 * Get a list of classes to be applied to a widget.
4159 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
4160 * otherwise state transitions will not work properly.
4162 * @param {OO.ui.Element} element Element for which to get classes
4163 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4165 OO
.ui
.Theme
.prototype.getElementClasses = function ( /* element */ ) {
4166 return { on
: [], off
: [] };
4170 * Update CSS classes provided by the theme.
4172 * For elements with theme logic hooks, this should be called any time there's a state change.
4174 * @param {OO.ui.Element} element Element for which to update classes
4175 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4177 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
4178 var $elements
= $( [] ),
4179 classes
= this.getElementClasses( element
);
4181 if ( element
.$icon
) {
4182 $elements
= $elements
.add( element
.$icon
);
4184 if ( element
.$indicator
) {
4185 $elements
= $elements
.add( element
.$indicator
);
4189 .removeClass( classes
.off
.join( ' ' ) )
4190 .addClass( classes
.on
.join( ' ' ) );
4194 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
4195 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
4196 * order in which users will navigate through the focusable elements via the "tab" key.
4199 * // TabIndexedElement is mixed into the ButtonWidget class
4200 * // to provide a tabIndex property.
4201 * var button1 = new OO.ui.ButtonWidget( {
4205 * var button2 = new OO.ui.ButtonWidget( {
4209 * var button3 = new OO.ui.ButtonWidget( {
4213 * var button4 = new OO.ui.ButtonWidget( {
4217 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
4223 * @param {Object} [config] Configuration options
4224 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
4225 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
4226 * functionality will be applied to it instead.
4227 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
4228 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
4229 * to remove the element from the tab-navigation flow.
4231 OO
.ui
.mixin
.TabIndexedElement
= function OoUiMixinTabIndexedElement( config
) {
4232 // Configuration initialization
4233 config
= $.extend( { tabIndex
: 0 }, config
);
4236 this.$tabIndexed
= null;
4237 this.tabIndex
= null;
4240 this.connect( this, { disable
: 'onTabIndexedElementDisable' } );
4243 this.setTabIndex( config
.tabIndex
);
4244 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
4249 OO
.initClass( OO
.ui
.mixin
.TabIndexedElement
);
4254 * Set the element that should use the tabindex functionality.
4256 * This method is used to retarget a tabindex mixin so that its functionality applies
4257 * to the specified element. If an element is currently using the functionality, the mixin’s
4258 * effect on that element is removed before the new element is set up.
4260 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
4263 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
4264 var tabIndex
= this.tabIndex
;
4265 // Remove attributes from old $tabIndexed
4266 this.setTabIndex( null );
4267 // Force update of new $tabIndexed
4268 this.$tabIndexed
= $tabIndexed
;
4269 this.tabIndex
= tabIndex
;
4270 return this.updateTabIndex();
4274 * Set the value of the tabindex.
4276 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
4279 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
4280 tabIndex
= typeof tabIndex
=== 'number' ? tabIndex
: null;
4282 if ( this.tabIndex
!== tabIndex
) {
4283 this.tabIndex
= tabIndex
;
4284 this.updateTabIndex();
4291 * Update the `tabindex` attribute, in case of changes to tab index or
4297 OO
.ui
.mixin
.TabIndexedElement
.prototype.updateTabIndex = function () {
4298 if ( this.$tabIndexed
) {
4299 if ( this.tabIndex
!== null ) {
4300 // Do not index over disabled elements
4301 this.$tabIndexed
.attr( {
4302 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
4303 // Support: ChromeVox and NVDA
4304 // These do not seem to inherit aria-disabled from parent elements
4305 'aria-disabled': this.isDisabled().toString()
4308 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
4315 * Handle disable events.
4318 * @param {boolean} disabled Element is disabled
4320 OO
.ui
.mixin
.TabIndexedElement
.prototype.onTabIndexedElementDisable = function () {
4321 this.updateTabIndex();
4325 * Get the value of the tabindex.
4327 * @return {number|null} Tabindex value
4329 OO
.ui
.mixin
.TabIndexedElement
.prototype.getTabIndex = function () {
4330 return this.tabIndex
;
4334 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
4335 * interface element that can be configured with access keys for accessibility.
4336 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
4338 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
4343 * @param {Object} [config] Configuration options
4344 * @cfg {jQuery} [$button] The button element created by the class.
4345 * If this configuration is omitted, the button element will use a generated `<a>`.
4346 * @cfg {boolean} [framed=true] Render the button with a frame
4348 OO
.ui
.mixin
.ButtonElement
= function OoUiMixinButtonElement( config
) {
4349 // Configuration initialization
4350 config
= config
|| {};
4353 this.$button
= null;
4355 this.active
= false;
4356 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
4357 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
4358 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
4359 this.onKeyUpHandler
= this.onKeyUp
.bind( this );
4360 this.onClickHandler
= this.onClick
.bind( this );
4361 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
4364 this.$element
.addClass( 'oo-ui-buttonElement' );
4365 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
4366 this.setButtonElement( config
.$button
|| $( '<a>' ) );
4371 OO
.initClass( OO
.ui
.mixin
.ButtonElement
);
4373 /* Static Properties */
4376 * Cancel mouse down events.
4378 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
4379 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
4380 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
4385 * @property {boolean}
4387 OO
.ui
.mixin
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
4392 * A 'click' event is emitted when the button element is clicked.
4400 * Set the button element.
4402 * This method is used to retarget a button mixin so that its functionality applies to
4403 * the specified button element instead of the one created by the class. If a button element
4404 * is already set, the method will remove the mixin’s effect on that element.
4406 * @param {jQuery} $button Element to use as button
4408 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
4409 if ( this.$button
) {
4411 .removeClass( 'oo-ui-buttonElement-button' )
4412 .removeAttr( 'role accesskey' )
4414 mousedown
: this.onMouseDownHandler
,
4415 keydown
: this.onKeyDownHandler
,
4416 click
: this.onClickHandler
,
4417 keypress
: this.onKeyPressHandler
4421 this.$button
= $button
4422 .addClass( 'oo-ui-buttonElement-button' )
4423 .attr( { role
: 'button' } )
4425 mousedown
: this.onMouseDownHandler
,
4426 keydown
: this.onKeyDownHandler
,
4427 click
: this.onClickHandler
,
4428 keypress
: this.onKeyPressHandler
4433 * Handles mouse down events.
4436 * @param {jQuery.Event} e Mouse down event
4438 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown = function ( e
) {
4439 if ( this.isDisabled() || e
.which
!== 1 ) {
4442 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
4443 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4444 // reliably remove the pressed class
4445 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler
);
4446 // Prevent change of focus unless specifically configured otherwise
4447 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
4453 * Handles mouse up events.
4456 * @param {jQuery.Event} e Mouse up event
4458 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp = function ( e
) {
4459 if ( this.isDisabled() || e
.which
!== 1 ) {
4462 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
4463 // Stop listening for mouseup, since we only needed this once
4464 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler
);
4468 * Handles mouse click events.
4471 * @param {jQuery.Event} e Mouse click event
4474 OO
.ui
.mixin
.ButtonElement
.prototype.onClick = function ( e
) {
4475 if ( !this.isDisabled() && e
.which
=== 1 ) {
4476 if ( this.emit( 'click' ) ) {
4483 * Handles key down events.
4486 * @param {jQuery.Event} e Key down event
4488 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyDown = function ( e
) {
4489 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
4492 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
4493 // Run the keyup handler no matter where the key is when the button is let go, so we can
4494 // reliably remove the pressed class
4495 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler
);
4499 * Handles key up events.
4502 * @param {jQuery.Event} e Key up event
4504 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyUp = function ( e
) {
4505 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
4508 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
4509 // Stop listening for keyup, since we only needed this once
4510 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler
);
4514 * Handles key press events.
4517 * @param {jQuery.Event} e Key press event
4520 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyPress = function ( e
) {
4521 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
4522 if ( this.emit( 'click' ) ) {
4529 * Check if button has a frame.
4531 * @return {boolean} Button is framed
4533 OO
.ui
.mixin
.ButtonElement
.prototype.isFramed = function () {
4538 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
4540 * @param {boolean} [framed] Make button framed, omit to toggle
4543 OO
.ui
.mixin
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
4544 framed
= framed
=== undefined ? !this.framed
: !!framed
;
4545 if ( framed
!== this.framed
) {
4546 this.framed
= framed
;
4548 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
4549 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
4550 this.updateThemeClasses();
4557 * Set the button to its 'active' state.
4559 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
4560 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
4561 * for other button types.
4563 * @param {boolean} [value] Make button active
4566 OO
.ui
.mixin
.ButtonElement
.prototype.setActive = function ( value
) {
4567 this.$element
.toggleClass( 'oo-ui-buttonElement-active', !!value
);
4572 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4573 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4574 * items from the group is done through the interface the class provides.
4575 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4577 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4583 * @param {Object} [config] Configuration options
4584 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4585 * is omitted, the group element will use a generated `<div>`.
4587 OO
.ui
.mixin
.GroupElement
= function OoUiMixinGroupElement( config
) {
4588 // Configuration initialization
4589 config
= config
|| {};
4594 this.aggregateItemEvents
= {};
4597 this.setGroupElement( config
.$group
|| $( '<div>' ) );
4603 * Set the group element.
4605 * If an element is already set, items will be moved to the new element.
4607 * @param {jQuery} $group Element to use as group
4609 OO
.ui
.mixin
.GroupElement
.prototype.setGroupElement = function ( $group
) {
4612 this.$group
= $group
;
4613 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4614 this.$group
.append( this.items
[ i
].$element
);
4619 * Check if a group contains no items.
4621 * @return {boolean} Group is empty
4623 OO
.ui
.mixin
.GroupElement
.prototype.isEmpty = function () {
4624 return !this.items
.length
;
4628 * Get all items in the group.
4630 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4631 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4634 * @return {OO.ui.Element[]} An array of items.
4636 OO
.ui
.mixin
.GroupElement
.prototype.getItems = function () {
4637 return this.items
.slice( 0 );
4641 * Get an item by its data.
4643 * Only the first item with matching data will be returned. To return all matching items,
4644 * use the #getItemsFromData method.
4646 * @param {Object} data Item data to search for
4647 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4649 OO
.ui
.mixin
.GroupElement
.prototype.getItemFromData = function ( data
) {
4651 hash
= OO
.getHash( data
);
4653 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4654 item
= this.items
[ i
];
4655 if ( hash
=== OO
.getHash( item
.getData() ) ) {
4664 * Get items by their data.
4666 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4668 * @param {Object} data Item data to search for
4669 * @return {OO.ui.Element[]} Items with equivalent data
4671 OO
.ui
.mixin
.GroupElement
.prototype.getItemsFromData = function ( data
) {
4673 hash
= OO
.getHash( data
),
4676 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4677 item
= this.items
[ i
];
4678 if ( hash
=== OO
.getHash( item
.getData() ) ) {
4687 * Aggregate the events emitted by the group.
4689 * When events are aggregated, the group will listen to all contained items for the event,
4690 * and then emit the event under a new name. The new event will contain an additional leading
4691 * parameter containing the item that emitted the original event. Other arguments emitted from
4692 * the original event are passed through.
4694 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
4695 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
4696 * A `null` value will remove aggregated events.
4698 * @throws {Error} An error is thrown if aggregation already exists.
4700 OO
.ui
.mixin
.GroupElement
.prototype.aggregate = function ( events
) {
4701 var i
, len
, item
, add
, remove
, itemEvent
, groupEvent
;
4703 for ( itemEvent
in events
) {
4704 groupEvent
= events
[ itemEvent
];
4706 // Remove existing aggregated event
4707 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4708 // Don't allow duplicate aggregations
4710 throw new Error( 'Duplicate item event aggregation for ' + itemEvent
);
4712 // Remove event aggregation from existing items
4713 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4714 item
= this.items
[ i
];
4715 if ( item
.connect
&& item
.disconnect
) {
4717 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4718 item
.disconnect( this, remove
);
4721 // Prevent future items from aggregating event
4722 delete this.aggregateItemEvents
[ itemEvent
];
4725 // Add new aggregate event
4727 // Make future items aggregate event
4728 this.aggregateItemEvents
[ itemEvent
] = groupEvent
;
4729 // Add event aggregation to existing items
4730 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4731 item
= this.items
[ i
];
4732 if ( item
.connect
&& item
.disconnect
) {
4734 add
[ itemEvent
] = [ 'emit', groupEvent
, item
];
4735 item
.connect( this, add
);
4743 * Add items to the group.
4745 * Items will be added to the end of the group array unless the optional `index` parameter specifies
4746 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
4748 * @param {OO.ui.Element[]} items An array of items to add to the group
4749 * @param {number} [index] Index of the insertion point
4752 OO
.ui
.mixin
.GroupElement
.prototype.addItems = function ( items
, index
) {
4753 var i
, len
, item
, event
, events
, currentIndex
,
4756 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
4759 // Check if item exists then remove it first, effectively "moving" it
4760 currentIndex
= this.items
.indexOf( item
);
4761 if ( currentIndex
>= 0 ) {
4762 this.removeItems( [ item
] );
4763 // Adjust index to compensate for removal
4764 if ( currentIndex
< index
) {
4769 if ( item
.connect
&& item
.disconnect
&& !$.isEmptyObject( this.aggregateItemEvents
) ) {
4771 for ( event
in this.aggregateItemEvents
) {
4772 events
[ event
] = [ 'emit', this.aggregateItemEvents
[ event
], item
];
4774 item
.connect( this, events
);
4776 item
.setElementGroup( this );
4777 itemElements
.push( item
.$element
.get( 0 ) );
4780 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
4781 this.$group
.append( itemElements
);
4782 this.items
.push
.apply( this.items
, items
);
4783 } else if ( index
=== 0 ) {
4784 this.$group
.prepend( itemElements
);
4785 this.items
.unshift
.apply( this.items
, items
);
4787 this.items
[ index
].$element
.before( itemElements
);
4788 this.items
.splice
.apply( this.items
, [ index
, 0 ].concat( items
) );
4795 * Remove the specified items from a group.
4797 * Removed items are detached (not removed) from the DOM so that they may be reused.
4798 * To remove all items from a group, you may wish to use the #clearItems method instead.
4800 * @param {OO.ui.Element[]} items An array of items to remove
4803 OO
.ui
.mixin
.GroupElement
.prototype.removeItems = function ( items
) {
4804 var i
, len
, item
, index
, remove
, itemEvent
;
4806 // Remove specific items
4807 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
4809 index
= this.items
.indexOf( item
);
4810 if ( index
!== -1 ) {
4812 item
.connect
&& item
.disconnect
&&
4813 !$.isEmptyObject( this.aggregateItemEvents
)
4816 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4817 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4819 item
.disconnect( this, remove
);
4821 item
.setElementGroup( null );
4822 this.items
.splice( index
, 1 );
4823 item
.$element
.detach();
4831 * Clear all items from the group.
4833 * Cleared items are detached from the DOM, not removed, so that they may be reused.
4834 * To remove only a subset of items from a group, use the #removeItems method.
4838 OO
.ui
.mixin
.GroupElement
.prototype.clearItems = function () {
4839 var i
, len
, item
, remove
, itemEvent
;
4842 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4843 item
= this.items
[ i
];
4845 item
.connect
&& item
.disconnect
&&
4846 !$.isEmptyObject( this.aggregateItemEvents
)
4849 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4850 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4852 item
.disconnect( this, remove
);
4854 item
.setElementGroup( null );
4855 item
.$element
.detach();
4863 * DraggableElement is a mixin class used to create elements that can be clicked
4864 * and dragged by a mouse to a new position within a group. This class must be used
4865 * in conjunction with OO.ui.mixin.DraggableGroupElement, which provides a container for
4866 * the draggable elements.
4873 OO
.ui
.mixin
.DraggableElement
= function OoUiMixinDraggableElement() {
4877 // Initialize and events
4879 .attr( 'draggable', true )
4880 .addClass( 'oo-ui-draggableElement' )
4882 dragstart
: this.onDragStart
.bind( this ),
4883 dragover
: this.onDragOver
.bind( this ),
4884 dragend
: this.onDragEnd
.bind( this ),
4885 drop
: this.onDrop
.bind( this )
4889 OO
.initClass( OO
.ui
.mixin
.DraggableElement
);
4896 * A dragstart event is emitted when the user clicks and begins dragging an item.
4897 * @param {OO.ui.mixin.DraggableElement} item The item the user has clicked and is dragging with the mouse.
4902 * A dragend event is emitted when the user drags an item and releases the mouse,
4903 * thus terminating the drag operation.
4908 * A drop event is emitted when the user drags an item and then releases the mouse button
4909 * over a valid target.
4912 /* Static Properties */
4915 * @inheritdoc OO.ui.mixin.ButtonElement
4917 OO
.ui
.mixin
.DraggableElement
.static.cancelButtonMouseDownEvents
= false;
4922 * Respond to dragstart event.
4925 * @param {jQuery.Event} event jQuery event
4928 OO
.ui
.mixin
.DraggableElement
.prototype.onDragStart = function ( e
) {
4929 var dataTransfer
= e
.originalEvent
.dataTransfer
;
4930 // Define drop effect
4931 dataTransfer
.dropEffect
= 'none';
4932 dataTransfer
.effectAllowed
= 'move';
4934 // We must set up a dataTransfer data property or Firefox seems to
4935 // ignore the fact the element is draggable.
4937 dataTransfer
.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
4939 // The above is only for Firefox. Move on if it fails.
4941 // Add dragging class
4942 this.$element
.addClass( 'oo-ui-draggableElement-dragging' );
4944 this.emit( 'dragstart', this );
4949 * Respond to dragend event.
4954 OO
.ui
.mixin
.DraggableElement
.prototype.onDragEnd = function () {
4955 this.$element
.removeClass( 'oo-ui-draggableElement-dragging' );
4956 this.emit( 'dragend' );
4960 * Handle drop event.
4963 * @param {jQuery.Event} event jQuery event
4966 OO
.ui
.mixin
.DraggableElement
.prototype.onDrop = function ( e
) {
4968 this.emit( 'drop', e
);
4972 * In order for drag/drop to work, the dragover event must
4973 * return false and stop propogation.
4977 OO
.ui
.mixin
.DraggableElement
.prototype.onDragOver = function ( e
) {
4983 * Store it in the DOM so we can access from the widget drag event
4986 * @param {number} Item index
4988 OO
.ui
.mixin
.DraggableElement
.prototype.setIndex = function ( index
) {
4989 if ( this.index
!== index
) {
4991 this.$element
.data( 'index', index
);
4999 * @return {number} Item index
5001 OO
.ui
.mixin
.DraggableElement
.prototype.getIndex = function () {
5006 * DraggableGroupElement is a mixin class used to create a group element to
5007 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
5008 * The class is used with OO.ui.mixin.DraggableElement.
5012 * @mixins OO.ui.mixin.GroupElement
5015 * @param {Object} [config] Configuration options
5016 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
5017 * should match the layout of the items. Items displayed in a single row
5018 * or in several rows should use horizontal orientation. The vertical orientation should only be
5019 * used when the items are displayed in a single column. Defaults to 'vertical'
5021 OO
.ui
.mixin
.DraggableGroupElement
= function OoUiMixinDraggableGroupElement( config
) {
5022 // Configuration initialization
5023 config
= config
|| {};
5025 // Parent constructor
5026 OO
.ui
.mixin
.GroupElement
.call( this, config
);
5029 this.orientation
= config
.orientation
|| 'vertical';
5030 this.dragItem
= null;
5031 this.itemDragOver
= null;
5033 this.sideInsertion
= '';
5037 dragstart
: 'itemDragStart',
5038 dragend
: 'itemDragEnd',
5041 this.connect( this, {
5042 itemDragStart
: 'onItemDragStart',
5043 itemDrop
: 'onItemDrop',
5044 itemDragEnd
: 'onItemDragEnd'
5047 dragover
: this.onDragOver
.bind( this ),
5048 dragleave
: this.onDragLeave
.bind( this )
5052 if ( Array
.isArray( config
.items
) ) {
5053 this.addItems( config
.items
);
5055 this.$placeholder
= $( '<div>' )
5056 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
5058 .addClass( 'oo-ui-draggableGroupElement' )
5059 .append( this.$status
)
5060 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation
=== 'horizontal' )
5061 .prepend( this.$placeholder
);
5065 OO
.mixinClass( OO
.ui
.mixin
.DraggableGroupElement
, OO
.ui
.mixin
.GroupElement
);
5070 * A 'reorder' event is emitted when the order of items in the group changes.
5073 * @param {OO.ui.mixin.DraggableElement} item Reordered item
5074 * @param {number} [newIndex] New index for the item
5080 * Respond to item drag start event
5083 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5085 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDragStart = function ( item
) {
5088 // Map the index of each object
5089 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5090 this.items
[ i
].setIndex( i
);
5093 if ( this.orientation
=== 'horizontal' ) {
5094 // Set the height of the indicator
5095 this.$placeholder
.css( {
5096 height
: item
.$element
.outerHeight(),
5100 // Set the width of the indicator
5101 this.$placeholder
.css( {
5103 width
: item
.$element
.outerWidth()
5106 this.setDragItem( item
);
5110 * Respond to item drag end event
5114 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDragEnd = function () {
5115 this.unsetDragItem();
5120 * Handle drop event and switch the order of the items accordingly
5123 * @param {OO.ui.mixin.DraggableElement} item Dropped item
5126 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDrop = function ( item
) {
5127 var toIndex
= item
.getIndex();
5128 // Check if the dropped item is from the current group
5129 // TODO: Figure out a way to configure a list of legally droppable
5130 // elements even if they are not yet in the list
5131 if ( this.getDragItem() ) {
5132 // If the insertion point is 'after', the insertion index
5133 // is shifted to the right (or to the left in RTL, hence 'after')
5134 if ( this.sideInsertion
=== 'after' ) {
5137 // Emit change event
5138 this.emit( 'reorder', this.getDragItem(), toIndex
);
5140 this.unsetDragItem();
5141 // Return false to prevent propogation
5146 * Handle dragleave event.
5150 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onDragLeave = function () {
5151 // This means the item was dragged outside the widget
5154 .addClass( 'oo-ui-element-hidden' );
5158 * Respond to dragover event
5161 * @param {jQuery.Event} event Event details
5163 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onDragOver = function ( e
) {
5164 var dragOverObj
, $optionWidget
, itemOffset
, itemMidpoint
, itemBoundingRect
,
5165 itemSize
, cssOutput
, dragPosition
, itemIndex
, itemPosition
,
5166 clientX
= e
.originalEvent
.clientX
,
5167 clientY
= e
.originalEvent
.clientY
;
5169 // Get the OptionWidget item we are dragging over
5170 dragOverObj
= this.getElementDocument().elementFromPoint( clientX
, clientY
);
5171 $optionWidget
= $( dragOverObj
).closest( '.oo-ui-draggableElement' );
5172 if ( $optionWidget
[ 0 ] ) {
5173 itemOffset
= $optionWidget
.offset();
5174 itemBoundingRect
= $optionWidget
[ 0 ].getBoundingClientRect();
5175 itemPosition
= $optionWidget
.position();
5176 itemIndex
= $optionWidget
.data( 'index' );
5181 this.isDragging() &&
5182 itemIndex
!== this.getDragItem().getIndex()
5184 if ( this.orientation
=== 'horizontal' ) {
5185 // Calculate where the mouse is relative to the item width
5186 itemSize
= itemBoundingRect
.width
;
5187 itemMidpoint
= itemBoundingRect
.left
+ itemSize
/ 2;
5188 dragPosition
= clientX
;
5189 // Which side of the item we hover over will dictate
5190 // where the placeholder will appear, on the left or
5193 left
: dragPosition
< itemMidpoint
? itemPosition
.left
: itemPosition
.left
+ itemSize
,
5194 top
: itemPosition
.top
5197 // Calculate where the mouse is relative to the item height
5198 itemSize
= itemBoundingRect
.height
;
5199 itemMidpoint
= itemBoundingRect
.top
+ itemSize
/ 2;
5200 dragPosition
= clientY
;
5201 // Which side of the item we hover over will dictate
5202 // where the placeholder will appear, on the top or
5205 top
: dragPosition
< itemMidpoint
? itemPosition
.top
: itemPosition
.top
+ itemSize
,
5206 left
: itemPosition
.left
5209 // Store whether we are before or after an item to rearrange
5210 // For horizontal layout, we need to account for RTL, as this is flipped
5211 if ( this.orientation
=== 'horizontal' && this.$element
.css( 'direction' ) === 'rtl' ) {
5212 this.sideInsertion
= dragPosition
< itemMidpoint
? 'after' : 'before';
5214 this.sideInsertion
= dragPosition
< itemMidpoint
? 'before' : 'after';
5216 // Add drop indicator between objects
5219 .removeClass( 'oo-ui-element-hidden' );
5221 // This means the item was dragged outside the widget
5224 .addClass( 'oo-ui-element-hidden' );
5231 * Set a dragged item
5233 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5235 OO
.ui
.mixin
.DraggableGroupElement
.prototype.setDragItem = function ( item
) {
5236 this.dragItem
= item
;
5240 * Unset the current dragged item
5242 OO
.ui
.mixin
.DraggableGroupElement
.prototype.unsetDragItem = function () {
5243 this.dragItem
= null;
5244 this.itemDragOver
= null;
5245 this.$placeholder
.addClass( 'oo-ui-element-hidden' );
5246 this.sideInsertion
= '';
5250 * Get the item that is currently being dragged.
5252 * @return {OO.ui.mixin.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
5254 OO
.ui
.mixin
.DraggableGroupElement
.prototype.getDragItem = function () {
5255 return this.dragItem
;
5259 * Check if an item in the group is currently being dragged.
5261 * @return {Boolean} Item is being dragged
5263 OO
.ui
.mixin
.DraggableGroupElement
.prototype.isDragging = function () {
5264 return this.getDragItem() !== null;
5268 * IconElement is often mixed into other classes to generate an icon.
5269 * Icons are graphics, about the size of normal text. They are used to aid the user
5270 * in locating a control or to convey information in a space-efficient way. See the
5271 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
5272 * included in the library.
5274 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5280 * @param {Object} [config] Configuration options
5281 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
5282 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
5283 * the icon element be set to an existing icon instead of the one generated by this class, set a
5284 * value using a jQuery selection. For example:
5286 * // Use a <div> tag instead of a <span>
5288 * // Use an existing icon element instead of the one generated by the class
5289 * $icon: this.$element
5290 * // Use an icon element from a child widget
5291 * $icon: this.childwidget.$element
5292 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
5293 * symbolic names. A map is used for i18n purposes and contains a `default` icon
5294 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
5295 * by the user's language.
5297 * Example of an i18n map:
5299 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5300 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
5301 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5302 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
5303 * text. The icon title is displayed when users move the mouse over the icon.
5305 OO
.ui
.mixin
.IconElement
= function OoUiMixinIconElement( config
) {
5306 // Configuration initialization
5307 config
= config
|| {};
5312 this.iconTitle
= null;
5315 this.setIcon( config
.icon
|| this.constructor.static.icon
);
5316 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
5317 this.setIconElement( config
.$icon
|| $( '<span>' ) );
5322 OO
.initClass( OO
.ui
.mixin
.IconElement
);
5324 /* Static Properties */
5327 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
5328 * for i18n purposes and contains a `default` icon name and additional names keyed by
5329 * language code. The `default` name is used when no icon is keyed by the user's language.
5331 * Example of an i18n map:
5333 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5335 * Note: the static property will be overridden if the #icon configuration is used.
5339 * @property {Object|string}
5341 OO
.ui
.mixin
.IconElement
.static.icon
= null;
5344 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
5345 * function that returns title text, or `null` for no title.
5347 * The static property will be overridden if the #iconTitle configuration is used.
5351 * @property {string|Function|null}
5353 OO
.ui
.mixin
.IconElement
.static.iconTitle
= null;
5358 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
5359 * applies to the specified icon element instead of the one created by the class. If an icon
5360 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
5361 * and mixin methods will no longer affect the element.
5363 * @param {jQuery} $icon Element to use as icon
5365 OO
.ui
.mixin
.IconElement
.prototype.setIconElement = function ( $icon
) {
5368 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
5369 .removeAttr( 'title' );
5373 .addClass( 'oo-ui-iconElement-icon' )
5374 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
5375 if ( this.iconTitle
!== null ) {
5376 this.$icon
.attr( 'title', this.iconTitle
);
5379 this.updateThemeClasses();
5383 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
5384 * The icon parameter can also be set to a map of icon names. See the #icon config setting
5387 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
5388 * by language code, or `null` to remove the icon.
5391 OO
.ui
.mixin
.IconElement
.prototype.setIcon = function ( icon
) {
5392 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
5393 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
5395 if ( this.icon
!== icon
) {
5397 if ( this.icon
!== null ) {
5398 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
5400 if ( icon
!== null ) {
5401 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
5407 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
5408 this.updateThemeClasses();
5414 * Set the icon title. Use `null` to remove the title.
5416 * @param {string|Function|null} iconTitle A text string used as the icon title,
5417 * a function that returns title text, or `null` for no title.
5420 OO
.ui
.mixin
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
5421 iconTitle
= typeof iconTitle
=== 'function' ||
5422 ( typeof iconTitle
=== 'string' && iconTitle
.length
) ?
5423 OO
.ui
.resolveMsg( iconTitle
) : null;
5425 if ( this.iconTitle
!== iconTitle
) {
5426 this.iconTitle
= iconTitle
;
5428 if ( this.iconTitle
!== null ) {
5429 this.$icon
.attr( 'title', iconTitle
);
5431 this.$icon
.removeAttr( 'title' );
5440 * Get the symbolic name of the icon.
5442 * @return {string} Icon name
5444 OO
.ui
.mixin
.IconElement
.prototype.getIcon = function () {
5449 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5451 * @return {string} Icon title text
5453 OO
.ui
.mixin
.IconElement
.prototype.getIconTitle = function () {
5454 return this.iconTitle
;
5458 * IndicatorElement is often mixed into other classes to generate an indicator.
5459 * Indicators are small graphics that are generally used in two ways:
5461 * - To draw attention to the status of an item. For example, an indicator might be
5462 * used to show that an item in a list has errors that need to be resolved.
5463 * - To clarify the function of a control that acts in an exceptional way (a button
5464 * that opens a menu instead of performing an action directly, for example).
5466 * For a list of indicators included in the library, please see the
5467 * [OOjs UI documentation on MediaWiki] [1].
5469 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5475 * @param {Object} [config] Configuration options
5476 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5477 * configuration is omitted, the indicator element will use a generated `<span>`.
5478 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5479 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5481 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5482 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5483 * or a function that returns title text. The indicator title is displayed when users move
5484 * the mouse over the indicator.
5486 OO
.ui
.mixin
.IndicatorElement
= function OoUiMixinIndicatorElement( config
) {
5487 // Configuration initialization
5488 config
= config
|| {};
5491 this.$indicator
= null;
5492 this.indicator
= null;
5493 this.indicatorTitle
= null;
5496 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
5497 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
5498 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
5503 OO
.initClass( OO
.ui
.mixin
.IndicatorElement
);
5505 /* Static Properties */
5508 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5509 * The static property will be overridden if the #indicator configuration is used.
5513 * @property {string|null}
5515 OO
.ui
.mixin
.IndicatorElement
.static.indicator
= null;
5518 * A text string used as the indicator title, a function that returns title text, or `null`
5519 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5523 * @property {string|Function|null}
5525 OO
.ui
.mixin
.IndicatorElement
.static.indicatorTitle
= null;
5530 * Set the indicator element.
5532 * If an element is already set, it will be cleaned up before setting up the new element.
5534 * @param {jQuery} $indicator Element to use as indicator
5536 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
5537 if ( this.$indicator
) {
5539 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
5540 .removeAttr( 'title' );
5543 this.$indicator
= $indicator
5544 .addClass( 'oo-ui-indicatorElement-indicator' )
5545 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
5546 if ( this.indicatorTitle
!== null ) {
5547 this.$indicator
.attr( 'title', this.indicatorTitle
);
5550 this.updateThemeClasses();
5554 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5556 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5559 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
5560 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
5562 if ( this.indicator
!== indicator
) {
5563 if ( this.$indicator
) {
5564 if ( this.indicator
!== null ) {
5565 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
5567 if ( indicator
!== null ) {
5568 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
5571 this.indicator
= indicator
;
5574 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
5575 this.updateThemeClasses();
5581 * Set the indicator title.
5583 * The title is displayed when a user moves the mouse over the indicator.
5585 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5586 * `null` for no indicator title
5589 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorTitle = function ( indicatorTitle
) {
5590 indicatorTitle
= typeof indicatorTitle
=== 'function' ||
5591 ( typeof indicatorTitle
=== 'string' && indicatorTitle
.length
) ?
5592 OO
.ui
.resolveMsg( indicatorTitle
) : null;
5594 if ( this.indicatorTitle
!== indicatorTitle
) {
5595 this.indicatorTitle
= indicatorTitle
;
5596 if ( this.$indicator
) {
5597 if ( this.indicatorTitle
!== null ) {
5598 this.$indicator
.attr( 'title', indicatorTitle
);
5600 this.$indicator
.removeAttr( 'title' );
5609 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5611 * @return {string} Symbolic name of indicator
5613 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicator = function () {
5614 return this.indicator
;
5618 * Get the indicator title.
5620 * The title is displayed when a user moves the mouse over the indicator.
5622 * @return {string} Indicator title text
5624 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicatorTitle = function () {
5625 return this.indicatorTitle
;
5629 * LabelElement is often mixed into other classes to generate a label, which
5630 * helps identify the function of an interface element.
5631 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5633 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5639 * @param {Object} [config] Configuration options
5640 * @cfg {jQuery} [$label] The label element created by the class. If this
5641 * configuration is omitted, the label element will use a generated `<span>`.
5642 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
5643 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
5644 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
5645 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5646 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5647 * The label will be truncated to fit if necessary.
5649 OO
.ui
.mixin
.LabelElement
= function OoUiMixinLabelElement( config
) {
5650 // Configuration initialization
5651 config
= config
|| {};
5656 this.autoFitLabel
= config
.autoFitLabel
=== undefined || !!config
.autoFitLabel
;
5659 this.setLabel( config
.label
|| this.constructor.static.label
);
5660 this.setLabelElement( config
.$label
|| $( '<span>' ) );
5665 OO
.initClass( OO
.ui
.mixin
.LabelElement
);
5670 * @event labelChange
5671 * @param {string} value
5674 /* Static Properties */
5677 * The label text. The label can be specified as a plaintext string, a function that will
5678 * produce a string in the future, or `null` for no label. The static value will
5679 * be overridden if a label is specified with the #label config option.
5683 * @property {string|Function|null}
5685 OO
.ui
.mixin
.LabelElement
.static.label
= null;
5690 * Set the label element.
5692 * If an element is already set, it will be cleaned up before setting up the new element.
5694 * @param {jQuery} $label Element to use as label
5696 OO
.ui
.mixin
.LabelElement
.prototype.setLabelElement = function ( $label
) {
5697 if ( this.$label
) {
5698 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
5701 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
5702 this.setLabelContent( this.label
);
5708 * An empty string will result in the label being hidden. A string containing only whitespace will
5709 * be converted to a single ` `.
5711 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
5712 * text; or null for no label
5715 OO
.ui
.mixin
.LabelElement
.prototype.setLabel = function ( label
) {
5716 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
5717 label
= ( ( typeof label
=== 'string' && label
.length
) || label
instanceof jQuery
|| label
instanceof OO
.ui
.HtmlSnippet
) ? label
: null;
5719 this.$element
.toggleClass( 'oo-ui-labelElement', !!label
);
5721 if ( this.label
!== label
) {
5722 if ( this.$label
) {
5723 this.setLabelContent( label
);
5726 this.emit( 'labelChange' );
5735 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
5736 * text; or null for no label
5738 OO
.ui
.mixin
.LabelElement
.prototype.getLabel = function () {
5747 OO
.ui
.mixin
.LabelElement
.prototype.fitLabel = function () {
5748 if ( this.$label
&& this.$label
.autoEllipsis
&& this.autoFitLabel
) {
5749 this.$label
.autoEllipsis( { hasSpan
: false, tooltip
: true } );
5756 * Set the content of the label.
5758 * Do not call this method until after the label element has been set by #setLabelElement.
5761 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5762 * text; or null for no label
5764 OO
.ui
.mixin
.LabelElement
.prototype.setLabelContent = function ( label
) {
5765 if ( typeof label
=== 'string' ) {
5766 if ( label
.match( /^\s*$/ ) ) {
5767 // Convert whitespace only string to a single non-breaking space
5768 this.$label
.html( ' ' );
5770 this.$label
.text( label
);
5772 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
5773 this.$label
.html( label
.toString() );
5774 } else if ( label
instanceof jQuery
) {
5775 this.$label
.empty().append( label
);
5777 this.$label
.empty();
5782 * LookupElement is a mixin that creates a {@link OO.ui.FloatingMenuSelectWidget menu} of suggested values for
5783 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
5784 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
5785 * from the lookup menu, that value becomes the value of the input field.
5787 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
5788 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
5789 * re-enable lookups.
5791 * See the [OOjs UI demos][1] for an example.
5793 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
5799 * @param {Object} [config] Configuration options
5800 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
5801 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
5802 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
5803 * By default, the lookup menu is not generated and displayed until the user begins to type.
5805 OO
.ui
.mixin
.LookupElement
= function OoUiMixinLookupElement( config
) {
5806 // Configuration initialization
5807 config
= config
|| {};
5810 this.$overlay
= config
.$overlay
|| this.$element
;
5811 this.lookupMenu
= new OO
.ui
.FloatingMenuSelectWidget( {
5814 $container
: config
.$container
|| this.$element
5817 this.allowSuggestionsWhenEmpty
= config
.allowSuggestionsWhenEmpty
|| false;
5819 this.lookupCache
= {};
5820 this.lookupQuery
= null;
5821 this.lookupRequest
= null;
5822 this.lookupsDisabled
= false;
5823 this.lookupInputFocused
= false;
5827 focus
: this.onLookupInputFocus
.bind( this ),
5828 blur
: this.onLookupInputBlur
.bind( this ),
5829 mousedown
: this.onLookupInputMouseDown
.bind( this )
5831 this.connect( this, { change
: 'onLookupInputChange' } );
5832 this.lookupMenu
.connect( this, {
5833 toggle
: 'onLookupMenuToggle',
5834 choose
: 'onLookupMenuItemChoose'
5838 this.$element
.addClass( 'oo-ui-lookupElement' );
5839 this.lookupMenu
.$element
.addClass( 'oo-ui-lookupElement-menu' );
5840 this.$overlay
.append( this.lookupMenu
.$element
);
5846 * Handle input focus event.
5849 * @param {jQuery.Event} e Input focus event
5851 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputFocus = function () {
5852 this.lookupInputFocused
= true;
5853 this.populateLookupMenu();
5857 * Handle input blur event.
5860 * @param {jQuery.Event} e Input blur event
5862 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputBlur = function () {
5863 this.closeLookupMenu();
5864 this.lookupInputFocused
= false;
5868 * Handle input mouse down event.
5871 * @param {jQuery.Event} e Input mouse down event
5873 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputMouseDown = function () {
5874 // Only open the menu if the input was already focused.
5875 // This way we allow the user to open the menu again after closing it with Esc
5876 // by clicking in the input. Opening (and populating) the menu when initially
5877 // clicking into the input is handled by the focus handler.
5878 if ( this.lookupInputFocused
&& !this.lookupMenu
.isVisible() ) {
5879 this.populateLookupMenu();
5884 * Handle input change event.
5887 * @param {string} value New input value
5889 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputChange = function () {
5890 if ( this.lookupInputFocused
) {
5891 this.populateLookupMenu();
5896 * Handle the lookup menu being shown/hidden.
5899 * @param {boolean} visible Whether the lookup menu is now visible.
5901 OO
.ui
.mixin
.LookupElement
.prototype.onLookupMenuToggle = function ( visible
) {
5903 // When the menu is hidden, abort any active request and clear the menu.
5904 // This has to be done here in addition to closeLookupMenu(), because
5905 // MenuSelectWidget will close itself when the user presses Esc.
5906 this.abortLookupRequest();
5907 this.lookupMenu
.clearItems();
5912 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
5915 * @param {OO.ui.MenuOptionWidget} item Selected item
5917 OO
.ui
.mixin
.LookupElement
.prototype.onLookupMenuItemChoose = function ( item
) {
5918 this.setValue( item
.getData() );
5925 * @return {OO.ui.FloatingMenuSelectWidget}
5927 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenu = function () {
5928 return this.lookupMenu
;
5932 * Disable or re-enable lookups.
5934 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
5936 * @param {boolean} disabled Disable lookups
5938 OO
.ui
.mixin
.LookupElement
.prototype.setLookupsDisabled = function ( disabled
) {
5939 this.lookupsDisabled
= !!disabled
;
5943 * Open the menu. If there are no entries in the menu, this does nothing.
5948 OO
.ui
.mixin
.LookupElement
.prototype.openLookupMenu = function () {
5949 if ( !this.lookupMenu
.isEmpty() ) {
5950 this.lookupMenu
.toggle( true );
5956 * Close the menu, empty it, and abort any pending request.
5961 OO
.ui
.mixin
.LookupElement
.prototype.closeLookupMenu = function () {
5962 this.lookupMenu
.toggle( false );
5963 this.abortLookupRequest();
5964 this.lookupMenu
.clearItems();
5969 * Request menu items based on the input's current value, and when they arrive,
5970 * populate the menu with these items and show the menu.
5972 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
5977 OO
.ui
.mixin
.LookupElement
.prototype.populateLookupMenu = function () {
5979 value
= this.getValue();
5981 if ( this.lookupsDisabled
|| this.isReadOnly() ) {
5985 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
5986 if ( !this.allowSuggestionsWhenEmpty
&& value
=== '' ) {
5987 this.closeLookupMenu();
5988 // Skip population if there is already a request pending for the current value
5989 } else if ( value
!== this.lookupQuery
) {
5990 this.getLookupMenuItems()
5991 .done( function ( items
) {
5992 widget
.lookupMenu
.clearItems();
5993 if ( items
.length
) {
5997 widget
.initializeLookupMenuSelection();
5999 widget
.lookupMenu
.toggle( false );
6002 .fail( function () {
6003 widget
.lookupMenu
.clearItems();
6011 * Highlight the first selectable item in the menu.
6016 OO
.ui
.mixin
.LookupElement
.prototype.initializeLookupMenuSelection = function () {
6017 if ( !this.lookupMenu
.getSelectedItem() ) {
6018 this.lookupMenu
.highlightItem( this.lookupMenu
.getFirstSelectableItem() );
6023 * Get lookup menu items for the current query.
6026 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
6027 * the done event. If the request was aborted to make way for a subsequent request, this promise
6028 * will not be rejected: it will remain pending forever.
6030 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenuItems = function () {
6032 value
= this.getValue(),
6033 deferred
= $.Deferred(),
6036 this.abortLookupRequest();
6037 if ( Object
.prototype.hasOwnProperty
.call( this.lookupCache
, value
) ) {
6038 deferred
.resolve( this.getLookupMenuOptionsFromData( this.lookupCache
[ value
] ) );
6041 this.lookupQuery
= value
;
6042 ourRequest
= this.lookupRequest
= this.getLookupRequest();
6044 .always( function () {
6045 // We need to pop pending even if this is an old request, otherwise
6046 // the widget will remain pending forever.
6047 // TODO: this assumes that an aborted request will fail or succeed soon after
6048 // being aborted, or at least eventually. It would be nice if we could popPending()
6049 // at abort time, but only if we knew that we hadn't already called popPending()
6050 // for that request.
6051 widget
.popPending();
6053 .done( function ( response
) {
6054 // If this is an old request (and aborting it somehow caused it to still succeed),
6055 // ignore its success completely
6056 if ( ourRequest
=== widget
.lookupRequest
) {
6057 widget
.lookupQuery
= null;
6058 widget
.lookupRequest
= null;
6059 widget
.lookupCache
[ value
] = widget
.getLookupCacheDataFromResponse( response
);
6060 deferred
.resolve( widget
.getLookupMenuOptionsFromData( widget
.lookupCache
[ value
] ) );
6063 .fail( function () {
6064 // If this is an old request (or a request failing because it's being aborted),
6065 // ignore its failure completely
6066 if ( ourRequest
=== widget
.lookupRequest
) {
6067 widget
.lookupQuery
= null;
6068 widget
.lookupRequest
= null;
6073 return deferred
.promise();
6077 * Abort the currently pending lookup request, if any.
6081 OO
.ui
.mixin
.LookupElement
.prototype.abortLookupRequest = function () {
6082 var oldRequest
= this.lookupRequest
;
6084 // First unset this.lookupRequest to the fail handler will notice
6085 // that the request is no longer current
6086 this.lookupRequest
= null;
6087 this.lookupQuery
= null;
6093 * Get a new request object of the current lookup query value.
6097 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
6099 OO
.ui
.mixin
.LookupElement
.prototype.getLookupRequest = function () {
6100 // Stub, implemented in subclass
6105 * Pre-process data returned by the request from #getLookupRequest.
6107 * The return value of this function will be cached, and any further queries for the given value
6108 * will use the cache rather than doing API requests.
6112 * @param {Mixed} response Response from server
6113 * @return {Mixed} Cached result data
6115 OO
.ui
.mixin
.LookupElement
.prototype.getLookupCacheDataFromResponse = function () {
6116 // Stub, implemented in subclass
6121 * Get a list of menu option widgets from the (possibly cached) data returned by
6122 * #getLookupCacheDataFromResponse.
6126 * @param {Mixed} data Cached result data, usually an array
6127 * @return {OO.ui.MenuOptionWidget[]} Menu items
6129 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenuOptionsFromData = function () {
6130 // Stub, implemented in subclass
6135 * Set the read-only state of the widget.
6137 * This will also disable/enable the lookups functionality.
6139 * @param {boolean} readOnly Make input read-only
6142 OO
.ui
.mixin
.LookupElement
.prototype.setReadOnly = function ( readOnly
) {
6144 // Note: Calling #setReadOnly this way assumes this is mixed into an OO.ui.TextInputWidget
6145 OO
.ui
.TextInputWidget
.prototype.setReadOnly
.call( this, readOnly
);
6147 // During construction, #setReadOnly is called before the OO.ui.mixin.LookupElement constructor
6148 if ( this.isReadOnly() && this.lookupMenu
) {
6149 this.closeLookupMenu();
6156 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
6157 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
6158 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
6159 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
6165 * @param {Object} [config] Configuration options
6166 * @cfg {Object} [popup] Configuration to pass to popup
6167 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
6169 OO
.ui
.mixin
.PopupElement
= function OoUiMixinPopupElement( config
) {
6170 // Configuration initialization
6171 config
= config
|| {};
6174 this.popup
= new OO
.ui
.PopupWidget( $.extend(
6175 { autoClose
: true },
6177 { $autoCloseIgnore
: this.$element
}
6186 * @return {OO.ui.PopupWidget} Popup widget
6188 OO
.ui
.mixin
.PopupElement
.prototype.getPopup = function () {
6193 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
6194 * additional functionality to an element created by another class. The class provides
6195 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
6196 * which are used to customize the look and feel of a widget to better describe its
6197 * importance and functionality.
6199 * The library currently contains the following styling flags for general use:
6201 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
6202 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
6203 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
6205 * The flags affect the appearance of the buttons:
6208 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
6209 * var button1 = new OO.ui.ButtonWidget( {
6210 * label: 'Constructive',
6211 * flags: 'constructive'
6213 * var button2 = new OO.ui.ButtonWidget( {
6214 * label: 'Destructive',
6215 * flags: 'destructive'
6217 * var button3 = new OO.ui.ButtonWidget( {
6218 * label: 'Progressive',
6219 * flags: 'progressive'
6221 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
6223 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
6224 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
6226 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6232 * @param {Object} [config] Configuration options
6233 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
6234 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
6235 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6236 * @cfg {jQuery} [$flagged] The flagged element. By default,
6237 * the flagged functionality is applied to the element created by the class ($element).
6238 * If a different element is specified, the flagged functionality will be applied to it instead.
6240 OO
.ui
.mixin
.FlaggedElement
= function OoUiMixinFlaggedElement( config
) {
6241 // Configuration initialization
6242 config
= config
|| {};
6246 this.$flagged
= null;
6249 this.setFlags( config
.flags
);
6250 this.setFlaggedElement( config
.$flagged
|| this.$element
);
6257 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
6258 * parameter contains the name of each modified flag and indicates whether it was
6261 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
6262 * that the flag was added, `false` that the flag was removed.
6268 * Set the flagged element.
6270 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
6271 * If an element is already set, the method will remove the mixin’s effect on that element.
6273 * @param {jQuery} $flagged Element that should be flagged
6275 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
6276 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
6277 return 'oo-ui-flaggedElement-' + flag
;
6280 if ( this.$flagged
) {
6281 this.$flagged
.removeClass( classNames
);
6284 this.$flagged
= $flagged
.addClass( classNames
);
6288 * Check if the specified flag is set.
6290 * @param {string} flag Name of flag
6291 * @return {boolean} The flag is set
6293 OO
.ui
.mixin
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
6294 // This may be called before the constructor, thus before this.flags is set
6295 return this.flags
&& ( flag
in this.flags
);
6299 * Get the names of all flags set.
6301 * @return {string[]} Flag names
6303 OO
.ui
.mixin
.FlaggedElement
.prototype.getFlags = function () {
6304 // This may be called before the constructor, thus before this.flags is set
6305 return Object
.keys( this.flags
|| {} );
6314 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags = function () {
6315 var flag
, className
,
6318 classPrefix
= 'oo-ui-flaggedElement-';
6320 for ( flag
in this.flags
) {
6321 className
= classPrefix
+ flag
;
6322 changes
[ flag
] = false;
6323 delete this.flags
[ flag
];
6324 remove
.push( className
);
6327 if ( this.$flagged
) {
6328 this.$flagged
.removeClass( remove
.join( ' ' ) );
6331 this.updateThemeClasses();
6332 this.emit( 'flag', changes
);
6338 * Add one or more flags.
6340 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
6341 * or an object keyed by flag name with a boolean value that indicates whether the flag should
6342 * be added (`true`) or removed (`false`).
6346 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags = function ( flags
) {
6347 var i
, len
, flag
, className
,
6351 classPrefix
= 'oo-ui-flaggedElement-';
6353 if ( typeof flags
=== 'string' ) {
6354 className
= classPrefix
+ flags
;
6356 if ( !this.flags
[ flags
] ) {
6357 this.flags
[ flags
] = true;
6358 add
.push( className
);
6360 } else if ( Array
.isArray( flags
) ) {
6361 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
6363 className
= classPrefix
+ flag
;
6365 if ( !this.flags
[ flag
] ) {
6366 changes
[ flag
] = true;
6367 this.flags
[ flag
] = true;
6368 add
.push( className
);
6371 } else if ( OO
.isPlainObject( flags
) ) {
6372 for ( flag
in flags
) {
6373 className
= classPrefix
+ flag
;
6374 if ( flags
[ flag
] ) {
6376 if ( !this.flags
[ flag
] ) {
6377 changes
[ flag
] = true;
6378 this.flags
[ flag
] = true;
6379 add
.push( className
);
6383 if ( this.flags
[ flag
] ) {
6384 changes
[ flag
] = false;
6385 delete this.flags
[ flag
];
6386 remove
.push( className
);
6392 if ( this.$flagged
) {
6394 .addClass( add
.join( ' ' ) )
6395 .removeClass( remove
.join( ' ' ) );
6398 this.updateThemeClasses();
6399 this.emit( 'flag', changes
);
6405 * TitledElement is mixed into other classes to provide a `title` attribute.
6406 * Titles are rendered by the browser and are made visible when the user moves
6407 * the mouse over the element. Titles are not visible on touch devices.
6410 * // TitledElement provides a 'title' attribute to the
6411 * // ButtonWidget class
6412 * var button = new OO.ui.ButtonWidget( {
6413 * label: 'Button with Title',
6414 * title: 'I am a button'
6416 * $( 'body' ).append( button.$element );
6422 * @param {Object} [config] Configuration options
6423 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
6424 * If this config is omitted, the title functionality is applied to $element, the
6425 * element created by the class.
6426 * @cfg {string|Function} [title] The title text or a function that returns text. If
6427 * this config is omitted, the value of the {@link #static-title static title} property is used.
6429 OO
.ui
.mixin
.TitledElement
= function OoUiMixinTitledElement( config
) {
6430 // Configuration initialization
6431 config
= config
|| {};
6434 this.$titled
= null;
6438 this.setTitle( config
.title
|| this.constructor.static.title
);
6439 this.setTitledElement( config
.$titled
|| this.$element
);
6444 OO
.initClass( OO
.ui
.mixin
.TitledElement
);
6446 /* Static Properties */
6449 * The title text, a function that returns text, or `null` for no title. The value of the static property
6450 * is overridden if the #title config option is used.
6454 * @property {string|Function|null}
6456 OO
.ui
.mixin
.TitledElement
.static.title
= null;
6461 * Set the titled element.
6463 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6464 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6466 * @param {jQuery} $titled Element that should use the 'titled' functionality
6468 OO
.ui
.mixin
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
6469 if ( this.$titled
) {
6470 this.$titled
.removeAttr( 'title' );
6473 this.$titled
= $titled
;
6475 this.$titled
.attr( 'title', this.title
);
6482 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6485 OO
.ui
.mixin
.TitledElement
.prototype.setTitle = function ( title
) {
6486 title
= typeof title
=== 'string' ? OO
.ui
.resolveMsg( title
) : null;
6488 if ( this.title
!== title
) {
6489 if ( this.$titled
) {
6490 if ( title
!== null ) {
6491 this.$titled
.attr( 'title', title
);
6493 this.$titled
.removeAttr( 'title' );
6505 * @return {string} Title string
6507 OO
.ui
.mixin
.TitledElement
.prototype.getTitle = function () {
6512 * Element that can be automatically clipped to visible boundaries.
6514 * Whenever the element's natural height changes, you have to call
6515 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
6516 * clipping correctly.
6518 * The dimensions of #$clippableContainer will be compared to the boundaries of the
6519 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
6520 * then #$clippable will be given a fixed reduced height and/or width and will be made
6521 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
6522 * but you can build a static footer by setting #$clippableContainer to an element that contains
6523 * #$clippable and the footer.
6529 * @param {Object} [config] Configuration options
6530 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
6531 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
6532 * omit to use #$clippable
6534 OO
.ui
.mixin
.ClippableElement
= function OoUiMixinClippableElement( config
) {
6535 // Configuration initialization
6536 config
= config
|| {};
6539 this.$clippable
= null;
6540 this.$clippableContainer
= null;
6541 this.clipping
= false;
6542 this.clippedHorizontally
= false;
6543 this.clippedVertically
= false;
6544 this.$clippableScrollableContainer
= null;
6545 this.$clippableScroller
= null;
6546 this.$clippableWindow
= null;
6547 this.idealWidth
= null;
6548 this.idealHeight
= null;
6549 this.onClippableScrollHandler
= this.clip
.bind( this );
6550 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
6553 if ( config
.$clippableContainer
) {
6554 this.setClippableContainer( config
.$clippableContainer
);
6556 this.setClippableElement( config
.$clippable
|| this.$element
);
6562 * Set clippable element.
6564 * If an element is already set, it will be cleaned up before setting up the new element.
6566 * @param {jQuery} $clippable Element to make clippable
6568 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
6569 if ( this.$clippable
) {
6570 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
6571 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
6572 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6575 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
6580 * Set clippable container.
6582 * This is the container that will be measured when deciding whether to clip. When clipping,
6583 * #$clippable will be resized in order to keep the clippable container fully visible.
6585 * If the clippable container is unset, #$clippable will be used.
6587 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
6589 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableContainer = function ( $clippableContainer
) {
6590 this.$clippableContainer
= $clippableContainer
;
6591 if ( this.$clippable
) {
6599 * Do not turn clipping on until after the element is attached to the DOM and visible.
6601 * @param {boolean} [clipping] Enable clipping, omit to toggle
6604 OO
.ui
.mixin
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
6605 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
6607 if ( this.clipping
!== clipping
) {
6608 this.clipping
= clipping
;
6610 this.$clippableScrollableContainer
= $( this.getClosestScrollableElementContainer() );
6611 // If the clippable container is the root, we have to listen to scroll events and check
6612 // jQuery.scrollTop on the window because of browser inconsistencies
6613 this.$clippableScroller
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
6614 $( OO
.ui
.Element
.static.getWindow( this.$clippableScrollableContainer
) ) :
6615 this.$clippableScrollableContainer
;
6616 this.$clippableScroller
.on( 'scroll', this.onClippableScrollHandler
);
6617 this.$clippableWindow
= $( this.getElementWindow() )
6618 .on( 'resize', this.onClippableWindowResizeHandler
);
6619 // Initial clip after visible
6622 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
6623 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6625 this.$clippableScrollableContainer
= null;
6626 this.$clippableScroller
.off( 'scroll', this.onClippableScrollHandler
);
6627 this.$clippableScroller
= null;
6628 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
6629 this.$clippableWindow
= null;
6637 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6639 * @return {boolean} Element will be clipped to the visible area
6641 OO
.ui
.mixin
.ClippableElement
.prototype.isClipping = function () {
6642 return this.clipping
;
6646 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6648 * @return {boolean} Part of the element is being clipped
6650 OO
.ui
.mixin
.ClippableElement
.prototype.isClipped = function () {
6651 return this.clippedHorizontally
|| this.clippedVertically
;
6655 * Check if the right of the element is being clipped by the nearest scrollable container.
6657 * @return {boolean} Part of the element is being clipped
6659 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedHorizontally = function () {
6660 return this.clippedHorizontally
;
6664 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6666 * @return {boolean} Part of the element is being clipped
6668 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedVertically = function () {
6669 return this.clippedVertically
;
6673 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6675 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6676 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6678 OO
.ui
.mixin
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
6679 this.idealWidth
= width
;
6680 this.idealHeight
= height
;
6682 if ( !this.clipping
) {
6683 // Update dimensions
6684 this.$clippable
.css( { width
: width
, height
: height
} );
6686 // While clipping, idealWidth and idealHeight are not considered
6690 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6691 * the element's natural height changes.
6693 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6694 * overlapped by, the visible area of the nearest scrollable container.
6698 OO
.ui
.mixin
.ClippableElement
.prototype.clip = function () {
6699 var $container
, extraHeight
, extraWidth
, ccOffset
,
6700 $scrollableContainer
, scOffset
, scHeight
, scWidth
,
6701 ccWidth
, scrollerIsWindow
, scrollTop
, scrollLeft
,
6702 desiredWidth
, desiredHeight
, allotedWidth
, allotedHeight
,
6703 naturalWidth
, naturalHeight
, clipWidth
, clipHeight
,
6704 buffer
= 7; // Chosen by fair dice roll
6706 if ( !this.clipping
) {
6707 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
6711 $container
= this.$clippableContainer
|| this.$clippable
;
6712 extraHeight
= $container
.outerHeight() - this.$clippable
.outerHeight();
6713 extraWidth
= $container
.outerWidth() - this.$clippable
.outerWidth();
6714 ccOffset
= $container
.offset();
6715 $scrollableContainer
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
6716 this.$clippableWindow
: this.$clippableScrollableContainer
;
6717 scOffset
= $scrollableContainer
.offset() || { top
: 0, left
: 0 };
6718 scHeight
= $scrollableContainer
.innerHeight() - buffer
;
6719 scWidth
= $scrollableContainer
.innerWidth() - buffer
;
6720 ccWidth
= $container
.outerWidth() + buffer
;
6721 scrollerIsWindow
= this.$clippableScroller
[ 0 ] === this.$clippableWindow
[ 0 ];
6722 scrollTop
= scrollerIsWindow
? this.$clippableScroller
.scrollTop() : 0;
6723 scrollLeft
= scrollerIsWindow
? this.$clippableScroller
.scrollLeft() : 0;
6724 desiredWidth
= ccOffset
.left
< 0 ?
6725 ccWidth
+ ccOffset
.left
:
6726 ( scOffset
.left
+ scrollLeft
+ scWidth
) - ccOffset
.left
;
6727 desiredHeight
= ( scOffset
.top
+ scrollTop
+ scHeight
) - ccOffset
.top
;
6728 allotedWidth
= desiredWidth
- extraWidth
;
6729 allotedHeight
= desiredHeight
- extraHeight
;
6730 naturalWidth
= this.$clippable
.prop( 'scrollWidth' );
6731 naturalHeight
= this.$clippable
.prop( 'scrollHeight' );
6732 clipWidth
= allotedWidth
< naturalWidth
;
6733 clipHeight
= allotedHeight
< naturalHeight
;
6736 this.$clippable
.css( { overflowX
: 'scroll', width
: Math
.max( 0, allotedWidth
) } );
6738 this.$clippable
.css( { width
: this.idealWidth
? this.idealWidth
- extraWidth
: '', overflowX
: '' } );
6741 this.$clippable
.css( { overflowY
: 'scroll', height
: Math
.max( 0, allotedHeight
) } );
6743 this.$clippable
.css( { height
: this.idealHeight
? this.idealHeight
- extraHeight
: '', overflowY
: '' } );
6746 // If we stopped clipping in at least one of the dimensions
6747 if ( ( this.clippedHorizontally
&& !clipWidth
) || ( this.clippedVertically
&& !clipHeight
) ) {
6748 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6751 this.clippedHorizontally
= clipWidth
;
6752 this.clippedVertically
= clipHeight
;
6758 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
6759 * Accesskeys allow an user to go to a specific element by using
6760 * a shortcut combination of a browser specific keys + the key
6764 * // AccessKeyedElement provides an 'accesskey' attribute to the
6765 * // ButtonWidget class
6766 * var button = new OO.ui.ButtonWidget( {
6767 * label: 'Button with Accesskey',
6770 * $( 'body' ).append( button.$element );
6776 * @param {Object} [config] Configuration options
6777 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
6778 * If this config is omitted, the accesskey functionality is applied to $element, the
6779 * element created by the class.
6780 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
6781 * this config is omitted, no accesskey will be added.
6783 OO
.ui
.mixin
.AccessKeyedElement
= function OoUiMixinAccessKeyedElement( config
) {
6784 // Configuration initialization
6785 config
= config
|| {};
6788 this.$accessKeyed
= null;
6789 this.accessKey
= null;
6792 this.setAccessKey( config
.accessKey
|| null );
6793 this.setAccessKeyedElement( config
.$accessKeyed
|| this.$element
);
6798 OO
.initClass( OO
.ui
.mixin
.AccessKeyedElement
);
6800 /* Static Properties */
6803 * The access key, a function that returns a key, or `null` for no accesskey.
6807 * @property {string|Function|null}
6809 OO
.ui
.mixin
.AccessKeyedElement
.static.accessKey
= null;
6814 * Set the accesskeyed element.
6816 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
6817 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
6819 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
6821 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKeyedElement = function ( $accessKeyed
) {
6822 if ( this.$accessKeyed
) {
6823 this.$accessKeyed
.removeAttr( 'accesskey' );
6826 this.$accessKeyed
= $accessKeyed
;
6827 if ( this.accessKey
) {
6828 this.$accessKeyed
.attr( 'accesskey', this.accessKey
);
6835 * @param {string|Function|null} accesskey Key, a function that returns a key, or `null` for no accesskey
6838 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKey = function ( accessKey
) {
6839 accessKey
= typeof accessKey
=== 'string' ? OO
.ui
.resolveMsg( accessKey
) : null;
6841 if ( this.accessKey
!== accessKey
) {
6842 if ( this.$accessKeyed
) {
6843 if ( accessKey
!== null ) {
6844 this.$accessKeyed
.attr( 'accesskey', accessKey
);
6846 this.$accessKeyed
.removeAttr( 'accesskey' );
6849 this.accessKey
= accessKey
;
6858 * @return {string} accessKey string
6860 OO
.ui
.mixin
.AccessKeyedElement
.prototype.getAccessKey = function () {
6861 return this.accessKey
;
6865 * Tools, together with {@link OO.ui.ToolGroup toolgroups}, constitute {@link OO.ui.Toolbar toolbars}.
6866 * Each tool is configured with a static name, title, and icon and is customized with the command to carry
6867 * out when the tool is selected. Tools must also be registered with a {@link OO.ui.ToolFactory tool factory},
6868 * which creates the tools on demand.
6870 * Tools are added to toolgroups ({@link OO.ui.ListToolGroup ListToolGroup},
6871 * {@link OO.ui.BarToolGroup BarToolGroup}, or {@link OO.ui.MenuToolGroup MenuToolGroup}), which determine how
6872 * the tool is displayed in the toolbar. See {@link OO.ui.Toolbar toolbars} for an example.
6874 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
6875 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
6879 * @extends OO.ui.Widget
6880 * @mixins OO.ui.mixin.IconElement
6881 * @mixins OO.ui.mixin.FlaggedElement
6882 * @mixins OO.ui.mixin.TabIndexedElement
6885 * @param {OO.ui.ToolGroup} toolGroup
6886 * @param {Object} [config] Configuration options
6887 * @cfg {string|Function} [title] Title text or a function that returns text. If this config is omitted, the value of
6888 * the {@link #static-title static title} property is used.
6890 * The title is used in different ways depending on the type of toolgroup that contains the tool. The
6891 * title is used as a tooltip if the tool is part of a {@link OO.ui.BarToolGroup bar} toolgroup, or as the label text if the tool is
6892 * part of a {@link OO.ui.ListToolGroup list} or {@link OO.ui.MenuToolGroup menu} toolgroup.
6894 * For bar toolgroups, a description of the accelerator key is appended to the title if an accelerator key
6895 * is associated with an action by the same name as the tool and accelerator functionality has been added to the application.
6896 * To add accelerator key functionality, you must subclass OO.ui.Toolbar and override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method.
6898 OO
.ui
.Tool
= function OoUiTool( toolGroup
, config
) {
6899 // Allow passing positional parameters inside the config object
6900 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
6902 toolGroup
= config
.toolGroup
;
6905 // Configuration initialization
6906 config
= config
|| {};
6908 // Parent constructor
6909 OO
.ui
.Tool
.parent
.call( this, config
);
6912 this.toolGroup
= toolGroup
;
6913 this.toolbar
= this.toolGroup
.getToolbar();
6914 this.active
= false;
6915 this.$title
= $( '<span>' );
6916 this.$accel
= $( '<span>' );
6917 this.$link
= $( '<a>' );
6920 // Mixin constructors
6921 OO
.ui
.mixin
.IconElement
.call( this, config
);
6922 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
6923 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$link
} ) );
6926 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
6929 this.$title
.addClass( 'oo-ui-tool-title' );
6931 .addClass( 'oo-ui-tool-accel' )
6933 // This may need to be changed if the key names are ever localized,
6934 // but for now they are essentially written in English
6939 .addClass( 'oo-ui-tool-link' )
6940 .append( this.$icon
, this.$title
, this.$accel
)
6941 .attr( 'role', 'button' );
6943 .data( 'oo-ui-tool', this )
6945 'oo-ui-tool ' + 'oo-ui-tool-name-' +
6946 this.constructor.static.name
.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
6948 .toggleClass( 'oo-ui-tool-with-label', this.constructor.static.displayBothIconAndLabel
)
6949 .append( this.$link
);
6950 this.setTitle( config
.title
|| this.constructor.static.title
);
6955 OO
.inheritClass( OO
.ui
.Tool
, OO
.ui
.Widget
);
6956 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.IconElement
);
6957 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.FlaggedElement
);
6958 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.TabIndexedElement
);
6960 /* Static Properties */
6966 OO
.ui
.Tool
.static.tagName
= 'span';
6969 * Symbolic name of tool.
6971 * The symbolic name is used internally to register the tool with a {@link OO.ui.ToolFactory ToolFactory}. It can
6972 * also be used when adding tools to toolgroups.
6977 * @property {string}
6979 OO
.ui
.Tool
.static.name
= '';
6982 * Symbolic name of the group.
6984 * The group name is used to associate tools with each other so that they can be selected later by
6985 * a {@link OO.ui.ToolGroup toolgroup}.
6990 * @property {string}
6992 OO
.ui
.Tool
.static.group
= '';
6995 * Tool title text or a function that returns title text. The value of the static property is overridden if the #title config option is used.
7000 * @property {string|Function}
7002 OO
.ui
.Tool
.static.title
= '';
7005 * Display both icon and label when the tool is used in a {@link OO.ui.BarToolGroup bar} toolgroup.
7006 * Normally only the icon is displayed, or only the label if no icon is given.
7010 * @property {boolean}
7012 OO
.ui
.Tool
.static.displayBothIconAndLabel
= false;
7015 * Add tool to catch-all groups automatically.
7017 * A catch-all group, which contains all tools that do not currently belong to a toolgroup,
7018 * can be included in a toolgroup using the wildcard selector, an asterisk (*).
7022 * @property {boolean}
7024 OO
.ui
.Tool
.static.autoAddToCatchall
= true;
7027 * Add tool to named groups automatically.
7029 * By default, tools that are configured with a static ‘group’ property are added
7030 * to that group and will be selected when the symbolic name of the group is specified (e.g., when
7031 * toolgroups include tools by group name).
7034 * @property {boolean}
7037 OO
.ui
.Tool
.static.autoAddToGroup
= true;
7040 * Check if this tool is compatible with given data.
7042 * This is a stub that can be overriden to provide support for filtering tools based on an
7043 * arbitrary piece of information (e.g., where the cursor is in a document). The implementation
7044 * must also call this method so that the compatibility check can be performed.
7048 * @param {Mixed} data Data to check
7049 * @return {boolean} Tool can be used with data
7051 OO
.ui
.Tool
.static.isCompatibleWith = function () {
7058 * Handle the toolbar state being updated.
7060 * This is an abstract method that must be overridden in a concrete subclass.
7065 OO
.ui
.Tool
.prototype.onUpdateState = function () {
7067 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
7072 * Handle the tool being selected.
7074 * This is an abstract method that must be overridden in a concrete subclass.
7079 OO
.ui
.Tool
.prototype.onSelect = function () {
7081 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
7086 * Check if the tool is active.
7088 * Tools become active when their #onSelect or #onUpdateState handlers change them to appear pressed
7089 * with the #setActive method. Additional CSS is applied to the tool to reflect the active state.
7091 * @return {boolean} Tool is active
7093 OO
.ui
.Tool
.prototype.isActive = function () {
7098 * Make the tool appear active or inactive.
7100 * This method should be called within #onSelect or #onUpdateState event handlers to make the tool
7101 * appear pressed or not.
7103 * @param {boolean} state Make tool appear active
7105 OO
.ui
.Tool
.prototype.setActive = function ( state
) {
7106 this.active
= !!state
;
7107 if ( this.active
) {
7108 this.$element
.addClass( 'oo-ui-tool-active' );
7110 this.$element
.removeClass( 'oo-ui-tool-active' );
7115 * Set the tool #title.
7117 * @param {string|Function} title Title text or a function that returns text
7120 OO
.ui
.Tool
.prototype.setTitle = function ( title
) {
7121 this.title
= OO
.ui
.resolveMsg( title
);
7127 * Get the tool #title.
7129 * @return {string} Title text
7131 OO
.ui
.Tool
.prototype.getTitle = function () {
7136 * Get the tool's symbolic name.
7138 * @return {string} Symbolic name of tool
7140 OO
.ui
.Tool
.prototype.getName = function () {
7141 return this.constructor.static.name
;
7147 OO
.ui
.Tool
.prototype.updateTitle = function () {
7148 var titleTooltips
= this.toolGroup
.constructor.static.titleTooltips
,
7149 accelTooltips
= this.toolGroup
.constructor.static.accelTooltips
,
7150 accel
= this.toolbar
.getToolAccelerator( this.constructor.static.name
),
7153 this.$title
.text( this.title
);
7154 this.$accel
.text( accel
);
7156 if ( titleTooltips
&& typeof this.title
=== 'string' && this.title
.length
) {
7157 tooltipParts
.push( this.title
);
7159 if ( accelTooltips
&& typeof accel
=== 'string' && accel
.length
) {
7160 tooltipParts
.push( accel
);
7162 if ( tooltipParts
.length
) {
7163 this.$link
.attr( 'title', tooltipParts
.join( ' ' ) );
7165 this.$link
.removeAttr( 'title' );
7172 * Destroying the tool removes all event handlers and the tool’s DOM elements.
7173 * Call this method whenever you are done using a tool.
7175 OO
.ui
.Tool
.prototype.destroy = function () {
7176 this.toolbar
.disconnect( this );
7177 this.$element
.remove();
7181 * Toolbars are complex interface components that permit users to easily access a variety
7182 * of {@link OO.ui.Tool tools} (e.g., formatting commands) and actions, which are additional commands that are
7183 * part of the toolbar, but not configured as tools.
7185 * Individual tools are customized and then registered with a {@link OO.ui.ToolFactory tool factory}, which creates
7186 * the tools on demand. Each tool has a symbolic name (used when registering the tool), a title (e.g., ‘Insert
7187 * picture’), and an icon.
7189 * Individual tools are organized in {@link OO.ui.ToolGroup toolgroups}, which can be {@link OO.ui.MenuToolGroup menus}
7190 * of tools, {@link OO.ui.ListToolGroup lists} of tools, or a single {@link OO.ui.BarToolGroup bar} of tools.
7191 * The arrangement and order of the toolgroups is customized when the toolbar is set up. Tools can be presented in
7192 * any order, but each can only appear once in the toolbar.
7194 * The following is an example of a basic toolbar.
7197 * // Example of a toolbar
7198 * // Create the toolbar
7199 * var toolFactory = new OO.ui.ToolFactory();
7200 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7201 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7203 * // We will be placing status text in this element when tools are used
7204 * var $area = $( '<p>' ).text( 'Toolbar example' );
7206 * // Define the tools that we're going to place in our toolbar
7208 * // Create a class inheriting from OO.ui.Tool
7209 * function PictureTool() {
7210 * PictureTool.parent.apply( this, arguments );
7212 * OO.inheritClass( PictureTool, OO.ui.Tool );
7213 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7214 * // of 'icon' and 'title' (displayed icon and text).
7215 * PictureTool.static.name = 'picture';
7216 * PictureTool.static.icon = 'picture';
7217 * PictureTool.static.title = 'Insert picture';
7218 * // Defines the action that will happen when this tool is selected (clicked).
7219 * PictureTool.prototype.onSelect = function () {
7220 * $area.text( 'Picture tool clicked!' );
7221 * // Never display this tool as "active" (selected).
7222 * this.setActive( false );
7224 * // Make this tool available in our toolFactory and thus our toolbar
7225 * toolFactory.register( PictureTool );
7227 * // Register two more tools, nothing interesting here
7228 * function SettingsTool() {
7229 * SettingsTool.parent.apply( this, arguments );
7231 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7232 * SettingsTool.static.name = 'settings';
7233 * SettingsTool.static.icon = 'settings';
7234 * SettingsTool.static.title = 'Change settings';
7235 * SettingsTool.prototype.onSelect = function () {
7236 * $area.text( 'Settings tool clicked!' );
7237 * this.setActive( false );
7239 * toolFactory.register( SettingsTool );
7241 * // Register two more tools, nothing interesting here
7242 * function StuffTool() {
7243 * StuffTool.parent.apply( this, arguments );
7245 * OO.inheritClass( StuffTool, OO.ui.Tool );
7246 * StuffTool.static.name = 'stuff';
7247 * StuffTool.static.icon = 'ellipsis';
7248 * StuffTool.static.title = 'More stuff';
7249 * StuffTool.prototype.onSelect = function () {
7250 * $area.text( 'More stuff tool clicked!' );
7251 * this.setActive( false );
7253 * toolFactory.register( StuffTool );
7255 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7256 * // little popup window (a PopupWidget).
7257 * function HelpTool( toolGroup, config ) {
7258 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7263 * this.popup.$body.append( '<p>I am helpful!</p>' );
7265 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7266 * HelpTool.static.name = 'help';
7267 * HelpTool.static.icon = 'help';
7268 * HelpTool.static.title = 'Help';
7269 * toolFactory.register( HelpTool );
7271 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7272 * // used once (but not all defined tools must be used).
7275 * // 'bar' tool groups display tools' icons only, side-by-side.
7277 * include: [ 'picture', 'help' ]
7280 * // 'list' tool groups display both the titles and icons, in a dropdown list.
7282 * indicator: 'down',
7284 * include: [ 'settings', 'stuff' ]
7286 * // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed
7287 * // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here,
7288 * // since it's more complicated to use. (See the next example snippet on this page.)
7291 * // Create some UI around the toolbar and place it in the document
7292 * var frame = new OO.ui.PanelLayout( {
7296 * var contentFrame = new OO.ui.PanelLayout( {
7300 * frame.$element.append(
7302 * contentFrame.$element.append( $area )
7304 * $( 'body' ).append( frame.$element );
7306 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7308 * toolbar.initialize();
7310 * The following example extends the previous one to illustrate 'menu' toolgroups and the usage of
7311 * 'updateState' event.
7314 * // Create the toolbar
7315 * var toolFactory = new OO.ui.ToolFactory();
7316 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7317 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7319 * // We will be placing status text in this element when tools are used
7320 * var $area = $( '<p>' ).text( 'Toolbar example' );
7322 * // Define the tools that we're going to place in our toolbar
7324 * // Create a class inheriting from OO.ui.Tool
7325 * function PictureTool() {
7326 * PictureTool.parent.apply( this, arguments );
7328 * OO.inheritClass( PictureTool, OO.ui.Tool );
7329 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7330 * // of 'icon' and 'title' (displayed icon and text).
7331 * PictureTool.static.name = 'picture';
7332 * PictureTool.static.icon = 'picture';
7333 * PictureTool.static.title = 'Insert picture';
7334 * // Defines the action that will happen when this tool is selected (clicked).
7335 * PictureTool.prototype.onSelect = function () {
7336 * $area.text( 'Picture tool clicked!' );
7337 * // Never display this tool as "active" (selected).
7338 * this.setActive( false );
7340 * // The toolbar can be synchronized with the state of some external stuff, like a text
7341 * // editor's editing area, highlighting the tools (e.g. a 'bold' tool would be shown as active
7342 * // when the text cursor was inside bolded text). Here we simply disable this feature.
7343 * PictureTool.prototype.onUpdateState = function () {
7345 * // Make this tool available in our toolFactory and thus our toolbar
7346 * toolFactory.register( PictureTool );
7348 * // Register two more tools, nothing interesting here
7349 * function SettingsTool() {
7350 * SettingsTool.parent.apply( this, arguments );
7351 * this.reallyActive = false;
7353 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7354 * SettingsTool.static.name = 'settings';
7355 * SettingsTool.static.icon = 'settings';
7356 * SettingsTool.static.title = 'Change settings';
7357 * SettingsTool.prototype.onSelect = function () {
7358 * $area.text( 'Settings tool clicked!' );
7359 * // Toggle the active state on each click
7360 * this.reallyActive = !this.reallyActive;
7361 * this.setActive( this.reallyActive );
7362 * // To update the menu label
7363 * this.toolbar.emit( 'updateState' );
7365 * SettingsTool.prototype.onUpdateState = function () {
7367 * toolFactory.register( SettingsTool );
7369 * // Register two more tools, nothing interesting here
7370 * function StuffTool() {
7371 * StuffTool.parent.apply( this, arguments );
7372 * this.reallyActive = false;
7374 * OO.inheritClass( StuffTool, OO.ui.Tool );
7375 * StuffTool.static.name = 'stuff';
7376 * StuffTool.static.icon = 'ellipsis';
7377 * StuffTool.static.title = 'More stuff';
7378 * StuffTool.prototype.onSelect = function () {
7379 * $area.text( 'More stuff tool clicked!' );
7380 * // Toggle the active state on each click
7381 * this.reallyActive = !this.reallyActive;
7382 * this.setActive( this.reallyActive );
7383 * // To update the menu label
7384 * this.toolbar.emit( 'updateState' );
7386 * StuffTool.prototype.onUpdateState = function () {
7388 * toolFactory.register( StuffTool );
7390 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7391 * // little popup window (a PopupWidget). 'onUpdateState' is also already implemented.
7392 * function HelpTool( toolGroup, config ) {
7393 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7398 * this.popup.$body.append( '<p>I am helpful!</p>' );
7400 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7401 * HelpTool.static.name = 'help';
7402 * HelpTool.static.icon = 'help';
7403 * HelpTool.static.title = 'Help';
7404 * toolFactory.register( HelpTool );
7406 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7407 * // used once (but not all defined tools must be used).
7410 * // 'bar' tool groups display tools' icons only, side-by-side.
7412 * include: [ 'picture', 'help' ]
7415 * // 'menu' tool groups display both the titles and icons, in a dropdown menu.
7416 * // Menu label indicates which items are selected.
7418 * indicator: 'down',
7419 * include: [ 'settings', 'stuff' ]
7423 * // Create some UI around the toolbar and place it in the document
7424 * var frame = new OO.ui.PanelLayout( {
7428 * var contentFrame = new OO.ui.PanelLayout( {
7432 * frame.$element.append(
7434 * contentFrame.$element.append( $area )
7436 * $( 'body' ).append( frame.$element );
7438 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7440 * toolbar.initialize();
7441 * toolbar.emit( 'updateState' );
7444 * @extends OO.ui.Element
7445 * @mixins OO.EventEmitter
7446 * @mixins OO.ui.mixin.GroupElement
7449 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
7450 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating toolgroups
7451 * @param {Object} [config] Configuration options
7452 * @cfg {boolean} [actions] Add an actions section to the toolbar. Actions are commands that are included
7453 * in the toolbar, but are not configured as tools. By default, actions are displayed on the right side of
7455 * @cfg {boolean} [shadow] Add a shadow below the toolbar.
7457 OO
.ui
.Toolbar
= function OoUiToolbar( toolFactory
, toolGroupFactory
, config
) {
7458 // Allow passing positional parameters inside the config object
7459 if ( OO
.isPlainObject( toolFactory
) && config
=== undefined ) {
7460 config
= toolFactory
;
7461 toolFactory
= config
.toolFactory
;
7462 toolGroupFactory
= config
.toolGroupFactory
;
7465 // Configuration initialization
7466 config
= config
|| {};
7468 // Parent constructor
7469 OO
.ui
.Toolbar
.parent
.call( this, config
);
7471 // Mixin constructors
7472 OO
.EventEmitter
.call( this );
7473 OO
.ui
.mixin
.GroupElement
.call( this, config
);
7476 this.toolFactory
= toolFactory
;
7477 this.toolGroupFactory
= toolGroupFactory
;
7480 this.$bar
= $( '<div>' );
7481 this.$actions
= $( '<div>' );
7482 this.initialized
= false;
7483 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
7487 .add( this.$bar
).add( this.$group
).add( this.$actions
)
7488 .on( 'mousedown keydown', this.onPointerDown
.bind( this ) );
7491 this.$group
.addClass( 'oo-ui-toolbar-tools' );
7492 if ( config
.actions
) {
7493 this.$bar
.append( this.$actions
.addClass( 'oo-ui-toolbar-actions' ) );
7496 .addClass( 'oo-ui-toolbar-bar' )
7497 .append( this.$group
, '<div style="clear:both"></div>' );
7498 if ( config
.shadow
) {
7499 this.$bar
.append( '<div class="oo-ui-toolbar-shadow"></div>' );
7501 this.$element
.addClass( 'oo-ui-toolbar' ).append( this.$bar
);
7506 OO
.inheritClass( OO
.ui
.Toolbar
, OO
.ui
.Element
);
7507 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.EventEmitter
);
7508 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.ui
.mixin
.GroupElement
);
7513 * Get the tool factory.
7515 * @return {OO.ui.ToolFactory} Tool factory
7517 OO
.ui
.Toolbar
.prototype.getToolFactory = function () {
7518 return this.toolFactory
;
7522 * Get the toolgroup factory.
7524 * @return {OO.Factory} Toolgroup factory
7526 OO
.ui
.Toolbar
.prototype.getToolGroupFactory = function () {
7527 return this.toolGroupFactory
;
7531 * Handles mouse down events.
7534 * @param {jQuery.Event} e Mouse down event
7536 OO
.ui
.Toolbar
.prototype.onPointerDown = function ( e
) {
7537 var $closestWidgetToEvent
= $( e
.target
).closest( '.oo-ui-widget' ),
7538 $closestWidgetToToolbar
= this.$element
.closest( '.oo-ui-widget' );
7539 if ( !$closestWidgetToEvent
.length
|| $closestWidgetToEvent
[ 0 ] === $closestWidgetToToolbar
[ 0 ] ) {
7545 * Handle window resize event.
7548 * @param {jQuery.Event} e Window resize event
7550 OO
.ui
.Toolbar
.prototype.onWindowResize = function () {
7551 this.$element
.toggleClass(
7552 'oo-ui-toolbar-narrow',
7553 this.$bar
.width() <= this.narrowThreshold
7558 * Sets up handles and preloads required information for the toolbar to work.
7559 * This must be called after it is attached to a visible document and before doing anything else.
7561 OO
.ui
.Toolbar
.prototype.initialize = function () {
7562 if ( !this.initialized
) {
7563 this.initialized
= true;
7564 this.narrowThreshold
= this.$group
.width() + this.$actions
.width();
7565 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler
);
7566 this.onWindowResize();
7571 * Set up the toolbar.
7573 * The toolbar is set up with a list of toolgroup configurations that specify the type of
7574 * toolgroup ({@link OO.ui.BarToolGroup bar}, {@link OO.ui.MenuToolGroup menu}, or {@link OO.ui.ListToolGroup list})
7575 * to add and which tools to include, exclude, promote, or demote within that toolgroup. Please
7576 * see {@link OO.ui.ToolGroup toolgroups} for more information about including tools in toolgroups.
7578 * @param {Object.<string,Array>} groups List of toolgroup configurations
7579 * @param {Array|string} [groups.include] Tools to include in the toolgroup
7580 * @param {Array|string} [groups.exclude] Tools to exclude from the toolgroup
7581 * @param {Array|string} [groups.promote] Tools to promote to the beginning of the toolgroup
7582 * @param {Array|string} [groups.demote] Tools to demote to the end of the toolgroup
7584 OO
.ui
.Toolbar
.prototype.setup = function ( groups
) {
7585 var i
, len
, type
, group
,
7587 defaultType
= 'bar';
7589 // Cleanup previous groups
7592 // Build out new groups
7593 for ( i
= 0, len
= groups
.length
; i
< len
; i
++ ) {
7594 group
= groups
[ i
];
7595 if ( group
.include
=== '*' ) {
7596 // Apply defaults to catch-all groups
7597 if ( group
.type
=== undefined ) {
7598 group
.type
= 'list';
7600 if ( group
.label
=== undefined ) {
7601 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
7604 // Check type has been registered
7605 type
= this.getToolGroupFactory().lookup( group
.type
) ? group
.type
: defaultType
;
7607 this.getToolGroupFactory().create( type
, this, group
)
7610 this.addItems( items
);
7614 * Remove all tools and toolgroups from the toolbar.
7616 OO
.ui
.Toolbar
.prototype.reset = function () {
7621 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
7622 this.items
[ i
].destroy();
7628 * Destroy the toolbar.
7630 * Destroying the toolbar removes all event handlers and DOM elements that constitute the toolbar. Call
7631 * this method whenever you are done using a toolbar.
7633 OO
.ui
.Toolbar
.prototype.destroy = function () {
7634 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler
);
7636 this.$element
.remove();
7640 * Check if the tool is available.
7642 * Available tools are ones that have not yet been added to the toolbar.
7644 * @param {string} name Symbolic name of tool
7645 * @return {boolean} Tool is available
7647 OO
.ui
.Toolbar
.prototype.isToolAvailable = function ( name
) {
7648 return !this.tools
[ name
];
7652 * Prevent tool from being used again.
7654 * @param {OO.ui.Tool} tool Tool to reserve
7656 OO
.ui
.Toolbar
.prototype.reserveTool = function ( tool
) {
7657 this.tools
[ tool
.getName() ] = tool
;
7661 * Allow tool to be used again.
7663 * @param {OO.ui.Tool} tool Tool to release
7665 OO
.ui
.Toolbar
.prototype.releaseTool = function ( tool
) {
7666 delete this.tools
[ tool
.getName() ];
7670 * Get accelerator label for tool.
7672 * The OOjs UI library does not contain an accelerator system, but this is the hook for one. To
7673 * use an accelerator system, subclass the toolbar and override this method, which is meant to return a label
7674 * that describes the accelerator keys for the tool passed (by symbolic name) to the method.
7676 * @param {string} name Symbolic name of tool
7677 * @return {string|undefined} Tool accelerator label if available
7679 OO
.ui
.Toolbar
.prototype.getToolAccelerator = function () {
7684 * ToolGroups are collections of {@link OO.ui.Tool tools} that are used in a {@link OO.ui.Toolbar toolbar}.
7685 * The type of toolgroup ({@link OO.ui.ListToolGroup list}, {@link OO.ui.BarToolGroup bar}, or {@link OO.ui.MenuToolGroup menu})
7686 * to which a tool belongs determines how the tool is arranged and displayed in the toolbar. Toolgroups
7687 * themselves are created on demand with a {@link OO.ui.ToolGroupFactory toolgroup factory}.
7689 * Toolgroups can contain individual tools, groups of tools, or all available tools:
7691 * To include an individual tool (or array of individual tools), specify tools by symbolic name:
7693 * include: [ 'tool-name' ] or [ { name: 'tool-name' }]
7695 * To include a group of tools, specify the group name. (The tool's static ‘group’ config is used to assign the tool to a group.)
7697 * include: [ { group: 'group-name' } ]
7699 * To include all tools that are not yet assigned to a toolgroup, use the catch-all selector, an asterisk (*):
7703 * See {@link OO.ui.Toolbar toolbars} for a full example. For more information about toolbars in general,
7704 * please see the [OOjs UI documentation on MediaWiki][1].
7706 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7710 * @extends OO.ui.Widget
7711 * @mixins OO.ui.mixin.GroupElement
7714 * @param {OO.ui.Toolbar} toolbar
7715 * @param {Object} [config] Configuration options
7716 * @cfg {Array|string} [include=[]] List of tools to include in the toolgroup.
7717 * @cfg {Array|string} [exclude=[]] List of tools to exclude from the toolgroup.
7718 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning of the toolgroup.
7719 * @cfg {Array|string} [demote=[]] List of tools to demote to the end of the toolgroup.
7720 * This setting is particularly useful when tools have been added to the toolgroup
7721 * en masse (e.g., via the catch-all selector).
7723 OO
.ui
.ToolGroup
= function OoUiToolGroup( toolbar
, config
) {
7724 // Allow passing positional parameters inside the config object
7725 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
7727 toolbar
= config
.toolbar
;
7730 // Configuration initialization
7731 config
= config
|| {};
7733 // Parent constructor
7734 OO
.ui
.ToolGroup
.parent
.call( this, config
);
7736 // Mixin constructors
7737 OO
.ui
.mixin
.GroupElement
.call( this, config
);
7740 this.toolbar
= toolbar
;
7742 this.pressed
= null;
7743 this.autoDisabled
= false;
7744 this.include
= config
.include
|| [];
7745 this.exclude
= config
.exclude
|| [];
7746 this.promote
= config
.promote
|| [];
7747 this.demote
= config
.demote
|| [];
7748 this.onCapturedMouseKeyUpHandler
= this.onCapturedMouseKeyUp
.bind( this );
7752 mousedown
: this.onMouseKeyDown
.bind( this ),
7753 mouseup
: this.onMouseKeyUp
.bind( this ),
7754 keydown
: this.onMouseKeyDown
.bind( this ),
7755 keyup
: this.onMouseKeyUp
.bind( this ),
7756 focus
: this.onMouseOverFocus
.bind( this ),
7757 blur
: this.onMouseOutBlur
.bind( this ),
7758 mouseover
: this.onMouseOverFocus
.bind( this ),
7759 mouseout
: this.onMouseOutBlur
.bind( this )
7761 this.toolbar
.getToolFactory().connect( this, { register
: 'onToolFactoryRegister' } );
7762 this.aggregate( { disable
: 'itemDisable' } );
7763 this.connect( this, { itemDisable
: 'updateDisabled' } );
7766 this.$group
.addClass( 'oo-ui-toolGroup-tools' );
7768 .addClass( 'oo-ui-toolGroup' )
7769 .append( this.$group
);
7775 OO
.inheritClass( OO
.ui
.ToolGroup
, OO
.ui
.Widget
);
7776 OO
.mixinClass( OO
.ui
.ToolGroup
, OO
.ui
.mixin
.GroupElement
);
7784 /* Static Properties */
7787 * Show labels in tooltips.
7791 * @property {boolean}
7793 OO
.ui
.ToolGroup
.static.titleTooltips
= false;
7796 * Show acceleration labels in tooltips.
7798 * Note: The OOjs UI library does not include an accelerator system, but does contain
7799 * a hook for one. To use an accelerator system, subclass the {@link OO.ui.Toolbar toolbar} and
7800 * override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method, which is
7801 * meant to return a label that describes the accelerator keys for a given tool (e.g., 'Ctrl + M').
7805 * @property {boolean}
7807 OO
.ui
.ToolGroup
.static.accelTooltips
= false;
7810 * Automatically disable the toolgroup when all tools are disabled
7814 * @property {boolean}
7816 OO
.ui
.ToolGroup
.static.autoDisable
= true;
7823 OO
.ui
.ToolGroup
.prototype.isDisabled = function () {
7824 return this.autoDisabled
|| OO
.ui
.ToolGroup
.parent
.prototype.isDisabled
.apply( this, arguments
);
7830 OO
.ui
.ToolGroup
.prototype.updateDisabled = function () {
7831 var i
, item
, allDisabled
= true;
7833 if ( this.constructor.static.autoDisable
) {
7834 for ( i
= this.items
.length
- 1; i
>= 0; i
-- ) {
7835 item
= this.items
[ i
];
7836 if ( !item
.isDisabled() ) {
7837 allDisabled
= false;
7841 this.autoDisabled
= allDisabled
;
7843 OO
.ui
.ToolGroup
.parent
.prototype.updateDisabled
.apply( this, arguments
);
7847 * Handle mouse down and key down events.
7850 * @param {jQuery.Event} e Mouse down or key down event
7852 OO
.ui
.ToolGroup
.prototype.onMouseKeyDown = function ( e
) {
7854 !this.isDisabled() &&
7855 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
7857 this.pressed
= this.getTargetTool( e
);
7858 if ( this.pressed
) {
7859 this.pressed
.setActive( true );
7860 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler
);
7861 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler
);
7868 * Handle captured mouse up and key up events.
7871 * @param {Event} e Mouse up or key up event
7873 OO
.ui
.ToolGroup
.prototype.onCapturedMouseKeyUp = function ( e
) {
7874 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler
);
7875 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler
);
7876 // onMouseKeyUp may be called a second time, depending on where the mouse is when the button is
7877 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
7878 this.onMouseKeyUp( e
);
7882 * Handle mouse up and key up events.
7885 * @param {jQuery.Event} e Mouse up or key up event
7887 OO
.ui
.ToolGroup
.prototype.onMouseKeyUp = function ( e
) {
7888 var tool
= this.getTargetTool( e
);
7891 !this.isDisabled() && this.pressed
&& this.pressed
=== tool
&&
7892 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
7894 this.pressed
.onSelect();
7895 this.pressed
= null;
7899 this.pressed
= null;
7903 * Handle mouse over and focus events.
7906 * @param {jQuery.Event} e Mouse over or focus event
7908 OO
.ui
.ToolGroup
.prototype.onMouseOverFocus = function ( e
) {
7909 var tool
= this.getTargetTool( e
);
7911 if ( this.pressed
&& this.pressed
=== tool
) {
7912 this.pressed
.setActive( true );
7917 * Handle mouse out and blur events.
7920 * @param {jQuery.Event} e Mouse out or blur event
7922 OO
.ui
.ToolGroup
.prototype.onMouseOutBlur = function ( e
) {
7923 var tool
= this.getTargetTool( e
);
7925 if ( this.pressed
&& this.pressed
=== tool
) {
7926 this.pressed
.setActive( false );
7931 * Get the closest tool to a jQuery.Event.
7933 * Only tool links are considered, which prevents other elements in the tool such as popups from
7934 * triggering tool group interactions.
7937 * @param {jQuery.Event} e
7938 * @return {OO.ui.Tool|null} Tool, `null` if none was found
7940 OO
.ui
.ToolGroup
.prototype.getTargetTool = function ( e
) {
7942 $item
= $( e
.target
).closest( '.oo-ui-tool-link' );
7944 if ( $item
.length
) {
7945 tool
= $item
.parent().data( 'oo-ui-tool' );
7948 return tool
&& !tool
.isDisabled() ? tool
: null;
7952 * Handle tool registry register events.
7954 * If a tool is registered after the group is created, we must repopulate the list to account for:
7956 * - a tool being added that may be included
7957 * - a tool already included being overridden
7960 * @param {string} name Symbolic name of tool
7962 OO
.ui
.ToolGroup
.prototype.onToolFactoryRegister = function () {
7967 * Get the toolbar that contains the toolgroup.
7969 * @return {OO.ui.Toolbar} Toolbar that contains the toolgroup
7971 OO
.ui
.ToolGroup
.prototype.getToolbar = function () {
7972 return this.toolbar
;
7976 * Add and remove tools based on configuration.
7978 OO
.ui
.ToolGroup
.prototype.populate = function () {
7979 var i
, len
, name
, tool
,
7980 toolFactory
= this.toolbar
.getToolFactory(),
7984 list
= this.toolbar
.getToolFactory().getTools(
7985 this.include
, this.exclude
, this.promote
, this.demote
7988 // Build a list of needed tools
7989 for ( i
= 0, len
= list
.length
; i
< len
; i
++ ) {
7993 toolFactory
.lookup( name
) &&
7994 // Tool is available or is already in this group
7995 ( this.toolbar
.isToolAvailable( name
) || this.tools
[ name
] )
7997 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
7998 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
7999 this.toolbar
.tools
[ name
] = true;
8000 tool
= this.tools
[ name
];
8002 // Auto-initialize tools on first use
8003 this.tools
[ name
] = tool
= toolFactory
.create( name
, this );
8006 this.toolbar
.reserveTool( tool
);
8008 names
[ name
] = true;
8011 // Remove tools that are no longer needed
8012 for ( name
in this.tools
) {
8013 if ( !names
[ name
] ) {
8014 this.tools
[ name
].destroy();
8015 this.toolbar
.releaseTool( this.tools
[ name
] );
8016 remove
.push( this.tools
[ name
] );
8017 delete this.tools
[ name
];
8020 if ( remove
.length
) {
8021 this.removeItems( remove
);
8023 // Update emptiness state
8025 this.$element
.removeClass( 'oo-ui-toolGroup-empty' );
8027 this.$element
.addClass( 'oo-ui-toolGroup-empty' );
8029 // Re-add tools (moving existing ones to new locations)
8030 this.addItems( add
);
8031 // Disabled state may depend on items
8032 this.updateDisabled();
8036 * Destroy toolgroup.
8038 OO
.ui
.ToolGroup
.prototype.destroy = function () {
8042 this.toolbar
.getToolFactory().disconnect( this );
8043 for ( name
in this.tools
) {
8044 this.toolbar
.releaseTool( this.tools
[ name
] );
8045 this.tools
[ name
].disconnect( this ).destroy();
8046 delete this.tools
[ name
];
8048 this.$element
.remove();
8052 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
8053 * consists of a header that contains the dialog title, a body with the message, and a footer that
8054 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
8055 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
8057 * There are two basic types of message dialogs, confirmation and alert:
8059 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
8060 * more details about the consequences.
8061 * - **alert**: the dialog title describes which event occurred and the message provides more information
8062 * about why the event occurred.
8064 * The MessageDialog class specifies two actions: ‘accept’, the primary
8065 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
8066 * passing along the selected action.
8068 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
8071 * // Example: Creating and opening a message dialog window.
8072 * var messageDialog = new OO.ui.MessageDialog();
8074 * // Create and append a window manager.
8075 * var windowManager = new OO.ui.WindowManager();
8076 * $( 'body' ).append( windowManager.$element );
8077 * windowManager.addWindows( [ messageDialog ] );
8078 * // Open the window.
8079 * windowManager.openWindow( messageDialog, {
8080 * title: 'Basic message dialog',
8081 * message: 'This is the message'
8084 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
8087 * @extends OO.ui.Dialog
8090 * @param {Object} [config] Configuration options
8092 OO
.ui
.MessageDialog
= function OoUiMessageDialog( config
) {
8093 // Parent constructor
8094 OO
.ui
.MessageDialog
.parent
.call( this, config
);
8097 this.verticalActionLayout
= null;
8100 this.$element
.addClass( 'oo-ui-messageDialog' );
8105 OO
.inheritClass( OO
.ui
.MessageDialog
, OO
.ui
.Dialog
);
8107 /* Static Properties */
8109 OO
.ui
.MessageDialog
.static.name
= 'message';
8111 OO
.ui
.MessageDialog
.static.size
= 'small';
8113 OO
.ui
.MessageDialog
.static.verbose
= false;
8118 * The title of a confirmation dialog describes what a progressive action will do. The
8119 * title of an alert dialog describes which event occurred.
8123 * @property {jQuery|string|Function|null}
8125 OO
.ui
.MessageDialog
.static.title
= null;
8128 * The message displayed in the dialog body.
8130 * A confirmation message describes the consequences of a progressive action. An alert
8131 * message describes why an event occurred.
8135 * @property {jQuery|string|Function|null}
8137 OO
.ui
.MessageDialog
.static.message
= null;
8139 OO
.ui
.MessageDialog
.static.actions
= [
8140 { action
: 'accept', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-accept' ), flags
: 'primary' },
8141 { action
: 'reject', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-reject' ), flags
: 'safe' }
8149 OO
.ui
.MessageDialog
.prototype.setManager = function ( manager
) {
8150 OO
.ui
.MessageDialog
.parent
.prototype.setManager
.call( this, manager
);
8153 this.manager
.connect( this, {
8163 OO
.ui
.MessageDialog
.prototype.onActionResize = function ( action
) {
8165 return OO
.ui
.MessageDialog
.parent
.prototype.onActionResize
.call( this, action
);
8169 * Handle window resized events.
8173 OO
.ui
.MessageDialog
.prototype.onResize = function () {
8175 dialog
.fitActions();
8176 // Wait for CSS transition to finish and do it again :(
8177 setTimeout( function () {
8178 dialog
.fitActions();
8183 * Toggle action layout between vertical and horizontal.
8187 * @param {boolean} [value] Layout actions vertically, omit to toggle
8190 OO
.ui
.MessageDialog
.prototype.toggleVerticalActionLayout = function ( value
) {
8191 value
= value
=== undefined ? !this.verticalActionLayout
: !!value
;
8193 if ( value
!== this.verticalActionLayout
) {
8194 this.verticalActionLayout
= value
;
8196 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value
)
8197 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value
);
8206 OO
.ui
.MessageDialog
.prototype.getActionProcess = function ( action
) {
8208 return new OO
.ui
.Process( function () {
8209 this.close( { action
: action
} );
8212 return OO
.ui
.MessageDialog
.parent
.prototype.getActionProcess
.call( this, action
);
8218 * @param {Object} [data] Dialog opening data
8219 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
8220 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
8221 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
8222 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
8225 OO
.ui
.MessageDialog
.prototype.getSetupProcess = function ( data
) {
8229 return OO
.ui
.MessageDialog
.parent
.prototype.getSetupProcess
.call( this, data
)
8230 .next( function () {
8231 this.title
.setLabel(
8232 data
.title
!== undefined ? data
.title
: this.constructor.static.title
8234 this.message
.setLabel(
8235 data
.message
!== undefined ? data
.message
: this.constructor.static.message
8237 this.message
.$element
.toggleClass(
8238 'oo-ui-messageDialog-message-verbose',
8239 data
.verbose
!== undefined ? data
.verbose
: this.constructor.static.verbose
8247 OO
.ui
.MessageDialog
.prototype.getReadyProcess = function ( data
) {
8251 return OO
.ui
.MessageDialog
.parent
.prototype.getReadyProcess
.call( this, data
)
8252 .next( function () {
8253 // Focus the primary action button
8254 var actions
= this.actions
.get();
8255 actions
= actions
.filter( function ( action
) {
8256 return action
.getFlags().indexOf( 'primary' ) > -1;
8258 if ( actions
.length
> 0 ) {
8259 actions
[ 0 ].$button
.focus();
8267 OO
.ui
.MessageDialog
.prototype.getBodyHeight = function () {
8268 var bodyHeight
, oldOverflow
,
8269 $scrollable
= this.container
.$element
;
8271 oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
8272 $scrollable
[ 0 ].style
.overflow
= 'hidden';
8274 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
8276 bodyHeight
= this.text
.$element
.outerHeight( true );
8277 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
8285 OO
.ui
.MessageDialog
.prototype.setDimensions = function ( dim
) {
8286 var $scrollable
= this.container
.$element
;
8287 OO
.ui
.MessageDialog
.parent
.prototype.setDimensions
.call( this, dim
);
8289 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
8290 // Need to do it after transition completes (250ms), add 50ms just in case.
8291 setTimeout( function () {
8292 var oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
8293 $scrollable
[ 0 ].style
.overflow
= 'hidden';
8295 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
8297 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
8306 OO
.ui
.MessageDialog
.prototype.initialize = function () {
8308 OO
.ui
.MessageDialog
.parent
.prototype.initialize
.call( this );
8311 this.$actions
= $( '<div>' );
8312 this.container
= new OO
.ui
.PanelLayout( {
8313 scrollable
: true, classes
: [ 'oo-ui-messageDialog-container' ]
8315 this.text
= new OO
.ui
.PanelLayout( {
8316 padded
: true, expanded
: false, classes
: [ 'oo-ui-messageDialog-text' ]
8318 this.message
= new OO
.ui
.LabelWidget( {
8319 classes
: [ 'oo-ui-messageDialog-message' ]
8323 this.title
.$element
.addClass( 'oo-ui-messageDialog-title' );
8324 this.$content
.addClass( 'oo-ui-messageDialog-content' );
8325 this.container
.$element
.append( this.text
.$element
);
8326 this.text
.$element
.append( this.title
.$element
, this.message
.$element
);
8327 this.$body
.append( this.container
.$element
);
8328 this.$actions
.addClass( 'oo-ui-messageDialog-actions' );
8329 this.$foot
.append( this.$actions
);
8335 OO
.ui
.MessageDialog
.prototype.attachActions = function () {
8336 var i
, len
, other
, special
, others
;
8339 OO
.ui
.MessageDialog
.parent
.prototype.attachActions
.call( this );
8341 special
= this.actions
.getSpecial();
8342 others
= this.actions
.getOthers();
8344 if ( special
.safe
) {
8345 this.$actions
.append( special
.safe
.$element
);
8346 special
.safe
.toggleFramed( false );
8348 if ( others
.length
) {
8349 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
8350 other
= others
[ i
];
8351 this.$actions
.append( other
.$element
);
8352 other
.toggleFramed( false );
8355 if ( special
.primary
) {
8356 this.$actions
.append( special
.primary
.$element
);
8357 special
.primary
.toggleFramed( false );
8360 if ( !this.isOpening() ) {
8361 // If the dialog is currently opening, this will be called automatically soon.
8362 // This also calls #fitActions.
8368 * Fit action actions into columns or rows.
8370 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
8374 OO
.ui
.MessageDialog
.prototype.fitActions = function () {
8376 previous
= this.verticalActionLayout
,
8377 actions
= this.actions
.get();
8380 this.toggleVerticalActionLayout( false );
8381 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
8382 action
= actions
[ i
];
8383 if ( action
.$element
.innerWidth() < action
.$label
.outerWidth( true ) ) {
8384 this.toggleVerticalActionLayout( true );
8389 // Move the body out of the way of the foot
8390 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
8392 if ( this.verticalActionLayout
!== previous
) {
8393 // We changed the layout, window height might need to be updated.
8399 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
8400 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
8401 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
8402 * relevant. The ProcessDialog class is always extended and customized with the actions and content
8403 * required for each process.
8405 * The process dialog box consists of a header that visually represents the ‘working’ state of long
8406 * processes with an animation. The header contains the dialog title as well as
8407 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
8408 * a ‘primary’ action on the right (e.g., ‘Done’).
8410 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
8411 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
8414 * // Example: Creating and opening a process dialog window.
8415 * function MyProcessDialog( config ) {
8416 * MyProcessDialog.parent.call( this, config );
8418 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
8420 * MyProcessDialog.static.title = 'Process dialog';
8421 * MyProcessDialog.static.actions = [
8422 * { action: 'save', label: 'Done', flags: 'primary' },
8423 * { label: 'Cancel', flags: 'safe' }
8426 * MyProcessDialog.prototype.initialize = function () {
8427 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
8428 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
8429 * 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>' );
8430 * this.$body.append( this.content.$element );
8432 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
8433 * var dialog = this;
8435 * return new OO.ui.Process( function () {
8436 * dialog.close( { action: action } );
8439 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
8442 * var windowManager = new OO.ui.WindowManager();
8443 * $( 'body' ).append( windowManager.$element );
8445 * var dialog = new MyProcessDialog();
8446 * windowManager.addWindows( [ dialog ] );
8447 * windowManager.openWindow( dialog );
8449 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
8453 * @extends OO.ui.Dialog
8456 * @param {Object} [config] Configuration options
8458 OO
.ui
.ProcessDialog
= function OoUiProcessDialog( config
) {
8459 // Parent constructor
8460 OO
.ui
.ProcessDialog
.parent
.call( this, config
);
8463 this.fitOnOpen
= false;
8466 this.$element
.addClass( 'oo-ui-processDialog' );
8471 OO
.inheritClass( OO
.ui
.ProcessDialog
, OO
.ui
.Dialog
);
8476 * Handle dismiss button click events.
8482 OO
.ui
.ProcessDialog
.prototype.onDismissErrorButtonClick = function () {
8487 * Handle retry button click events.
8489 * Hides errors and then tries again.
8493 OO
.ui
.ProcessDialog
.prototype.onRetryButtonClick = function () {
8495 this.executeAction( this.currentAction
);
8501 OO
.ui
.ProcessDialog
.prototype.onActionResize = function ( action
) {
8502 if ( this.actions
.isSpecial( action
) ) {
8505 return OO
.ui
.ProcessDialog
.parent
.prototype.onActionResize
.call( this, action
);
8511 OO
.ui
.ProcessDialog
.prototype.initialize = function () {
8513 OO
.ui
.ProcessDialog
.parent
.prototype.initialize
.call( this );
8516 this.$navigation
= $( '<div>' );
8517 this.$location
= $( '<div>' );
8518 this.$safeActions
= $( '<div>' );
8519 this.$primaryActions
= $( '<div>' );
8520 this.$otherActions
= $( '<div>' );
8521 this.dismissButton
= new OO
.ui
.ButtonWidget( {
8522 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' )
8524 this.retryButton
= new OO
.ui
.ButtonWidget();
8525 this.$errors
= $( '<div>' );
8526 this.$errorsTitle
= $( '<div>' );
8529 this.dismissButton
.connect( this, { click
: 'onDismissErrorButtonClick' } );
8530 this.retryButton
.connect( this, { click
: 'onRetryButtonClick' } );
8533 this.title
.$element
.addClass( 'oo-ui-processDialog-title' );
8535 .append( this.title
.$element
)
8536 .addClass( 'oo-ui-processDialog-location' );
8537 this.$safeActions
.addClass( 'oo-ui-processDialog-actions-safe' );
8538 this.$primaryActions
.addClass( 'oo-ui-processDialog-actions-primary' );
8539 this.$otherActions
.addClass( 'oo-ui-processDialog-actions-other' );
8541 .addClass( 'oo-ui-processDialog-errors-title' )
8542 .text( OO
.ui
.msg( 'ooui-dialog-process-error' ) );
8544 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
8545 .append( this.$errorsTitle
, this.dismissButton
.$element
, this.retryButton
.$element
);
8547 .addClass( 'oo-ui-processDialog-content' )
8548 .append( this.$errors
);
8550 .addClass( 'oo-ui-processDialog-navigation' )
8551 .append( this.$safeActions
, this.$location
, this.$primaryActions
);
8552 this.$head
.append( this.$navigation
);
8553 this.$foot
.append( this.$otherActions
);
8559 OO
.ui
.ProcessDialog
.prototype.getActionWidgets = function ( actions
) {
8560 var i
, len
, widgets
= [];
8561 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
8563 new OO
.ui
.ActionWidget( $.extend( { framed
: true }, actions
[ i
] ) )
8572 OO
.ui
.ProcessDialog
.prototype.attachActions = function () {
8573 var i
, len
, other
, special
, others
;
8576 OO
.ui
.ProcessDialog
.parent
.prototype.attachActions
.call( this );
8578 special
= this.actions
.getSpecial();
8579 others
= this.actions
.getOthers();
8580 if ( special
.primary
) {
8581 this.$primaryActions
.append( special
.primary
.$element
);
8583 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
8584 other
= others
[ i
];
8585 this.$otherActions
.append( other
.$element
);
8587 if ( special
.safe
) {
8588 this.$safeActions
.append( special
.safe
.$element
);
8592 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
8598 OO
.ui
.ProcessDialog
.prototype.executeAction = function ( action
) {
8600 return OO
.ui
.ProcessDialog
.parent
.prototype.executeAction
.call( this, action
)
8601 .fail( function ( errors
) {
8602 process
.showErrors( errors
|| [] );
8609 OO
.ui
.ProcessDialog
.prototype.setDimensions = function () {
8611 OO
.ui
.ProcessDialog
.parent
.prototype.setDimensions
.apply( this, arguments
);
8617 * Fit label between actions.
8622 OO
.ui
.ProcessDialog
.prototype.fitLabel = function () {
8623 var safeWidth
, primaryWidth
, biggerWidth
, labelWidth
, navigationWidth
, leftWidth
, rightWidth
,
8624 size
= this.getSizeProperties();
8626 if ( typeof size
.width
!== 'number' ) {
8627 if ( this.isOpened() ) {
8628 navigationWidth
= this.$head
.width() - 20;
8629 } else if ( this.isOpening() ) {
8630 if ( !this.fitOnOpen
) {
8631 // Size is relative and the dialog isn't open yet, so wait.
8632 this.manager
.opening
.done( this.fitLabel
.bind( this ) );
8633 this.fitOnOpen
= true;
8640 navigationWidth
= size
.width
- 20;
8643 safeWidth
= this.$safeActions
.is( ':visible' ) ? this.$safeActions
.width() : 0;
8644 primaryWidth
= this.$primaryActions
.is( ':visible' ) ? this.$primaryActions
.width() : 0;
8645 biggerWidth
= Math
.max( safeWidth
, primaryWidth
);
8647 labelWidth
= this.title
.$element
.width();
8649 if ( 2 * biggerWidth
+ labelWidth
< navigationWidth
) {
8650 // We have enough space to center the label
8651 leftWidth
= rightWidth
= biggerWidth
;
8653 // Let's hope we at least have enough space not to overlap, because we can't wrap the label…
8654 if ( this.getDir() === 'ltr' ) {
8655 leftWidth
= safeWidth
;
8656 rightWidth
= primaryWidth
;
8658 leftWidth
= primaryWidth
;
8659 rightWidth
= safeWidth
;
8663 this.$location
.css( { paddingLeft
: leftWidth
, paddingRight
: rightWidth
} );
8669 * Handle errors that occurred during accept or reject processes.
8672 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
8674 OO
.ui
.ProcessDialog
.prototype.showErrors = function ( errors
) {
8675 var i
, len
, $item
, actions
,
8681 if ( errors
instanceof OO
.ui
.Error
) {
8682 errors
= [ errors
];
8685 for ( i
= 0, len
= errors
.length
; i
< len
; i
++ ) {
8686 if ( !errors
[ i
].isRecoverable() ) {
8687 recoverable
= false;
8689 if ( errors
[ i
].isWarning() ) {
8692 $item
= $( '<div>' )
8693 .addClass( 'oo-ui-processDialog-error' )
8694 .append( errors
[ i
].getMessage() );
8695 items
.push( $item
[ 0 ] );
8697 this.$errorItems
= $( items
);
8698 if ( recoverable
) {
8699 abilities
[ this.currentAction
] = true;
8700 // Copy the flags from the first matching action
8701 actions
= this.actions
.get( { actions
: this.currentAction
} );
8702 if ( actions
.length
) {
8703 this.retryButton
.clearFlags().setFlags( actions
[ 0 ].getFlags() );
8706 abilities
[ this.currentAction
] = false;
8707 this.actions
.setAbilities( abilities
);
8710 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-continue' ) );
8712 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-retry' ) );
8714 this.retryButton
.toggle( recoverable
);
8715 this.$errorsTitle
.after( this.$errorItems
);
8716 this.$errors
.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
8724 OO
.ui
.ProcessDialog
.prototype.hideErrors = function () {
8725 this.$errors
.addClass( 'oo-ui-element-hidden' );
8726 if ( this.$errorItems
) {
8727 this.$errorItems
.remove();
8728 this.$errorItems
= null;
8735 OO
.ui
.ProcessDialog
.prototype.getTeardownProcess = function ( data
) {
8737 return OO
.ui
.ProcessDialog
.parent
.prototype.getTeardownProcess
.call( this, data
)
8738 .first( function () {
8739 // Make sure to hide errors
8741 this.fitOnOpen
= false;
8746 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
8747 * which is a widget that is specified by reference before any optional configuration settings.
8749 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
8751 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8752 * A left-alignment is used for forms with many fields.
8753 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8754 * A right-alignment is used for long but familiar forms which users tab through,
8755 * verifying the current field with a quick glance at the label.
8756 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8757 * that users fill out from top to bottom.
8758 * - **inline**: The label is placed after the field-widget and aligned to the left.
8759 * An inline-alignment is best used with checkboxes or radio buttons.
8761 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
8762 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
8764 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8766 * @extends OO.ui.Layout
8767 * @mixins OO.ui.mixin.LabelElement
8768 * @mixins OO.ui.mixin.TitledElement
8771 * @param {OO.ui.Widget} fieldWidget Field widget
8772 * @param {Object} [config] Configuration options
8773 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
8774 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
8775 * The array may contain strings or OO.ui.HtmlSnippet instances.
8776 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
8777 * The array may contain strings or OO.ui.HtmlSnippet instances.
8778 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
8779 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
8780 * For important messages, you are advised to use `notices`, as they are always shown.
8782 * @throws {Error} An error is thrown if no widget is specified
8784 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
8785 var hasInputWidget
, div
, i
;
8787 // Allow passing positional parameters inside the config object
8788 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
8789 config
= fieldWidget
;
8790 fieldWidget
= config
.fieldWidget
;
8793 // Make sure we have required constructor arguments
8794 if ( fieldWidget
=== undefined ) {
8795 throw new Error( 'Widget not found' );
8798 hasInputWidget
= fieldWidget
.constructor.static.supportsSimpleLabel
;
8800 // Configuration initialization
8801 config
= $.extend( { align
: 'left' }, config
);
8803 // Parent constructor
8804 OO
.ui
.FieldLayout
.parent
.call( this, config
);
8806 // Mixin constructors
8807 OO
.ui
.mixin
.LabelElement
.call( this, config
);
8808 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
8811 this.fieldWidget
= fieldWidget
;
8812 this.errors
= config
.errors
|| [];
8813 this.notices
= config
.notices
|| [];
8814 this.$field
= $( '<div>' );
8815 this.$messages
= $( '<ul>' );
8816 this.$body
= $( '<' + ( hasInputWidget
? 'label' : 'div' ) + '>' );
8818 if ( config
.help
) {
8819 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
8820 classes
: [ 'oo-ui-fieldLayout-help' ],
8826 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
8827 div
.html( config
.help
.toString() );
8829 div
.text( config
.help
);
8831 this.popupButtonWidget
.getPopup().$body
.append(
8832 div
.addClass( 'oo-ui-fieldLayout-help-content' )
8834 this.$help
= this.popupButtonWidget
.$element
;
8836 this.$help
= $( [] );
8840 if ( hasInputWidget
) {
8841 this.$label
.on( 'click', this.onLabelClick
.bind( this ) );
8843 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
8847 .addClass( 'oo-ui-fieldLayout' )
8848 .append( this.$help
, this.$body
);
8849 if ( this.errors
.length
|| this.notices
.length
) {
8850 this.$element
.append( this.$messages
);
8852 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
8853 this.$messages
.addClass( 'oo-ui-fieldLayout-messages' );
8855 .addClass( 'oo-ui-fieldLayout-field' )
8856 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget
.isDisabled() )
8857 .append( this.fieldWidget
.$element
);
8859 for ( i
= 0; i
< this.notices
.length
; i
++ ) {
8860 this.$messages
.append( this.makeMessage( 'notice', this.notices
[ i
] ) );
8862 for ( i
= 0; i
< this.errors
.length
; i
++ ) {
8863 this.$messages
.append( this.makeMessage( 'error', this.errors
[ i
] ) );
8866 this.setAlignment( config
.align
);
8871 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
8872 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.LabelElement
);
8873 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.TitledElement
);
8878 * Handle field disable events.
8881 * @param {boolean} value Field is disabled
8883 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
8884 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
8888 * Handle label mouse click events.
8891 * @param {jQuery.Event} e Mouse click event
8893 OO
.ui
.FieldLayout
.prototype.onLabelClick = function () {
8894 this.fieldWidget
.simulateLabelClick();
8899 * Get the widget contained by the field.
8901 * @return {OO.ui.Widget} Field widget
8903 OO
.ui
.FieldLayout
.prototype.getField = function () {
8904 return this.fieldWidget
;
8908 * @param {string} kind 'error' or 'notice'
8909 * @param {string|OO.ui.HtmlSnippet} text
8912 OO
.ui
.FieldLayout
.prototype.makeMessage = function ( kind
, text
) {
8913 var $listItem
, $icon
, message
;
8914 $listItem
= $( '<li>' );
8915 if ( kind
=== 'error' ) {
8916 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'warning' ] } ).$element
;
8917 } else if ( kind
=== 'notice' ) {
8918 $icon
= new OO
.ui
.IconWidget( { icon
: 'info' } ).$element
;
8922 message
= new OO
.ui
.LabelWidget( { label
: text
} );
8924 .append( $icon
, message
.$element
)
8925 .addClass( 'oo-ui-fieldLayout-messages-' + kind
);
8930 * Set the field alignment mode.
8933 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
8936 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
8937 if ( value
!== this.align
) {
8938 // Default to 'left'
8939 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
8943 if ( value
=== 'inline' ) {
8944 this.$body
.append( this.$field
, this.$label
);
8946 this.$body
.append( this.$label
, this.$field
);
8948 // Set classes. The following classes can be used here:
8949 // * oo-ui-fieldLayout-align-left
8950 // * oo-ui-fieldLayout-align-right
8951 // * oo-ui-fieldLayout-align-top
8952 // * oo-ui-fieldLayout-align-inline
8954 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
8956 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
8964 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
8965 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
8966 * is required and is specified before any optional configuration settings.
8968 * Labels can be aligned in one of four ways:
8970 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8971 * A left-alignment is used for forms with many fields.
8972 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8973 * A right-alignment is used for long but familiar forms which users tab through,
8974 * verifying the current field with a quick glance at the label.
8975 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8976 * that users fill out from top to bottom.
8977 * - **inline**: The label is placed after the field-widget and aligned to the left.
8978 * An inline-alignment is best used with checkboxes or radio buttons.
8980 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
8981 * text is specified.
8984 * // Example of an ActionFieldLayout
8985 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
8986 * new OO.ui.TextInputWidget( {
8987 * placeholder: 'Field widget'
8989 * new OO.ui.ButtonWidget( {
8993 * label: 'An ActionFieldLayout. This label is aligned top',
8995 * help: 'This is help text'
8999 * $( 'body' ).append( actionFieldLayout.$element );
9003 * @extends OO.ui.FieldLayout
9006 * @param {OO.ui.Widget} fieldWidget Field widget
9007 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
9009 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
9010 // Allow passing positional parameters inside the config object
9011 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
9012 config
= fieldWidget
;
9013 fieldWidget
= config
.fieldWidget
;
9014 buttonWidget
= config
.buttonWidget
;
9017 // Parent constructor
9018 OO
.ui
.ActionFieldLayout
.parent
.call( this, fieldWidget
, config
);
9021 this.buttonWidget
= buttonWidget
;
9022 this.$button
= $( '<div>' );
9023 this.$input
= $( '<div>' );
9027 .addClass( 'oo-ui-actionFieldLayout' );
9029 .addClass( 'oo-ui-actionFieldLayout-button' )
9030 .append( this.buttonWidget
.$element
);
9032 .addClass( 'oo-ui-actionFieldLayout-input' )
9033 .append( this.fieldWidget
.$element
);
9035 .append( this.$input
, this.$button
);
9040 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
9043 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
9044 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
9045 * configured with a label as well. For more information and examples,
9046 * please see the [OOjs UI documentation on MediaWiki][1].
9049 * // Example of a fieldset layout
9050 * var input1 = new OO.ui.TextInputWidget( {
9051 * placeholder: 'A text input field'
9054 * var input2 = new OO.ui.TextInputWidget( {
9055 * placeholder: 'A text input field'
9058 * var fieldset = new OO.ui.FieldsetLayout( {
9059 * label: 'Example of a fieldset layout'
9062 * fieldset.addItems( [
9063 * new OO.ui.FieldLayout( input1, {
9064 * label: 'Field One'
9066 * new OO.ui.FieldLayout( input2, {
9067 * label: 'Field Two'
9070 * $( 'body' ).append( fieldset.$element );
9072 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9075 * @extends OO.ui.Layout
9076 * @mixins OO.ui.mixin.IconElement
9077 * @mixins OO.ui.mixin.LabelElement
9078 * @mixins OO.ui.mixin.GroupElement
9081 * @param {Object} [config] Configuration options
9082 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
9084 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
9085 // Configuration initialization
9086 config
= config
|| {};
9088 // Parent constructor
9089 OO
.ui
.FieldsetLayout
.parent
.call( this, config
);
9091 // Mixin constructors
9092 OO
.ui
.mixin
.IconElement
.call( this, config
);
9093 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9094 OO
.ui
.mixin
.GroupElement
.call( this, config
);
9096 if ( config
.help
) {
9097 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
9098 classes
: [ 'oo-ui-fieldsetLayout-help' ],
9103 this.popupButtonWidget
.getPopup().$body
.append(
9105 .text( config
.help
)
9106 .addClass( 'oo-ui-fieldsetLayout-help-content' )
9108 this.$help
= this.popupButtonWidget
.$element
;
9110 this.$help
= $( [] );
9115 .addClass( 'oo-ui-fieldsetLayout' )
9116 .prepend( this.$help
, this.$icon
, this.$label
, this.$group
);
9117 if ( Array
.isArray( config
.items
) ) {
9118 this.addItems( config
.items
);
9124 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
9125 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.IconElement
);
9126 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.LabelElement
);
9127 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.GroupElement
);
9130 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
9131 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
9132 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
9133 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9135 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
9136 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
9137 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
9138 * some fancier controls. Some controls have both regular and InputWidget variants, for example
9139 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
9140 * often have simplified APIs to match the capabilities of HTML forms.
9141 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
9143 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
9144 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9147 * // Example of a form layout that wraps a fieldset layout
9148 * var input1 = new OO.ui.TextInputWidget( {
9149 * placeholder: 'Username'
9151 * var input2 = new OO.ui.TextInputWidget( {
9152 * placeholder: 'Password',
9155 * var submit = new OO.ui.ButtonInputWidget( {
9159 * var fieldset = new OO.ui.FieldsetLayout( {
9160 * label: 'A form layout'
9162 * fieldset.addItems( [
9163 * new OO.ui.FieldLayout( input1, {
9164 * label: 'Username',
9167 * new OO.ui.FieldLayout( input2, {
9168 * label: 'Password',
9171 * new OO.ui.FieldLayout( submit )
9173 * var form = new OO.ui.FormLayout( {
9174 * items: [ fieldset ],
9175 * action: '/api/formhandler',
9178 * $( 'body' ).append( form.$element );
9181 * @extends OO.ui.Layout
9182 * @mixins OO.ui.mixin.GroupElement
9185 * @param {Object} [config] Configuration options
9186 * @cfg {string} [method] HTML form `method` attribute
9187 * @cfg {string} [action] HTML form `action` attribute
9188 * @cfg {string} [enctype] HTML form `enctype` attribute
9189 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
9191 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
9192 // Configuration initialization
9193 config
= config
|| {};
9195 // Parent constructor
9196 OO
.ui
.FormLayout
.parent
.call( this, config
);
9198 // Mixin constructors
9199 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
9202 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
9204 // Make sure the action is safe
9205 if ( config
.action
!== undefined && !OO
.ui
.isSafeUrl( config
.action
) ) {
9206 throw new Error( 'Potentially unsafe action provided: ' + config
.action
);
9211 .addClass( 'oo-ui-formLayout' )
9213 method
: config
.method
,
9214 action
: config
.action
,
9215 enctype
: config
.enctype
9217 if ( Array
.isArray( config
.items
) ) {
9218 this.addItems( config
.items
);
9224 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
9225 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.mixin
.GroupElement
);
9230 * A 'submit' event is emitted when the form is submitted.
9235 /* Static Properties */
9237 OO
.ui
.FormLayout
.static.tagName
= 'form';
9242 * Handle form submit events.
9245 * @param {jQuery.Event} e Submit event
9248 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
9249 if ( this.emit( 'submit' ) ) {
9255 * MenuLayouts combine a menu and a content {@link OO.ui.PanelLayout panel}. The menu is positioned relative to the content (after, before, top, or bottom)
9256 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
9259 * var menuLayout = new OO.ui.MenuLayout( {
9262 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9263 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9264 * select = new OO.ui.SelectWidget( {
9266 * new OO.ui.OptionWidget( {
9270 * new OO.ui.OptionWidget( {
9274 * new OO.ui.OptionWidget( {
9278 * new OO.ui.OptionWidget( {
9283 * } ).on( 'select', function ( item ) {
9284 * menuLayout.setMenuPosition( item.getData() );
9287 * menuLayout.$menu.append(
9288 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
9290 * menuLayout.$content.append(
9291 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
9293 * $( 'body' ).append( menuLayout.$element );
9295 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
9296 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
9297 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
9300 * .oo-ui-menuLayout-menu {
9304 * .oo-ui-menuLayout-content {
9312 * @extends OO.ui.Layout
9315 * @param {Object} [config] Configuration options
9316 * @cfg {boolean} [showMenu=true] Show menu
9317 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
9319 OO
.ui
.MenuLayout
= function OoUiMenuLayout( config
) {
9320 // Configuration initialization
9321 config
= $.extend( {
9323 menuPosition
: 'before'
9326 // Parent constructor
9327 OO
.ui
.MenuLayout
.parent
.call( this, config
);
9332 * @property {jQuery}
9334 this.$menu
= $( '<div>' );
9338 * @property {jQuery}
9340 this.$content
= $( '<div>' );
9344 .addClass( 'oo-ui-menuLayout-menu' );
9345 this.$content
.addClass( 'oo-ui-menuLayout-content' );
9347 .addClass( 'oo-ui-menuLayout' )
9348 .append( this.$content
, this.$menu
);
9349 this.setMenuPosition( config
.menuPosition
);
9350 this.toggleMenu( config
.showMenu
);
9355 OO
.inheritClass( OO
.ui
.MenuLayout
, OO
.ui
.Layout
);
9362 * @param {boolean} showMenu Show menu, omit to toggle
9365 OO
.ui
.MenuLayout
.prototype.toggleMenu = function ( showMenu
) {
9366 showMenu
= showMenu
=== undefined ? !this.showMenu
: !!showMenu
;
9368 if ( this.showMenu
!== showMenu
) {
9369 this.showMenu
= showMenu
;
9371 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu
)
9372 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu
);
9379 * Check if menu is visible
9381 * @return {boolean} Menu is visible
9383 OO
.ui
.MenuLayout
.prototype.isMenuVisible = function () {
9384 return this.showMenu
;
9388 * Set menu position.
9390 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
9391 * @throws {Error} If position value is not supported
9394 OO
.ui
.MenuLayout
.prototype.setMenuPosition = function ( position
) {
9395 this.$element
.removeClass( 'oo-ui-menuLayout-' + this.menuPosition
);
9396 this.menuPosition
= position
;
9397 this.$element
.addClass( 'oo-ui-menuLayout-' + position
);
9403 * Get menu position.
9405 * @return {string} Menu position
9407 OO
.ui
.MenuLayout
.prototype.getMenuPosition = function () {
9408 return this.menuPosition
;
9412 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
9413 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
9414 * through the pages and select which one to display. By default, only one page is
9415 * displayed at a time and the outline is hidden. When a user navigates to a new page,
9416 * the booklet layout automatically focuses on the first focusable element, unless the
9417 * default setting is changed. Optionally, booklets can be configured to show
9418 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
9421 * // Example of a BookletLayout that contains two PageLayouts.
9423 * function PageOneLayout( name, config ) {
9424 * PageOneLayout.parent.call( this, name, config );
9425 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
9427 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
9428 * PageOneLayout.prototype.setupOutlineItem = function () {
9429 * this.outlineItem.setLabel( 'Page One' );
9432 * function PageTwoLayout( name, config ) {
9433 * PageTwoLayout.parent.call( this, name, config );
9434 * this.$element.append( '<p>Second page</p>' );
9436 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
9437 * PageTwoLayout.prototype.setupOutlineItem = function () {
9438 * this.outlineItem.setLabel( 'Page Two' );
9441 * var page1 = new PageOneLayout( 'one' ),
9442 * page2 = new PageTwoLayout( 'two' );
9444 * var booklet = new OO.ui.BookletLayout( {
9448 * booklet.addPages ( [ page1, page2 ] );
9449 * $( 'body' ).append( booklet.$element );
9452 * @extends OO.ui.MenuLayout
9455 * @param {Object} [config] Configuration options
9456 * @cfg {boolean} [continuous=false] Show all pages, one after another
9457 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
9458 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
9459 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
9461 OO
.ui
.BookletLayout
= function OoUiBookletLayout( config
) {
9462 // Configuration initialization
9463 config
= config
|| {};
9465 // Parent constructor
9466 OO
.ui
.BookletLayout
.parent
.call( this, config
);
9469 this.currentPageName
= null;
9471 this.ignoreFocus
= false;
9472 this.stackLayout
= new OO
.ui
.StackLayout( { continuous
: !!config
.continuous
} );
9473 this.$content
.append( this.stackLayout
.$element
);
9474 this.autoFocus
= config
.autoFocus
=== undefined || !!config
.autoFocus
;
9475 this.outlineVisible
= false;
9476 this.outlined
= !!config
.outlined
;
9477 if ( this.outlined
) {
9478 this.editable
= !!config
.editable
;
9479 this.outlineControlsWidget
= null;
9480 this.outlineSelectWidget
= new OO
.ui
.OutlineSelectWidget();
9481 this.outlinePanel
= new OO
.ui
.PanelLayout( { scrollable
: true } );
9482 this.$menu
.append( this.outlinePanel
.$element
);
9483 this.outlineVisible
= true;
9484 if ( this.editable
) {
9485 this.outlineControlsWidget
= new OO
.ui
.OutlineControlsWidget(
9486 this.outlineSelectWidget
9490 this.toggleMenu( this.outlined
);
9493 this.stackLayout
.connect( this, { set: 'onStackLayoutSet' } );
9494 if ( this.outlined
) {
9495 this.outlineSelectWidget
.connect( this, { select
: 'onOutlineSelectWidgetSelect' } );
9497 if ( this.autoFocus
) {
9498 // Event 'focus' does not bubble, but 'focusin' does
9499 this.stackLayout
.$element
.on( 'focusin', this.onStackLayoutFocus
.bind( this ) );
9503 this.$element
.addClass( 'oo-ui-bookletLayout' );
9504 this.stackLayout
.$element
.addClass( 'oo-ui-bookletLayout-stackLayout' );
9505 if ( this.outlined
) {
9506 this.outlinePanel
.$element
9507 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
9508 .append( this.outlineSelectWidget
.$element
);
9509 if ( this.editable
) {
9510 this.outlinePanel
.$element
9511 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
9512 .append( this.outlineControlsWidget
.$element
);
9519 OO
.inheritClass( OO
.ui
.BookletLayout
, OO
.ui
.MenuLayout
);
9524 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
9526 * @param {OO.ui.PageLayout} page Current page
9530 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
9533 * @param {OO.ui.PageLayout[]} page Added pages
9534 * @param {number} index Index pages were added at
9538 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
9539 * {@link #removePages removed} from the booklet.
9542 * @param {OO.ui.PageLayout[]} pages Removed pages
9548 * Handle stack layout focus.
9551 * @param {jQuery.Event} e Focusin event
9553 OO
.ui
.BookletLayout
.prototype.onStackLayoutFocus = function ( e
) {
9556 // Find the page that an element was focused within
9557 $target
= $( e
.target
).closest( '.oo-ui-pageLayout' );
9558 for ( name
in this.pages
) {
9559 // Check for page match, exclude current page to find only page changes
9560 if ( this.pages
[ name
].$element
[ 0 ] === $target
[ 0 ] && name
!== this.currentPageName
) {
9561 this.setPage( name
);
9568 * Handle stack layout set events.
9571 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
9573 OO
.ui
.BookletLayout
.prototype.onStackLayoutSet = function ( page
) {
9576 page
.scrollElementIntoView( { complete: function () {
9577 if ( layout
.autoFocus
) {
9585 * Focus the first input in the current page.
9587 * If no page is selected, the first selectable page will be selected.
9588 * If the focus is already in an element on the current page, nothing will happen.
9589 * @param {number} [itemIndex] A specific item to focus on
9591 OO
.ui
.BookletLayout
.prototype.focus = function ( itemIndex
) {
9593 items
= this.stackLayout
.getItems();
9595 if ( itemIndex
!== undefined && items
[ itemIndex
] ) {
9596 page
= items
[ itemIndex
];
9598 page
= this.stackLayout
.getCurrentItem();
9601 if ( !page
&& this.outlined
) {
9602 this.selectFirstSelectablePage();
9603 page
= this.stackLayout
.getCurrentItem();
9608 // Only change the focus if is not already in the current page
9609 if ( !page
.$element
.find( ':focus' ).length
) {
9610 $input
= page
.$element
.find( ':input:first' );
9611 if ( $input
.length
) {
9612 $input
[ 0 ].focus();
9618 * Find the first focusable input in the booklet layout and focus
9621 OO
.ui
.BookletLayout
.prototype.focusFirstFocusable = function () {
9624 items
= this.stackLayout
.getItems(),
9625 checkAndFocus = function () {
9626 if ( OO
.ui
.isFocusableElement( $( this ) ) ) {
9633 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
9637 // Find all potentially focusable elements in the item
9638 // and check if they are focusable
9640 .find( 'input, select, textarea, button, object' )
9641 /* jshint loopfunc:true */
9642 .each( checkAndFocus
);
9647 * Handle outline widget select events.
9650 * @param {OO.ui.OptionWidget|null} item Selected item
9652 OO
.ui
.BookletLayout
.prototype.onOutlineSelectWidgetSelect = function ( item
) {
9654 this.setPage( item
.getData() );
9659 * Check if booklet has an outline.
9661 * @return {boolean} Booklet has an outline
9663 OO
.ui
.BookletLayout
.prototype.isOutlined = function () {
9664 return this.outlined
;
9668 * Check if booklet has editing controls.
9670 * @return {boolean} Booklet is editable
9672 OO
.ui
.BookletLayout
.prototype.isEditable = function () {
9673 return this.editable
;
9677 * Check if booklet has a visible outline.
9679 * @return {boolean} Outline is visible
9681 OO
.ui
.BookletLayout
.prototype.isOutlineVisible = function () {
9682 return this.outlined
&& this.outlineVisible
;
9686 * Hide or show the outline.
9688 * @param {boolean} [show] Show outline, omit to invert current state
9691 OO
.ui
.BookletLayout
.prototype.toggleOutline = function ( show
) {
9692 if ( this.outlined
) {
9693 show
= show
=== undefined ? !this.outlineVisible
: !!show
;
9694 this.outlineVisible
= show
;
9695 this.toggleMenu( show
);
9702 * Get the page closest to the specified page.
9704 * @param {OO.ui.PageLayout} page Page to use as a reference point
9705 * @return {OO.ui.PageLayout|null} Page closest to the specified page
9707 OO
.ui
.BookletLayout
.prototype.getClosestPage = function ( page
) {
9708 var next
, prev
, level
,
9709 pages
= this.stackLayout
.getItems(),
9710 index
= pages
.indexOf( page
);
9712 if ( index
!== -1 ) {
9713 next
= pages
[ index
+ 1 ];
9714 prev
= pages
[ index
- 1 ];
9715 // Prefer adjacent pages at the same level
9716 if ( this.outlined
) {
9717 level
= this.outlineSelectWidget
.getItemFromData( page
.getName() ).getLevel();
9720 level
=== this.outlineSelectWidget
.getItemFromData( prev
.getName() ).getLevel()
9726 level
=== this.outlineSelectWidget
.getItemFromData( next
.getName() ).getLevel()
9732 return prev
|| next
|| null;
9736 * Get the outline widget.
9738 * If the booklet is not outlined, the method will return `null`.
9740 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
9742 OO
.ui
.BookletLayout
.prototype.getOutline = function () {
9743 return this.outlineSelectWidget
;
9747 * Get the outline controls widget.
9749 * If the outline is not editable, the method will return `null`.
9751 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
9753 OO
.ui
.BookletLayout
.prototype.getOutlineControls = function () {
9754 return this.outlineControlsWidget
;
9758 * Get a page by its symbolic name.
9760 * @param {string} name Symbolic name of page
9761 * @return {OO.ui.PageLayout|undefined} Page, if found
9763 OO
.ui
.BookletLayout
.prototype.getPage = function ( name
) {
9764 return this.pages
[ name
];
9768 * Get the current page.
9770 * @return {OO.ui.PageLayout|undefined} Current page, if found
9772 OO
.ui
.BookletLayout
.prototype.getCurrentPage = function () {
9773 var name
= this.getCurrentPageName();
9774 return name
? this.getPage( name
) : undefined;
9778 * Get the symbolic name of the current page.
9780 * @return {string|null} Symbolic name of the current page
9782 OO
.ui
.BookletLayout
.prototype.getCurrentPageName = function () {
9783 return this.currentPageName
;
9787 * Add pages to the booklet layout
9789 * When pages are added with the same names as existing pages, the existing pages will be
9790 * automatically removed before the new pages are added.
9792 * @param {OO.ui.PageLayout[]} pages Pages to add
9793 * @param {number} index Index of the insertion point
9797 OO
.ui
.BookletLayout
.prototype.addPages = function ( pages
, index
) {
9798 var i
, len
, name
, page
, item
, currentIndex
,
9799 stackLayoutPages
= this.stackLayout
.getItems(),
9803 // Remove pages with same names
9804 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
9806 name
= page
.getName();
9808 if ( Object
.prototype.hasOwnProperty
.call( this.pages
, name
) ) {
9809 // Correct the insertion index
9810 currentIndex
= stackLayoutPages
.indexOf( this.pages
[ name
] );
9811 if ( currentIndex
!== -1 && currentIndex
+ 1 < index
) {
9814 remove
.push( this.pages
[ name
] );
9817 if ( remove
.length
) {
9818 this.removePages( remove
);
9822 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
9824 name
= page
.getName();
9825 this.pages
[ page
.getName() ] = page
;
9826 if ( this.outlined
) {
9827 item
= new OO
.ui
.OutlineOptionWidget( { data
: name
} );
9828 page
.setOutlineItem( item
);
9833 if ( this.outlined
&& items
.length
) {
9834 this.outlineSelectWidget
.addItems( items
, index
);
9835 this.selectFirstSelectablePage();
9837 this.stackLayout
.addItems( pages
, index
);
9838 this.emit( 'add', pages
, index
);
9844 * Remove the specified pages from the booklet layout.
9846 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
9848 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
9852 OO
.ui
.BookletLayout
.prototype.removePages = function ( pages
) {
9853 var i
, len
, name
, page
,
9856 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
9858 name
= page
.getName();
9859 delete this.pages
[ name
];
9860 if ( this.outlined
) {
9861 items
.push( this.outlineSelectWidget
.getItemFromData( name
) );
9862 page
.setOutlineItem( null );
9865 if ( this.outlined
&& items
.length
) {
9866 this.outlineSelectWidget
.removeItems( items
);
9867 this.selectFirstSelectablePage();
9869 this.stackLayout
.removeItems( pages
);
9870 this.emit( 'remove', pages
);
9876 * Clear all pages from the booklet layout.
9878 * To remove only a subset of pages from the booklet, use the #removePages method.
9883 OO
.ui
.BookletLayout
.prototype.clearPages = function () {
9885 pages
= this.stackLayout
.getItems();
9888 this.currentPageName
= null;
9889 if ( this.outlined
) {
9890 this.outlineSelectWidget
.clearItems();
9891 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
9892 pages
[ i
].setOutlineItem( null );
9895 this.stackLayout
.clearItems();
9897 this.emit( 'remove', pages
);
9903 * Set the current page by symbolic name.
9906 * @param {string} name Symbolic name of page
9908 OO
.ui
.BookletLayout
.prototype.setPage = function ( name
) {
9911 page
= this.pages
[ name
];
9913 if ( name
!== this.currentPageName
) {
9914 if ( this.outlined
) {
9915 selectedItem
= this.outlineSelectWidget
.getSelectedItem();
9916 if ( selectedItem
&& selectedItem
.getData() !== name
) {
9917 this.outlineSelectWidget
.selectItemByData( name
);
9921 if ( this.currentPageName
&& this.pages
[ this.currentPageName
] ) {
9922 this.pages
[ this.currentPageName
].setActive( false );
9923 // Blur anything focused if the next page doesn't have anything focusable - this
9924 // is not needed if the next page has something focusable because once it is focused
9925 // this blur happens automatically
9926 if ( this.autoFocus
&& !page
.$element
.find( ':input' ).length
) {
9927 $focused
= this.pages
[ this.currentPageName
].$element
.find( ':focus' );
9928 if ( $focused
.length
) {
9929 $focused
[ 0 ].blur();
9933 this.currentPageName
= name
;
9934 this.stackLayout
.setItem( page
);
9935 page
.setActive( true );
9936 this.emit( 'set', page
);
9942 * Select the first selectable page.
9946 OO
.ui
.BookletLayout
.prototype.selectFirstSelectablePage = function () {
9947 if ( !this.outlineSelectWidget
.getSelectedItem() ) {
9948 this.outlineSelectWidget
.selectItem( this.outlineSelectWidget
.getFirstSelectableItem() );
9955 * IndexLayouts contain {@link OO.ui.CardLayout card layouts} as well as
9956 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the cards and
9957 * select which one to display. By default, only one card is displayed at a time. When a user
9958 * navigates to a new card, the index layout automatically focuses on the first focusable element,
9959 * unless the default setting is changed.
9961 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
9964 * // Example of a IndexLayout that contains two CardLayouts.
9966 * function CardOneLayout( name, config ) {
9967 * CardOneLayout.parent.call( this, name, config );
9968 * this.$element.append( '<p>First card</p>' );
9970 * OO.inheritClass( CardOneLayout, OO.ui.CardLayout );
9971 * CardOneLayout.prototype.setupTabItem = function () {
9972 * this.tabItem.setLabel( 'Card One' );
9975 * function CardTwoLayout( name, config ) {
9976 * CardTwoLayout.parent.call( this, name, config );
9977 * this.$element.append( '<p>Second card</p>' );
9979 * OO.inheritClass( CardTwoLayout, OO.ui.CardLayout );
9980 * CardTwoLayout.prototype.setupTabItem = function () {
9981 * this.tabItem.setLabel( 'Card Two' );
9984 * var card1 = new CardOneLayout( 'one' ),
9985 * card2 = new CardTwoLayout( 'two' );
9987 * var index = new OO.ui.IndexLayout();
9989 * index.addCards ( [ card1, card2 ] );
9990 * $( 'body' ).append( index.$element );
9993 * @extends OO.ui.MenuLayout
9996 * @param {Object} [config] Configuration options
9997 * @cfg {boolean} [continuous=false] Show all cards, one after another
9998 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new card is displayed.
10000 OO
.ui
.IndexLayout
= function OoUiIndexLayout( config
) {
10001 // Configuration initialization
10002 config
= $.extend( {}, config
, { menuPosition
: 'top' } );
10004 // Parent constructor
10005 OO
.ui
.IndexLayout
.parent
.call( this, config
);
10008 this.currentCardName
= null;
10010 this.ignoreFocus
= false;
10011 this.stackLayout
= new OO
.ui
.StackLayout( { continuous
: !!config
.continuous
} );
10012 this.$content
.append( this.stackLayout
.$element
);
10013 this.autoFocus
= config
.autoFocus
=== undefined || !!config
.autoFocus
;
10015 this.tabSelectWidget
= new OO
.ui
.TabSelectWidget();
10016 this.tabPanel
= new OO
.ui
.PanelLayout();
10017 this.$menu
.append( this.tabPanel
.$element
);
10019 this.toggleMenu( true );
10022 this.stackLayout
.connect( this, { set: 'onStackLayoutSet' } );
10023 this.tabSelectWidget
.connect( this, { select
: 'onTabSelectWidgetSelect' } );
10024 if ( this.autoFocus
) {
10025 // Event 'focus' does not bubble, but 'focusin' does
10026 this.stackLayout
.$element
.on( 'focusin', this.onStackLayoutFocus
.bind( this ) );
10030 this.$element
.addClass( 'oo-ui-indexLayout' );
10031 this.stackLayout
.$element
.addClass( 'oo-ui-indexLayout-stackLayout' );
10032 this.tabPanel
.$element
10033 .addClass( 'oo-ui-indexLayout-tabPanel' )
10034 .append( this.tabSelectWidget
.$element
);
10039 OO
.inheritClass( OO
.ui
.IndexLayout
, OO
.ui
.MenuLayout
);
10044 * A 'set' event is emitted when a card is {@link #setCard set} to be displayed by the index layout.
10046 * @param {OO.ui.CardLayout} card Current card
10050 * An 'add' event is emitted when cards are {@link #addCards added} to the index layout.
10053 * @param {OO.ui.CardLayout[]} card Added cards
10054 * @param {number} index Index cards were added at
10058 * A 'remove' event is emitted when cards are {@link #clearCards cleared} or
10059 * {@link #removeCards removed} from the index.
10062 * @param {OO.ui.CardLayout[]} cards Removed cards
10068 * Handle stack layout focus.
10071 * @param {jQuery.Event} e Focusin event
10073 OO
.ui
.IndexLayout
.prototype.onStackLayoutFocus = function ( e
) {
10076 // Find the card that an element was focused within
10077 $target
= $( e
.target
).closest( '.oo-ui-cardLayout' );
10078 for ( name
in this.cards
) {
10079 // Check for card match, exclude current card to find only card changes
10080 if ( this.cards
[ name
].$element
[ 0 ] === $target
[ 0 ] && name
!== this.currentCardName
) {
10081 this.setCard( name
);
10088 * Handle stack layout set events.
10091 * @param {OO.ui.PanelLayout|null} card The card panel that is now the current panel
10093 OO
.ui
.IndexLayout
.prototype.onStackLayoutSet = function ( card
) {
10096 card
.scrollElementIntoView( { complete: function () {
10097 if ( layout
.autoFocus
) {
10105 * Focus the first input in the current card.
10107 * If no card is selected, the first selectable card will be selected.
10108 * If the focus is already in an element on the current card, nothing will happen.
10109 * @param {number} [itemIndex] A specific item to focus on
10111 OO
.ui
.IndexLayout
.prototype.focus = function ( itemIndex
) {
10113 items
= this.stackLayout
.getItems();
10115 if ( itemIndex
!== undefined && items
[ itemIndex
] ) {
10116 card
= items
[ itemIndex
];
10118 card
= this.stackLayout
.getCurrentItem();
10122 this.selectFirstSelectableCard();
10123 card
= this.stackLayout
.getCurrentItem();
10128 // Only change the focus if is not already in the current card
10129 if ( !card
.$element
.find( ':focus' ).length
) {
10130 $input
= card
.$element
.find( ':input:first' );
10131 if ( $input
.length
) {
10132 $input
[ 0 ].focus();
10138 * Find the first focusable input in the index layout and focus
10141 OO
.ui
.IndexLayout
.prototype.focusFirstFocusable = function () {
10144 items
= this.stackLayout
.getItems(),
10145 checkAndFocus = function () {
10146 if ( OO
.ui
.isFocusableElement( $( this ) ) ) {
10153 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
10157 // Find all potentially focusable elements in the item
10158 // and check if they are focusable
10159 items
[ i
].$element
10160 .find( 'input, select, textarea, button, object' )
10161 .each( checkAndFocus
);
10166 * Handle tab widget select events.
10169 * @param {OO.ui.OptionWidget|null} item Selected item
10171 OO
.ui
.IndexLayout
.prototype.onTabSelectWidgetSelect = function ( item
) {
10173 this.setCard( item
.getData() );
10178 * Get the card closest to the specified card.
10180 * @param {OO.ui.CardLayout} card Card to use as a reference point
10181 * @return {OO.ui.CardLayout|null} Card closest to the specified card
10183 OO
.ui
.IndexLayout
.prototype.getClosestCard = function ( card
) {
10184 var next
, prev
, level
,
10185 cards
= this.stackLayout
.getItems(),
10186 index
= cards
.indexOf( card
);
10188 if ( index
!== -1 ) {
10189 next
= cards
[ index
+ 1 ];
10190 prev
= cards
[ index
- 1 ];
10191 // Prefer adjacent cards at the same level
10192 level
= this.tabSelectWidget
.getItemFromData( card
.getName() ).getLevel();
10195 level
=== this.tabSelectWidget
.getItemFromData( prev
.getName() ).getLevel()
10201 level
=== this.tabSelectWidget
.getItemFromData( next
.getName() ).getLevel()
10206 return prev
|| next
|| null;
10210 * Get the tabs widget.
10212 * @return {OO.ui.TabSelectWidget} Tabs widget
10214 OO
.ui
.IndexLayout
.prototype.getTabs = function () {
10215 return this.tabSelectWidget
;
10219 * Get a card by its symbolic name.
10221 * @param {string} name Symbolic name of card
10222 * @return {OO.ui.CardLayout|undefined} Card, if found
10224 OO
.ui
.IndexLayout
.prototype.getCard = function ( name
) {
10225 return this.cards
[ name
];
10229 * Get the current card.
10231 * @return {OO.ui.CardLayout|undefined} Current card, if found
10233 OO
.ui
.IndexLayout
.prototype.getCurrentCard = function () {
10234 var name
= this.getCurrentCardName();
10235 return name
? this.getCard( name
) : undefined;
10239 * Get the symbolic name of the current card.
10241 * @return {string|null} Symbolic name of the current card
10243 OO
.ui
.IndexLayout
.prototype.getCurrentCardName = function () {
10244 return this.currentCardName
;
10248 * Add cards to the index layout
10250 * When cards are added with the same names as existing cards, the existing cards will be
10251 * automatically removed before the new cards are added.
10253 * @param {OO.ui.CardLayout[]} cards Cards to add
10254 * @param {number} index Index of the insertion point
10258 OO
.ui
.IndexLayout
.prototype.addCards = function ( cards
, index
) {
10259 var i
, len
, name
, card
, item
, currentIndex
,
10260 stackLayoutCards
= this.stackLayout
.getItems(),
10264 // Remove cards with same names
10265 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10267 name
= card
.getName();
10269 if ( Object
.prototype.hasOwnProperty
.call( this.cards
, name
) ) {
10270 // Correct the insertion index
10271 currentIndex
= stackLayoutCards
.indexOf( this.cards
[ name
] );
10272 if ( currentIndex
!== -1 && currentIndex
+ 1 < index
) {
10275 remove
.push( this.cards
[ name
] );
10278 if ( remove
.length
) {
10279 this.removeCards( remove
);
10283 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10285 name
= card
.getName();
10286 this.cards
[ card
.getName() ] = card
;
10287 item
= new OO
.ui
.TabOptionWidget( { data
: name
} );
10288 card
.setTabItem( item
);
10289 items
.push( item
);
10292 if ( items
.length
) {
10293 this.tabSelectWidget
.addItems( items
, index
);
10294 this.selectFirstSelectableCard();
10296 this.stackLayout
.addItems( cards
, index
);
10297 this.emit( 'add', cards
, index
);
10303 * Remove the specified cards from the index layout.
10305 * To remove all cards from the index, you may wish to use the #clearCards method instead.
10307 * @param {OO.ui.CardLayout[]} cards An array of cards to remove
10311 OO
.ui
.IndexLayout
.prototype.removeCards = function ( cards
) {
10312 var i
, len
, name
, card
,
10315 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10317 name
= card
.getName();
10318 delete this.cards
[ name
];
10319 items
.push( this.tabSelectWidget
.getItemFromData( name
) );
10320 card
.setTabItem( null );
10322 if ( items
.length
) {
10323 this.tabSelectWidget
.removeItems( items
);
10324 this.selectFirstSelectableCard();
10326 this.stackLayout
.removeItems( cards
);
10327 this.emit( 'remove', cards
);
10333 * Clear all cards from the index layout.
10335 * To remove only a subset of cards from the index, use the #removeCards method.
10340 OO
.ui
.IndexLayout
.prototype.clearCards = function () {
10342 cards
= this.stackLayout
.getItems();
10345 this.currentCardName
= null;
10346 this.tabSelectWidget
.clearItems();
10347 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10348 cards
[ i
].setTabItem( null );
10350 this.stackLayout
.clearItems();
10352 this.emit( 'remove', cards
);
10358 * Set the current card by symbolic name.
10361 * @param {string} name Symbolic name of card
10363 OO
.ui
.IndexLayout
.prototype.setCard = function ( name
) {
10366 card
= this.cards
[ name
];
10368 if ( name
!== this.currentCardName
) {
10369 selectedItem
= this.tabSelectWidget
.getSelectedItem();
10370 if ( selectedItem
&& selectedItem
.getData() !== name
) {
10371 this.tabSelectWidget
.selectItemByData( name
);
10374 if ( this.currentCardName
&& this.cards
[ this.currentCardName
] ) {
10375 this.cards
[ this.currentCardName
].setActive( false );
10376 // Blur anything focused if the next card doesn't have anything focusable - this
10377 // is not needed if the next card has something focusable because once it is focused
10378 // this blur happens automatically
10379 if ( this.autoFocus
&& !card
.$element
.find( ':input' ).length
) {
10380 $focused
= this.cards
[ this.currentCardName
].$element
.find( ':focus' );
10381 if ( $focused
.length
) {
10382 $focused
[ 0 ].blur();
10386 this.currentCardName
= name
;
10387 this.stackLayout
.setItem( card
);
10388 card
.setActive( true );
10389 this.emit( 'set', card
);
10395 * Select the first selectable card.
10399 OO
.ui
.IndexLayout
.prototype.selectFirstSelectableCard = function () {
10400 if ( !this.tabSelectWidget
.getSelectedItem() ) {
10401 this.tabSelectWidget
.selectItem( this.tabSelectWidget
.getFirstSelectableItem() );
10408 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
10409 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
10412 * // Example of a panel layout
10413 * var panel = new OO.ui.PanelLayout( {
10417 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
10419 * $( 'body' ).append( panel.$element );
10422 * @extends OO.ui.Layout
10425 * @param {Object} [config] Configuration options
10426 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
10427 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
10428 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
10429 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
10431 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
10432 // Configuration initialization
10433 config
= $.extend( {
10440 // Parent constructor
10441 OO
.ui
.PanelLayout
.parent
.call( this, config
);
10444 this.$element
.addClass( 'oo-ui-panelLayout' );
10445 if ( config
.scrollable
) {
10446 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
10448 if ( config
.padded
) {
10449 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
10451 if ( config
.expanded
) {
10452 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
10454 if ( config
.framed
) {
10455 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
10461 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
10464 * CardLayouts are used within {@link OO.ui.IndexLayout index layouts} to create cards that users can select and display
10465 * from the index's optional {@link OO.ui.TabSelectWidget tab} navigation. Cards are usually not instantiated directly,
10466 * rather extended to include the required content and functionality.
10468 * Each card must have a unique symbolic name, which is passed to the constructor. In addition, the card's tab
10469 * item is customized (with a label) using the #setupTabItem method. See
10470 * {@link OO.ui.IndexLayout IndexLayout} for an example.
10473 * @extends OO.ui.PanelLayout
10476 * @param {string} name Unique symbolic name of card
10477 * @param {Object} [config] Configuration options
10479 OO
.ui
.CardLayout
= function OoUiCardLayout( name
, config
) {
10480 // Allow passing positional parameters inside the config object
10481 if ( OO
.isPlainObject( name
) && config
=== undefined ) {
10483 name
= config
.name
;
10486 // Configuration initialization
10487 config
= $.extend( { scrollable
: true }, config
);
10489 // Parent constructor
10490 OO
.ui
.CardLayout
.parent
.call( this, config
);
10494 this.tabItem
= null;
10495 this.active
= false;
10498 this.$element
.addClass( 'oo-ui-cardLayout' );
10503 OO
.inheritClass( OO
.ui
.CardLayout
, OO
.ui
.PanelLayout
);
10508 * An 'active' event is emitted when the card becomes active. Cards become active when they are
10509 * shown in a index layout that is configured to display only one card at a time.
10512 * @param {boolean} active Card is active
10518 * Get the symbolic name of the card.
10520 * @return {string} Symbolic name of card
10522 OO
.ui
.CardLayout
.prototype.getName = function () {
10527 * Check if card is active.
10529 * Cards become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to display
10530 * only one card at a time. Additional CSS is applied to the card's tab item to reflect the active state.
10532 * @return {boolean} Card is active
10534 OO
.ui
.CardLayout
.prototype.isActive = function () {
10535 return this.active
;
10541 * The tab item allows users to access the card from the index's tab
10542 * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
10544 * @return {OO.ui.TabOptionWidget|null} Tab option widget
10546 OO
.ui
.CardLayout
.prototype.getTabItem = function () {
10547 return this.tabItem
;
10551 * Set or unset the tab item.
10553 * Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
10554 * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
10555 * level), use #setupTabItem instead of this method.
10557 * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
10560 OO
.ui
.CardLayout
.prototype.setTabItem = function ( tabItem
) {
10561 this.tabItem
= tabItem
|| null;
10563 this.setupTabItem();
10569 * Set up the tab item.
10571 * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
10572 * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
10573 * the #setTabItem method instead.
10575 * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
10578 OO
.ui
.CardLayout
.prototype.setupTabItem = function () {
10583 * Set the card to its 'active' state.
10585 * Cards become active when they are shown in a index layout that is configured to display only one card at a time. Additional
10586 * CSS is applied to the tab item to reflect the card's active state. Outside of the index
10587 * context, setting the active state on a card does nothing.
10589 * @param {boolean} value Card is active
10592 OO
.ui
.CardLayout
.prototype.setActive = function ( active
) {
10595 if ( active
!== this.active
) {
10596 this.active
= active
;
10597 this.$element
.toggleClass( 'oo-ui-cardLayout-active', this.active
);
10598 this.emit( 'active', this.active
);
10603 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
10604 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
10605 * rather extended to include the required content and functionality.
10607 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
10608 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
10609 * {@link OO.ui.BookletLayout BookletLayout} for an example.
10612 * @extends OO.ui.PanelLayout
10615 * @param {string} name Unique symbolic name of page
10616 * @param {Object} [config] Configuration options
10618 OO
.ui
.PageLayout
= function OoUiPageLayout( name
, config
) {
10619 // Allow passing positional parameters inside the config object
10620 if ( OO
.isPlainObject( name
) && config
=== undefined ) {
10622 name
= config
.name
;
10625 // Configuration initialization
10626 config
= $.extend( { scrollable
: true }, config
);
10628 // Parent constructor
10629 OO
.ui
.PageLayout
.parent
.call( this, config
);
10633 this.outlineItem
= null;
10634 this.active
= false;
10637 this.$element
.addClass( 'oo-ui-pageLayout' );
10642 OO
.inheritClass( OO
.ui
.PageLayout
, OO
.ui
.PanelLayout
);
10647 * An 'active' event is emitted when the page becomes active. Pages become active when they are
10648 * shown in a booklet layout that is configured to display only one page at a time.
10651 * @param {boolean} active Page is active
10657 * Get the symbolic name of the page.
10659 * @return {string} Symbolic name of page
10661 OO
.ui
.PageLayout
.prototype.getName = function () {
10666 * Check if page is active.
10668 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
10669 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
10671 * @return {boolean} Page is active
10673 OO
.ui
.PageLayout
.prototype.isActive = function () {
10674 return this.active
;
10678 * Get outline item.
10680 * The outline item allows users to access the page from the booklet's outline
10681 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
10683 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
10685 OO
.ui
.PageLayout
.prototype.getOutlineItem = function () {
10686 return this.outlineItem
;
10690 * Set or unset the outline item.
10692 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
10693 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
10694 * level), use #setupOutlineItem instead of this method.
10696 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
10699 OO
.ui
.PageLayout
.prototype.setOutlineItem = function ( outlineItem
) {
10700 this.outlineItem
= outlineItem
|| null;
10701 if ( outlineItem
) {
10702 this.setupOutlineItem();
10708 * Set up the outline item.
10710 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
10711 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
10712 * the #setOutlineItem method instead.
10714 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
10717 OO
.ui
.PageLayout
.prototype.setupOutlineItem = function () {
10722 * Set the page to its 'active' state.
10724 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
10725 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
10726 * context, setting the active state on a page does nothing.
10728 * @param {boolean} value Page is active
10731 OO
.ui
.PageLayout
.prototype.setActive = function ( active
) {
10734 if ( active
!== this.active
) {
10735 this.active
= active
;
10736 this.$element
.toggleClass( 'oo-ui-pageLayout-active', active
);
10737 this.emit( 'active', this.active
);
10742 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
10743 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
10744 * by setting the #continuous option to 'true'.
10747 * // A stack layout with two panels, configured to be displayed continously
10748 * var myStack = new OO.ui.StackLayout( {
10750 * new OO.ui.PanelLayout( {
10751 * $content: $( '<p>Panel One</p>' ),
10755 * new OO.ui.PanelLayout( {
10756 * $content: $( '<p>Panel Two</p>' ),
10763 * $( 'body' ).append( myStack.$element );
10766 * @extends OO.ui.PanelLayout
10767 * @mixins OO.ui.mixin.GroupElement
10770 * @param {Object} [config] Configuration options
10771 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
10772 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
10774 OO
.ui
.StackLayout
= function OoUiStackLayout( config
) {
10775 // Configuration initialization
10776 config
= $.extend( { scrollable
: true }, config
);
10778 // Parent constructor
10779 OO
.ui
.StackLayout
.parent
.call( this, config
);
10781 // Mixin constructors
10782 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
10785 this.currentItem
= null;
10786 this.continuous
= !!config
.continuous
;
10789 this.$element
.addClass( 'oo-ui-stackLayout' );
10790 if ( this.continuous
) {
10791 this.$element
.addClass( 'oo-ui-stackLayout-continuous' );
10793 if ( Array
.isArray( config
.items
) ) {
10794 this.addItems( config
.items
);
10800 OO
.inheritClass( OO
.ui
.StackLayout
, OO
.ui
.PanelLayout
);
10801 OO
.mixinClass( OO
.ui
.StackLayout
, OO
.ui
.mixin
.GroupElement
);
10806 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
10807 * {@link #clearItems cleared} or {@link #setItem displayed}.
10810 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
10816 * Get the current panel.
10818 * @return {OO.ui.Layout|null}
10820 OO
.ui
.StackLayout
.prototype.getCurrentItem = function () {
10821 return this.currentItem
;
10825 * Unset the current item.
10828 * @param {OO.ui.StackLayout} layout
10831 OO
.ui
.StackLayout
.prototype.unsetCurrentItem = function () {
10832 var prevItem
= this.currentItem
;
10833 if ( prevItem
=== null ) {
10837 this.currentItem
= null;
10838 this.emit( 'set', null );
10842 * Add panel layouts to the stack layout.
10844 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
10845 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
10848 * @param {OO.ui.Layout[]} items Panels to add
10849 * @param {number} [index] Index of the insertion point
10852 OO
.ui
.StackLayout
.prototype.addItems = function ( items
, index
) {
10853 // Update the visibility
10854 this.updateHiddenState( items
, this.currentItem
);
10857 OO
.ui
.mixin
.GroupElement
.prototype.addItems
.call( this, items
, index
);
10859 if ( !this.currentItem
&& items
.length
) {
10860 this.setItem( items
[ 0 ] );
10867 * Remove the specified panels from the stack layout.
10869 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
10870 * you may wish to use the #clearItems method instead.
10872 * @param {OO.ui.Layout[]} items Panels to remove
10876 OO
.ui
.StackLayout
.prototype.removeItems = function ( items
) {
10878 OO
.ui
.mixin
.GroupElement
.prototype.removeItems
.call( this, items
);
10880 if ( items
.indexOf( this.currentItem
) !== -1 ) {
10881 if ( this.items
.length
) {
10882 this.setItem( this.items
[ 0 ] );
10884 this.unsetCurrentItem();
10892 * Clear all panels from the stack layout.
10894 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
10895 * a subset of panels, use the #removeItems method.
10900 OO
.ui
.StackLayout
.prototype.clearItems = function () {
10901 this.unsetCurrentItem();
10902 OO
.ui
.mixin
.GroupElement
.prototype.clearItems
.call( this );
10908 * Show the specified panel.
10910 * If another panel is currently displayed, it will be hidden.
10912 * @param {OO.ui.Layout} item Panel to show
10916 OO
.ui
.StackLayout
.prototype.setItem = function ( item
) {
10917 if ( item
!== this.currentItem
) {
10918 this.updateHiddenState( this.items
, item
);
10920 if ( this.items
.indexOf( item
) !== -1 ) {
10921 this.currentItem
= item
;
10922 this.emit( 'set', item
);
10924 this.unsetCurrentItem();
10932 * Update the visibility of all items in case of non-continuous view.
10934 * Ensure all items are hidden except for the selected one.
10935 * This method does nothing when the stack is continuous.
10938 * @param {OO.ui.Layout[]} items Item list iterate over
10939 * @param {OO.ui.Layout} [selectedItem] Selected item to show
10941 OO
.ui
.StackLayout
.prototype.updateHiddenState = function ( items
, selectedItem
) {
10944 if ( !this.continuous
) {
10945 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
10946 if ( !selectedItem
|| selectedItem
!== items
[ i
] ) {
10947 items
[ i
].$element
.addClass( 'oo-ui-element-hidden' );
10950 if ( selectedItem
) {
10951 selectedItem
.$element
.removeClass( 'oo-ui-element-hidden' );
10957 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
10958 * items), with small margins between them. Convenient when you need to put a number of block-level
10959 * widgets on a single line next to each other.
10961 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
10964 * // HorizontalLayout with a text input and a label
10965 * var layout = new OO.ui.HorizontalLayout( {
10967 * new OO.ui.LabelWidget( { label: 'Label' } ),
10968 * new OO.ui.TextInputWidget( { value: 'Text' } )
10971 * $( 'body' ).append( layout.$element );
10974 * @extends OO.ui.Layout
10975 * @mixins OO.ui.mixin.GroupElement
10978 * @param {Object} [config] Configuration options
10979 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
10981 OO
.ui
.HorizontalLayout
= function OoUiHorizontalLayout( config
) {
10982 // Configuration initialization
10983 config
= config
|| {};
10985 // Parent constructor
10986 OO
.ui
.HorizontalLayout
.parent
.call( this, config
);
10988 // Mixin constructors
10989 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
10992 this.$element
.addClass( 'oo-ui-horizontalLayout' );
10993 if ( Array
.isArray( config
.items
) ) {
10994 this.addItems( config
.items
);
11000 OO
.inheritClass( OO
.ui
.HorizontalLayout
, OO
.ui
.Layout
);
11001 OO
.mixinClass( OO
.ui
.HorizontalLayout
, OO
.ui
.mixin
.GroupElement
);
11004 * BarToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11005 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11006 * and {@link OO.ui.ListToolGroup ListToolGroup}). The {@link OO.ui.Tool tools} in a BarToolGroup are
11007 * displayed by icon in a single row. The title of the tool is displayed when users move the mouse over
11010 * BarToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar is
11014 * // Example of a BarToolGroup with two tools
11015 * var toolFactory = new OO.ui.ToolFactory();
11016 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11017 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11019 * // We will be placing status text in this element when tools are used
11020 * var $area = $( '<p>' ).text( 'Example of a BarToolGroup with two tools.' );
11022 * // Define the tools that we're going to place in our toolbar
11024 * // Create a class inheriting from OO.ui.Tool
11025 * function PictureTool() {
11026 * PictureTool.parent.apply( this, arguments );
11028 * OO.inheritClass( PictureTool, OO.ui.Tool );
11029 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
11030 * // of 'icon' and 'title' (displayed icon and text).
11031 * PictureTool.static.name = 'picture';
11032 * PictureTool.static.icon = 'picture';
11033 * PictureTool.static.title = 'Insert picture';
11034 * // Defines the action that will happen when this tool is selected (clicked).
11035 * PictureTool.prototype.onSelect = function () {
11036 * $area.text( 'Picture tool clicked!' );
11037 * // Never display this tool as "active" (selected).
11038 * this.setActive( false );
11040 * // Make this tool available in our toolFactory and thus our toolbar
11041 * toolFactory.register( PictureTool );
11043 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
11044 * // little popup window (a PopupWidget).
11045 * function HelpTool( toolGroup, config ) {
11046 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11051 * this.popup.$body.append( '<p>I am helpful!</p>' );
11053 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11054 * HelpTool.static.name = 'help';
11055 * HelpTool.static.icon = 'help';
11056 * HelpTool.static.title = 'Help';
11057 * toolFactory.register( HelpTool );
11059 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11060 * // used once (but not all defined tools must be used).
11063 * // 'bar' tool groups display tools by icon only
11065 * include: [ 'picture', 'help' ]
11069 * // Create some UI around the toolbar and place it in the document
11070 * var frame = new OO.ui.PanelLayout( {
11074 * var contentFrame = new OO.ui.PanelLayout( {
11078 * frame.$element.append(
11079 * toolbar.$element,
11080 * contentFrame.$element.append( $area )
11082 * $( 'body' ).append( frame.$element );
11084 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11086 * toolbar.initialize();
11088 * For more information about how to add tools to a bar tool group, please see {@link OO.ui.ToolGroup toolgroup}.
11089 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11091 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11094 * @extends OO.ui.ToolGroup
11097 * @param {OO.ui.Toolbar} toolbar
11098 * @param {Object} [config] Configuration options
11100 OO
.ui
.BarToolGroup
= function OoUiBarToolGroup( toolbar
, config
) {
11101 // Allow passing positional parameters inside the config object
11102 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11104 toolbar
= config
.toolbar
;
11107 // Parent constructor
11108 OO
.ui
.BarToolGroup
.parent
.call( this, toolbar
, config
);
11111 this.$element
.addClass( 'oo-ui-barToolGroup' );
11116 OO
.inheritClass( OO
.ui
.BarToolGroup
, OO
.ui
.ToolGroup
);
11118 /* Static Properties */
11120 OO
.ui
.BarToolGroup
.static.titleTooltips
= true;
11122 OO
.ui
.BarToolGroup
.static.accelTooltips
= true;
11124 OO
.ui
.BarToolGroup
.static.name
= 'bar';
11127 * PopupToolGroup is an abstract base class used by both {@link OO.ui.MenuToolGroup MenuToolGroup}
11128 * and {@link OO.ui.ListToolGroup ListToolGroup} to provide a popup--an overlaid menu or list of tools with an
11129 * optional icon and label. This class can be used for other base classes that also use this functionality.
11133 * @extends OO.ui.ToolGroup
11134 * @mixins OO.ui.mixin.IconElement
11135 * @mixins OO.ui.mixin.IndicatorElement
11136 * @mixins OO.ui.mixin.LabelElement
11137 * @mixins OO.ui.mixin.TitledElement
11138 * @mixins OO.ui.mixin.ClippableElement
11139 * @mixins OO.ui.mixin.TabIndexedElement
11142 * @param {OO.ui.Toolbar} toolbar
11143 * @param {Object} [config] Configuration options
11144 * @cfg {string} [header] Text to display at the top of the popup
11146 OO
.ui
.PopupToolGroup
= function OoUiPopupToolGroup( toolbar
, config
) {
11147 // Allow passing positional parameters inside the config object
11148 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11150 toolbar
= config
.toolbar
;
11153 // Configuration initialization
11154 config
= config
|| {};
11156 // Parent constructor
11157 OO
.ui
.PopupToolGroup
.parent
.call( this, toolbar
, config
);
11160 this.active
= false;
11161 this.dragging
= false;
11162 this.onBlurHandler
= this.onBlur
.bind( this );
11163 this.$handle
= $( '<span>' );
11165 // Mixin constructors
11166 OO
.ui
.mixin
.IconElement
.call( this, config
);
11167 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
11168 OO
.ui
.mixin
.LabelElement
.call( this, config
);
11169 OO
.ui
.mixin
.TitledElement
.call( this, config
);
11170 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
11171 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
11175 keydown
: this.onHandleMouseKeyDown
.bind( this ),
11176 keyup
: this.onHandleMouseKeyUp
.bind( this ),
11177 mousedown
: this.onHandleMouseKeyDown
.bind( this ),
11178 mouseup
: this.onHandleMouseKeyUp
.bind( this )
11183 .addClass( 'oo-ui-popupToolGroup-handle' )
11184 .append( this.$icon
, this.$label
, this.$indicator
);
11185 // If the pop-up should have a header, add it to the top of the toolGroup.
11186 // Note: If this feature is useful for other widgets, we could abstract it into an
11187 // OO.ui.HeaderedElement mixin constructor.
11188 if ( config
.header
!== undefined ) {
11190 .prepend( $( '<span>' )
11191 .addClass( 'oo-ui-popupToolGroup-header' )
11192 .text( config
.header
)
11196 .addClass( 'oo-ui-popupToolGroup' )
11197 .prepend( this.$handle
);
11202 OO
.inheritClass( OO
.ui
.PopupToolGroup
, OO
.ui
.ToolGroup
);
11203 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.IconElement
);
11204 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.IndicatorElement
);
11205 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.LabelElement
);
11206 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.TitledElement
);
11207 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.ClippableElement
);
11208 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.TabIndexedElement
);
11215 OO
.ui
.PopupToolGroup
.prototype.setDisabled = function () {
11217 OO
.ui
.PopupToolGroup
.parent
.prototype.setDisabled
.apply( this, arguments
);
11219 if ( this.isDisabled() && this.isElementAttached() ) {
11220 this.setActive( false );
11225 * Handle focus being lost.
11227 * The event is actually generated from a mouseup/keyup, so it is not a normal blur event object.
11230 * @param {jQuery.Event} e Mouse up or key up event
11232 OO
.ui
.PopupToolGroup
.prototype.onBlur = function ( e
) {
11233 // Only deactivate when clicking outside the dropdown element
11234 if ( $( e
.target
).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element
[ 0 ] ) {
11235 this.setActive( false );
11242 OO
.ui
.PopupToolGroup
.prototype.onMouseKeyUp = function ( e
) {
11243 // Only close toolgroup when a tool was actually selected
11245 !this.isDisabled() && this.pressed
&& this.pressed
=== this.getTargetTool( e
) &&
11246 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11248 this.setActive( false );
11250 return OO
.ui
.PopupToolGroup
.parent
.prototype.onMouseKeyUp
.call( this, e
);
11254 * Handle mouse up and key up events.
11257 * @param {jQuery.Event} e Mouse up or key up event
11259 OO
.ui
.PopupToolGroup
.prototype.onHandleMouseKeyUp = function ( e
) {
11261 !this.isDisabled() &&
11262 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11269 * Handle mouse down and key down events.
11272 * @param {jQuery.Event} e Mouse down or key down event
11274 OO
.ui
.PopupToolGroup
.prototype.onHandleMouseKeyDown = function ( e
) {
11276 !this.isDisabled() &&
11277 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11279 this.setActive( !this.active
);
11285 * Switch into 'active' mode.
11287 * When active, the popup is visible. A mouseup event anywhere in the document will trigger
11290 OO
.ui
.PopupToolGroup
.prototype.setActive = function ( value
) {
11291 var containerWidth
, containerLeft
;
11293 if ( this.active
!== value
) {
11294 this.active
= value
;
11296 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler
);
11297 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler
);
11299 this.$clippable
.css( 'left', '' );
11300 // Try anchoring the popup to the left first
11301 this.$element
.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
11302 this.toggleClipping( true );
11303 if ( this.isClippedHorizontally() ) {
11304 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
11305 this.toggleClipping( false );
11307 .removeClass( 'oo-ui-popupToolGroup-left' )
11308 .addClass( 'oo-ui-popupToolGroup-right' );
11309 this.toggleClipping( true );
11311 if ( this.isClippedHorizontally() ) {
11312 // Anchoring to the right also caused the popup to clip, so just make it fill the container
11313 containerWidth
= this.$clippableContainer
.width();
11314 containerLeft
= this.$clippableContainer
.offset().left
;
11316 this.toggleClipping( false );
11317 this.$element
.removeClass( 'oo-ui-popupToolGroup-right' );
11319 this.$clippable
.css( {
11320 left
: -( this.$element
.offset().left
- containerLeft
),
11321 width
: containerWidth
11325 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler
);
11326 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler
);
11327 this.$element
.removeClass(
11328 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
11330 this.toggleClipping( false );
11336 * ListToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11337 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11338 * and {@link OO.ui.BarToolGroup BarToolGroup}). The {@link OO.ui.Tool tools} in a ListToolGroup are displayed
11339 * by label in a dropdown menu. The title of the tool is used as the label text. The menu itself can be configured
11340 * with a label, icon, indicator, header, and title.
11342 * ListToolGroups can be configured to be expanded and collapsed. Collapsed lists will have a ‘More’ option that
11343 * users can select to see the full list of tools. If a collapsed toolgroup is expanded, a ‘Fewer’ option permits
11344 * users to collapse the list again.
11346 * ListToolGroups are created by a {@link OO.ui.ToolGroupFactory toolgroup factory} when the toolbar is set up. The factory
11347 * requires the ListToolGroup's symbolic name, 'list', which is specified along with the other configurations. For more
11348 * information about how to add tools to a ListToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11351 * // Example of a ListToolGroup
11352 * var toolFactory = new OO.ui.ToolFactory();
11353 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11354 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11356 * // Configure and register two tools
11357 * function SettingsTool() {
11358 * SettingsTool.parent.apply( this, arguments );
11360 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11361 * SettingsTool.static.name = 'settings';
11362 * SettingsTool.static.icon = 'settings';
11363 * SettingsTool.static.title = 'Change settings';
11364 * SettingsTool.prototype.onSelect = function () {
11365 * this.setActive( false );
11367 * toolFactory.register( SettingsTool );
11368 * // Register two more tools, nothing interesting here
11369 * function StuffTool() {
11370 * StuffTool.parent.apply( this, arguments );
11372 * OO.inheritClass( StuffTool, OO.ui.Tool );
11373 * StuffTool.static.name = 'stuff';
11374 * StuffTool.static.icon = 'ellipsis';
11375 * StuffTool.static.title = 'Change the world';
11376 * StuffTool.prototype.onSelect = function () {
11377 * this.setActive( false );
11379 * toolFactory.register( StuffTool );
11382 * // Configurations for list toolgroup.
11384 * label: 'ListToolGroup',
11385 * indicator: 'down',
11387 * title: 'This is the title, displayed when user moves the mouse over the list toolgroup',
11388 * header: 'This is the header',
11389 * include: [ 'settings', 'stuff' ],
11390 * allowCollapse: ['stuff']
11394 * // Create some UI around the toolbar and place it in the document
11395 * var frame = new OO.ui.PanelLayout( {
11399 * frame.$element.append(
11402 * $( 'body' ).append( frame.$element );
11403 * // Build the toolbar. This must be done after the toolbar has been appended to the document.
11404 * toolbar.initialize();
11406 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11408 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11411 * @extends OO.ui.PopupToolGroup
11414 * @param {OO.ui.Toolbar} toolbar
11415 * @param {Object} [config] Configuration options
11416 * @cfg {Array} [allowCollapse] Allow the specified tools to be collapsed. By default, collapsible tools
11417 * will only be displayed if users click the ‘More’ option displayed at the bottom of the list. If
11418 * the list is expanded, a ‘Fewer’ option permits users to collapse the list again. Any tools that
11419 * are included in the toolgroup, but are not designated as collapsible, will always be displayed.
11420 * To open a collapsible list in its expanded state, set #expanded to 'true'.
11421 * @cfg {Array} [forceExpand] Expand the specified tools. All other tools will be designated as collapsible.
11422 * Unless #expanded is set to true, the collapsible tools will be collapsed when the list is first opened.
11423 * @cfg {boolean} [expanded=false] Expand collapsible tools. This config is only relevant if tools have
11424 * been designated as collapsible. When expanded is set to true, all tools in the group will be displayed
11425 * when the list is first opened. Users can collapse the list with a ‘Fewer’ option at the bottom.
11427 OO
.ui
.ListToolGroup
= function OoUiListToolGroup( toolbar
, config
) {
11428 // Allow passing positional parameters inside the config object
11429 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11431 toolbar
= config
.toolbar
;
11434 // Configuration initialization
11435 config
= config
|| {};
11437 // Properties (must be set before parent constructor, which calls #populate)
11438 this.allowCollapse
= config
.allowCollapse
;
11439 this.forceExpand
= config
.forceExpand
;
11440 this.expanded
= config
.expanded
!== undefined ? config
.expanded
: false;
11441 this.collapsibleTools
= [];
11443 // Parent constructor
11444 OO
.ui
.ListToolGroup
.parent
.call( this, toolbar
, config
);
11447 this.$element
.addClass( 'oo-ui-listToolGroup' );
11452 OO
.inheritClass( OO
.ui
.ListToolGroup
, OO
.ui
.PopupToolGroup
);
11454 /* Static Properties */
11456 OO
.ui
.ListToolGroup
.static.name
= 'list';
11463 OO
.ui
.ListToolGroup
.prototype.populate = function () {
11464 var i
, len
, allowCollapse
= [];
11466 OO
.ui
.ListToolGroup
.parent
.prototype.populate
.call( this );
11468 // Update the list of collapsible tools
11469 if ( this.allowCollapse
!== undefined ) {
11470 allowCollapse
= this.allowCollapse
;
11471 } else if ( this.forceExpand
!== undefined ) {
11472 allowCollapse
= OO
.simpleArrayDifference( Object
.keys( this.tools
), this.forceExpand
);
11475 this.collapsibleTools
= [];
11476 for ( i
= 0, len
= allowCollapse
.length
; i
< len
; i
++ ) {
11477 if ( this.tools
[ allowCollapse
[ i
] ] !== undefined ) {
11478 this.collapsibleTools
.push( this.tools
[ allowCollapse
[ i
] ] );
11482 // Keep at the end, even when tools are added
11483 this.$group
.append( this.getExpandCollapseTool().$element
);
11485 this.getExpandCollapseTool().toggle( this.collapsibleTools
.length
!== 0 );
11486 this.updateCollapsibleState();
11489 OO
.ui
.ListToolGroup
.prototype.getExpandCollapseTool = function () {
11490 var ExpandCollapseTool
;
11491 if ( this.expandCollapseTool
=== undefined ) {
11492 ExpandCollapseTool = function () {
11493 ExpandCollapseTool
.parent
.apply( this, arguments
);
11496 OO
.inheritClass( ExpandCollapseTool
, OO
.ui
.Tool
);
11498 ExpandCollapseTool
.prototype.onSelect = function () {
11499 this.toolGroup
.expanded
= !this.toolGroup
.expanded
;
11500 this.toolGroup
.updateCollapsibleState();
11501 this.setActive( false );
11503 ExpandCollapseTool
.prototype.onUpdateState = function () {
11504 // Do nothing. Tool interface requires an implementation of this function.
11507 ExpandCollapseTool
.static.name
= 'more-fewer';
11509 this.expandCollapseTool
= new ExpandCollapseTool( this );
11511 return this.expandCollapseTool
;
11517 OO
.ui
.ListToolGroup
.prototype.onMouseKeyUp = function ( e
) {
11518 // Do not close the popup when the user wants to show more/fewer tools
11520 $( e
.target
).closest( '.oo-ui-tool-name-more-fewer' ).length
&&
11521 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11523 // HACK: Prevent the popup list from being hidden. Skip the PopupToolGroup implementation (which
11524 // hides the popup list when a tool is selected) and call ToolGroup's implementation directly.
11525 return OO
.ui
.ListToolGroup
.parent
.parent
.prototype.onMouseKeyUp
.call( this, e
);
11527 return OO
.ui
.ListToolGroup
.parent
.prototype.onMouseKeyUp
.call( this, e
);
11531 OO
.ui
.ListToolGroup
.prototype.updateCollapsibleState = function () {
11534 this.getExpandCollapseTool()
11535 .setIcon( this.expanded
? 'collapse' : 'expand' )
11536 .setTitle( OO
.ui
.msg( this.expanded
? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
11538 for ( i
= 0, len
= this.collapsibleTools
.length
; i
< len
; i
++ ) {
11539 this.collapsibleTools
[ i
].toggle( this.expanded
);
11544 * MenuToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11545 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.BarToolGroup BarToolGroup}
11546 * and {@link OO.ui.ListToolGroup ListToolGroup}). MenuToolGroups contain selectable {@link OO.ui.Tool tools},
11547 * which are displayed by label in a dropdown menu. The tool's title is used as the label text, and the
11548 * menu label is updated to reflect which tool or tools are currently selected. If no tools are selected,
11549 * the menu label is empty. The menu can be configured with an indicator, icon, title, and/or header.
11551 * MenuToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar
11552 * is set up. Note that all tools must define an {@link OO.ui.Tool#onUpdateState onUpdateState} method if
11553 * a MenuToolGroup is used.
11556 * // Example of a MenuToolGroup
11557 * var toolFactory = new OO.ui.ToolFactory();
11558 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11559 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11561 * // We will be placing status text in this element when tools are used
11562 * var $area = $( '<p>' ).text( 'An example of a MenuToolGroup. Select a tool from the dropdown menu.' );
11564 * // Define the tools that we're going to place in our toolbar
11566 * function SettingsTool() {
11567 * SettingsTool.parent.apply( this, arguments );
11568 * this.reallyActive = false;
11570 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11571 * SettingsTool.static.name = 'settings';
11572 * SettingsTool.static.icon = 'settings';
11573 * SettingsTool.static.title = 'Change settings';
11574 * SettingsTool.prototype.onSelect = function () {
11575 * $area.text( 'Settings tool clicked!' );
11576 * // Toggle the active state on each click
11577 * this.reallyActive = !this.reallyActive;
11578 * this.setActive( this.reallyActive );
11579 * // To update the menu label
11580 * this.toolbar.emit( 'updateState' );
11582 * SettingsTool.prototype.onUpdateState = function () {
11584 * toolFactory.register( SettingsTool );
11586 * function StuffTool() {
11587 * StuffTool.parent.apply( this, arguments );
11588 * this.reallyActive = false;
11590 * OO.inheritClass( StuffTool, OO.ui.Tool );
11591 * StuffTool.static.name = 'stuff';
11592 * StuffTool.static.icon = 'ellipsis';
11593 * StuffTool.static.title = 'More stuff';
11594 * StuffTool.prototype.onSelect = function () {
11595 * $area.text( 'More stuff tool clicked!' );
11596 * // Toggle the active state on each click
11597 * this.reallyActive = !this.reallyActive;
11598 * this.setActive( this.reallyActive );
11599 * // To update the menu label
11600 * this.toolbar.emit( 'updateState' );
11602 * StuffTool.prototype.onUpdateState = function () {
11604 * toolFactory.register( StuffTool );
11606 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11607 * // used once (but not all defined tools must be used).
11611 * header: 'This is the (optional) header',
11612 * title: 'This is the (optional) title',
11613 * indicator: 'down',
11614 * include: [ 'settings', 'stuff' ]
11618 * // Create some UI around the toolbar and place it in the document
11619 * var frame = new OO.ui.PanelLayout( {
11623 * var contentFrame = new OO.ui.PanelLayout( {
11627 * frame.$element.append(
11628 * toolbar.$element,
11629 * contentFrame.$element.append( $area )
11631 * $( 'body' ).append( frame.$element );
11633 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11635 * toolbar.initialize();
11636 * toolbar.emit( 'updateState' );
11638 * For more information about how to add tools to a MenuToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11639 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki] [1].
11641 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11644 * @extends OO.ui.PopupToolGroup
11647 * @param {OO.ui.Toolbar} toolbar
11648 * @param {Object} [config] Configuration options
11650 OO
.ui
.MenuToolGroup
= function OoUiMenuToolGroup( toolbar
, config
) {
11651 // Allow passing positional parameters inside the config object
11652 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11654 toolbar
= config
.toolbar
;
11657 // Configuration initialization
11658 config
= config
|| {};
11660 // Parent constructor
11661 OO
.ui
.MenuToolGroup
.parent
.call( this, toolbar
, config
);
11664 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
11667 this.$element
.addClass( 'oo-ui-menuToolGroup' );
11672 OO
.inheritClass( OO
.ui
.MenuToolGroup
, OO
.ui
.PopupToolGroup
);
11674 /* Static Properties */
11676 OO
.ui
.MenuToolGroup
.static.name
= 'menu';
11681 * Handle the toolbar state being updated.
11683 * When the state changes, the title of each active item in the menu will be joined together and
11684 * used as a label for the group. The label will be empty if none of the items are active.
11688 OO
.ui
.MenuToolGroup
.prototype.onUpdateState = function () {
11692 for ( name
in this.tools
) {
11693 if ( this.tools
[ name
].isActive() ) {
11694 labelTexts
.push( this.tools
[ name
].getTitle() );
11698 this.setLabel( labelTexts
.join( ', ' ) || ' ' );
11702 * Popup tools open a popup window when they are selected from the {@link OO.ui.Toolbar toolbar}. Each popup tool is configured
11703 * with a static name, title, and icon, as well with as any popup configurations. Unlike other tools, popup tools do not require that developers specify
11704 * an #onSelect or #onUpdateState method, as these methods have been implemented already.
11706 * // Example of a popup tool. When selected, a popup tool displays
11707 * // a popup window.
11708 * function HelpTool( toolGroup, config ) {
11709 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11714 * this.popup.$body.append( '<p>I am helpful!</p>' );
11716 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11717 * HelpTool.static.name = 'help';
11718 * HelpTool.static.icon = 'help';
11719 * HelpTool.static.title = 'Help';
11720 * toolFactory.register( HelpTool );
11722 * For an example of a toolbar that contains a popup tool, see {@link OO.ui.Toolbar toolbars}. For more information about
11723 * toolbars in genreral, please see the [OOjs UI documentation on MediaWiki][1].
11725 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11729 * @extends OO.ui.Tool
11730 * @mixins OO.ui.mixin.PopupElement
11733 * @param {OO.ui.ToolGroup} toolGroup
11734 * @param {Object} [config] Configuration options
11736 OO
.ui
.PopupTool
= function OoUiPopupTool( toolGroup
, config
) {
11737 // Allow passing positional parameters inside the config object
11738 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
11739 config
= toolGroup
;
11740 toolGroup
= config
.toolGroup
;
11743 // Parent constructor
11744 OO
.ui
.PopupTool
.parent
.call( this, toolGroup
, config
);
11746 // Mixin constructors
11747 OO
.ui
.mixin
.PopupElement
.call( this, config
);
11751 .addClass( 'oo-ui-popupTool' )
11752 .append( this.popup
.$element
);
11757 OO
.inheritClass( OO
.ui
.PopupTool
, OO
.ui
.Tool
);
11758 OO
.mixinClass( OO
.ui
.PopupTool
, OO
.ui
.mixin
.PopupElement
);
11763 * Handle the tool being selected.
11767 OO
.ui
.PopupTool
.prototype.onSelect = function () {
11768 if ( !this.isDisabled() ) {
11769 this.popup
.toggle();
11771 this.setActive( false );
11776 * Handle the toolbar state being updated.
11780 OO
.ui
.PopupTool
.prototype.onUpdateState = function () {
11781 this.setActive( false );
11785 * A ToolGroupTool is a special sort of tool that can contain other {@link OO.ui.Tool tools}
11786 * and {@link OO.ui.ToolGroup toolgroups}. The ToolGroupTool was specifically designed to be used
11787 * inside a {@link OO.ui.BarToolGroup bar} toolgroup to provide access to additional tools from
11788 * the bar item. Included tools will be displayed in a dropdown {@link OO.ui.ListToolGroup list}
11789 * when the ToolGroupTool is selected.
11791 * // Example: ToolGroupTool with two nested tools, 'setting1' and 'setting2', defined elsewhere.
11793 * function SettingsTool() {
11794 * SettingsTool.parent.apply( this, arguments );
11796 * OO.inheritClass( SettingsTool, OO.ui.ToolGroupTool );
11797 * SettingsTool.static.name = 'settings';
11798 * SettingsTool.static.title = 'Change settings';
11799 * SettingsTool.static.groupConfig = {
11800 * icon: 'settings',
11801 * label: 'ToolGroupTool',
11802 * include: [ 'setting1', 'setting2' ]
11804 * toolFactory.register( SettingsTool );
11806 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
11808 * Please note that this implementation is subject to change per [T74159] [2].
11810 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars#ToolGroupTool
11811 * [2]: https://phabricator.wikimedia.org/T74159
11815 * @extends OO.ui.Tool
11818 * @param {OO.ui.ToolGroup} toolGroup
11819 * @param {Object} [config] Configuration options
11821 OO
.ui
.ToolGroupTool
= function OoUiToolGroupTool( toolGroup
, config
) {
11822 // Allow passing positional parameters inside the config object
11823 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
11824 config
= toolGroup
;
11825 toolGroup
= config
.toolGroup
;
11828 // Parent constructor
11829 OO
.ui
.ToolGroupTool
.parent
.call( this, toolGroup
, config
);
11832 this.innerToolGroup
= this.createGroup( this.constructor.static.groupConfig
);
11835 this.innerToolGroup
.connect( this, { disable
: 'onToolGroupDisable' } );
11838 this.$link
.remove();
11840 .addClass( 'oo-ui-toolGroupTool' )
11841 .append( this.innerToolGroup
.$element
);
11846 OO
.inheritClass( OO
.ui
.ToolGroupTool
, OO
.ui
.Tool
);
11848 /* Static Properties */
11851 * Toolgroup configuration.
11853 * The toolgroup configuration consists of the tools to include, as well as an icon and label
11854 * to use for the bar item. Tools can be included by symbolic name, group, or with the
11855 * wildcard selector. Please see {@link OO.ui.ToolGroup toolgroup} for more information.
11857 * @property {Object.<string,Array>}
11859 OO
.ui
.ToolGroupTool
.static.groupConfig
= {};
11864 * Handle the tool being selected.
11868 OO
.ui
.ToolGroupTool
.prototype.onSelect = function () {
11869 this.innerToolGroup
.setActive( !this.innerToolGroup
.active
);
11874 * Synchronize disabledness state of the tool with the inner toolgroup.
11877 * @param {boolean} disabled Element is disabled
11879 OO
.ui
.ToolGroupTool
.prototype.onToolGroupDisable = function ( disabled
) {
11880 this.setDisabled( disabled
);
11884 * Handle the toolbar state being updated.
11888 OO
.ui
.ToolGroupTool
.prototype.onUpdateState = function () {
11889 this.setActive( false );
11893 * Build a {@link OO.ui.ToolGroup toolgroup} from the specified configuration.
11895 * @param {Object.<string,Array>} group Toolgroup configuration. Please see {@link OO.ui.ToolGroup toolgroup} for
11896 * more information.
11897 * @return {OO.ui.ListToolGroup}
11899 OO
.ui
.ToolGroupTool
.prototype.createGroup = function ( group
) {
11900 if ( group
.include
=== '*' ) {
11901 // Apply defaults to catch-all groups
11902 if ( group
.label
=== undefined ) {
11903 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
11907 return this.toolbar
.getToolGroupFactory().create( 'list', this.toolbar
, group
);
11911 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
11913 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
11918 * @extends OO.ui.mixin.GroupElement
11921 * @param {Object} [config] Configuration options
11923 OO
.ui
.mixin
.GroupWidget
= function OoUiMixinGroupWidget( config
) {
11924 // Parent constructor
11925 OO
.ui
.mixin
.GroupWidget
.parent
.call( this, config
);
11930 OO
.inheritClass( OO
.ui
.mixin
.GroupWidget
, OO
.ui
.mixin
.GroupElement
);
11935 * Set the disabled state of the widget.
11937 * This will also update the disabled state of child widgets.
11939 * @param {boolean} disabled Disable widget
11942 OO
.ui
.mixin
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
11946 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
11947 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
11949 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
11950 if ( this.items
) {
11951 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
11952 this.items
[ i
].updateDisabled();
11960 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
11962 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
11963 * allows bidirectional communication.
11965 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
11973 OO
.ui
.mixin
.ItemWidget
= function OoUiMixinItemWidget() {
11980 * Check if widget is disabled.
11982 * Checks parent if present, making disabled state inheritable.
11984 * @return {boolean} Widget is disabled
11986 OO
.ui
.mixin
.ItemWidget
.prototype.isDisabled = function () {
11987 return this.disabled
||
11988 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
11992 * Set group element is in.
11994 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
11997 OO
.ui
.mixin
.ItemWidget
.prototype.setElementGroup = function ( group
) {
11999 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
12000 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
12002 // Initialize item disabled states
12003 this.updateDisabled();
12009 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
12010 * Controls include moving items up and down, removing items, and adding different kinds of items.
12012 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
12015 * @extends OO.ui.Widget
12016 * @mixins OO.ui.mixin.GroupElement
12017 * @mixins OO.ui.mixin.IconElement
12020 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
12021 * @param {Object} [config] Configuration options
12022 * @cfg {Object} [abilities] List of abilties
12023 * @cfg {boolean} [abilities.move=true] Allow moving movable items
12024 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
12026 OO
.ui
.OutlineControlsWidget
= function OoUiOutlineControlsWidget( outline
, config
) {
12027 // Allow passing positional parameters inside the config object
12028 if ( OO
.isPlainObject( outline
) && config
=== undefined ) {
12030 outline
= config
.outline
;
12033 // Configuration initialization
12034 config
= $.extend( { icon
: 'add' }, config
);
12036 // Parent constructor
12037 OO
.ui
.OutlineControlsWidget
.parent
.call( this, config
);
12039 // Mixin constructors
12040 OO
.ui
.mixin
.GroupElement
.call( this, config
);
12041 OO
.ui
.mixin
.IconElement
.call( this, config
);
12044 this.outline
= outline
;
12045 this.$movers
= $( '<div>' );
12046 this.upButton
= new OO
.ui
.ButtonWidget( {
12049 title
: OO
.ui
.msg( 'ooui-outline-control-move-up' )
12051 this.downButton
= new OO
.ui
.ButtonWidget( {
12054 title
: OO
.ui
.msg( 'ooui-outline-control-move-down' )
12056 this.removeButton
= new OO
.ui
.ButtonWidget( {
12059 title
: OO
.ui
.msg( 'ooui-outline-control-remove' )
12061 this.abilities
= { move: true, remove
: true };
12064 outline
.connect( this, {
12065 select
: 'onOutlineChange',
12066 add
: 'onOutlineChange',
12067 remove
: 'onOutlineChange'
12069 this.upButton
.connect( this, { click
: [ 'emit', 'move', -1 ] } );
12070 this.downButton
.connect( this, { click
: [ 'emit', 'move', 1 ] } );
12071 this.removeButton
.connect( this, { click
: [ 'emit', 'remove' ] } );
12074 this.$element
.addClass( 'oo-ui-outlineControlsWidget' );
12075 this.$group
.addClass( 'oo-ui-outlineControlsWidget-items' );
12077 .addClass( 'oo-ui-outlineControlsWidget-movers' )
12078 .append( this.removeButton
.$element
, this.upButton
.$element
, this.downButton
.$element
);
12079 this.$element
.append( this.$icon
, this.$group
, this.$movers
);
12080 this.setAbilities( config
.abilities
|| {} );
12085 OO
.inheritClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.Widget
);
12086 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.mixin
.GroupElement
);
12087 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.mixin
.IconElement
);
12093 * @param {number} places Number of places to move
12105 * @param {Object} abilities List of abilties
12106 * @param {boolean} [abilities.move] Allow moving movable items
12107 * @param {boolean} [abilities.remove] Allow removing removable items
12109 OO
.ui
.OutlineControlsWidget
.prototype.setAbilities = function ( abilities
) {
12112 for ( ability
in this.abilities
) {
12113 if ( abilities
[ ability
] !== undefined ) {
12114 this.abilities
[ ability
] = !!abilities
[ ability
];
12118 this.onOutlineChange();
12124 * Handle outline change events.
12126 OO
.ui
.OutlineControlsWidget
.prototype.onOutlineChange = function () {
12127 var i
, len
, firstMovable
, lastMovable
,
12128 items
= this.outline
.getItems(),
12129 selectedItem
= this.outline
.getSelectedItem(),
12130 movable
= this.abilities
.move && selectedItem
&& selectedItem
.isMovable(),
12131 removable
= this.abilities
.remove
&& selectedItem
&& selectedItem
.isRemovable();
12135 len
= items
.length
;
12136 while ( ++i
< len
) {
12137 if ( items
[ i
].isMovable() ) {
12138 firstMovable
= items
[ i
];
12144 if ( items
[ i
].isMovable() ) {
12145 lastMovable
= items
[ i
];
12150 this.upButton
.setDisabled( !movable
|| selectedItem
=== firstMovable
);
12151 this.downButton
.setDisabled( !movable
|| selectedItem
=== lastMovable
);
12152 this.removeButton
.setDisabled( !removable
);
12156 * ToggleWidget implements basic behavior of widgets with an on/off state.
12157 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
12161 * @extends OO.ui.Widget
12164 * @param {Object} [config] Configuration options
12165 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
12166 * By default, the toggle is in the 'off' state.
12168 OO
.ui
.ToggleWidget
= function OoUiToggleWidget( config
) {
12169 // Configuration initialization
12170 config
= config
|| {};
12172 // Parent constructor
12173 OO
.ui
.ToggleWidget
.parent
.call( this, config
);
12179 this.$element
.addClass( 'oo-ui-toggleWidget' );
12180 this.setValue( !!config
.value
);
12185 OO
.inheritClass( OO
.ui
.ToggleWidget
, OO
.ui
.Widget
);
12192 * A change event is emitted when the on/off state of the toggle changes.
12194 * @param {boolean} value Value representing the new state of the toggle
12200 * Get the value representing the toggle’s state.
12202 * @return {boolean} The on/off state of the toggle
12204 OO
.ui
.ToggleWidget
.prototype.getValue = function () {
12209 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
12211 * @param {boolean} value The state of the toggle
12215 OO
.ui
.ToggleWidget
.prototype.setValue = function ( value
) {
12217 if ( this.value
!== value
) {
12218 this.value
= value
;
12219 this.emit( 'change', value
);
12220 this.$element
.toggleClass( 'oo-ui-toggleWidget-on', value
);
12221 this.$element
.toggleClass( 'oo-ui-toggleWidget-off', !value
);
12222 this.$element
.attr( 'aria-checked', value
.toString() );
12228 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
12229 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
12230 * removed, and cleared from the group.
12233 * // Example: A ButtonGroupWidget with two buttons
12234 * var button1 = new OO.ui.PopupButtonWidget( {
12235 * label: 'Select a category',
12238 * $content: $( '<p>List of categories...</p>' ),
12243 * var button2 = new OO.ui.ButtonWidget( {
12244 * label: 'Add item'
12246 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
12247 * items: [button1, button2]
12249 * $( 'body' ).append( buttonGroup.$element );
12252 * @extends OO.ui.Widget
12253 * @mixins OO.ui.mixin.GroupElement
12256 * @param {Object} [config] Configuration options
12257 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
12259 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
12260 // Configuration initialization
12261 config
= config
|| {};
12263 // Parent constructor
12264 OO
.ui
.ButtonGroupWidget
.parent
.call( this, config
);
12266 // Mixin constructors
12267 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
12270 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
12271 if ( Array
.isArray( config
.items
) ) {
12272 this.addItems( config
.items
);
12278 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
12279 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.GroupElement
);
12282 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
12283 * feels, and functionality can be customized via the class’s configuration options
12284 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12287 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
12290 * // A button widget
12291 * var button = new OO.ui.ButtonWidget( {
12292 * label: 'Button with Icon',
12294 * iconTitle: 'Remove'
12296 * $( 'body' ).append( button.$element );
12298 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
12301 * @extends OO.ui.Widget
12302 * @mixins OO.ui.mixin.ButtonElement
12303 * @mixins OO.ui.mixin.IconElement
12304 * @mixins OO.ui.mixin.IndicatorElement
12305 * @mixins OO.ui.mixin.LabelElement
12306 * @mixins OO.ui.mixin.TitledElement
12307 * @mixins OO.ui.mixin.FlaggedElement
12308 * @mixins OO.ui.mixin.TabIndexedElement
12309 * @mixins OO.ui.mixin.AccessKeyedElement
12312 * @param {Object} [config] Configuration options
12313 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
12314 * @cfg {string} [target] The frame or window in which to open the hyperlink.
12315 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
12317 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
12318 // Configuration initialization
12319 config
= config
|| {};
12321 // Parent constructor
12322 OO
.ui
.ButtonWidget
.parent
.call( this, config
);
12324 // Mixin constructors
12325 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
12326 OO
.ui
.mixin
.IconElement
.call( this, config
);
12327 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
12328 OO
.ui
.mixin
.LabelElement
.call( this, config
);
12329 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
12330 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
12331 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
12332 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$button
} ) );
12336 this.target
= null;
12337 this.noFollow
= false;
12340 this.connect( this, { disable
: 'onDisable' } );
12343 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
12345 .addClass( 'oo-ui-buttonWidget' )
12346 .append( this.$button
);
12347 this.setHref( config
.href
);
12348 this.setTarget( config
.target
);
12349 this.setNoFollow( config
.noFollow
);
12354 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
12355 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
12356 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IconElement
);
12357 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
12358 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.LabelElement
);
12359 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TitledElement
);
12360 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
12361 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
12362 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
12369 OO
.ui
.ButtonWidget
.prototype.onMouseDown = function ( e
) {
12370 if ( !this.isDisabled() ) {
12371 // Remove the tab-index while the button is down to prevent the button from stealing focus
12372 this.$button
.removeAttr( 'tabindex' );
12375 return OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown
.call( this, e
);
12381 OO
.ui
.ButtonWidget
.prototype.onMouseUp = function ( e
) {
12382 if ( !this.isDisabled() ) {
12383 // Restore the tab-index after the button is up to restore the button's accessibility
12384 this.$button
.attr( 'tabindex', this.tabIndex
);
12387 return OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp
.call( this, e
);
12391 * Get hyperlink location.
12393 * @return {string} Hyperlink location
12395 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
12400 * Get hyperlink target.
12402 * @return {string} Hyperlink target
12404 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
12405 return this.target
;
12409 * Get search engine traversal hint.
12411 * @return {boolean} Whether search engines should avoid traversing this hyperlink
12413 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
12414 return this.noFollow
;
12418 * Set hyperlink location.
12420 * @param {string|null} href Hyperlink location, null to remove
12422 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
12423 href
= typeof href
=== 'string' ? href
: null;
12424 if ( href
!== null ) {
12425 if ( !OO
.ui
.isSafeUrl( href
) ) {
12426 throw new Error( 'Potentially unsafe href provided: ' + href
);
12431 if ( href
!== this.href
) {
12440 * Update the `href` attribute, in case of changes to href or
12446 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
12447 if ( this.href
!== null && !this.isDisabled() ) {
12448 this.$button
.attr( 'href', this.href
);
12450 this.$button
.removeAttr( 'href' );
12457 * Handle disable events.
12460 * @param {boolean} disabled Element is disabled
12462 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
12467 * Set hyperlink target.
12469 * @param {string|null} target Hyperlink target, null to remove
12471 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
12472 target
= typeof target
=== 'string' ? target
: null;
12474 if ( target
!== this.target
) {
12475 this.target
= target
;
12476 if ( target
!== null ) {
12477 this.$button
.attr( 'target', target
);
12479 this.$button
.removeAttr( 'target' );
12487 * Set search engine traversal hint.
12489 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
12491 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
12492 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
12494 if ( noFollow
!== this.noFollow
) {
12495 this.noFollow
= noFollow
;
12497 this.$button
.attr( 'rel', 'nofollow' );
12499 this.$button
.removeAttr( 'rel' );
12507 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
12508 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
12511 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
12512 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12515 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
12518 * @extends OO.ui.ButtonWidget
12519 * @mixins OO.ui.mixin.PendingElement
12522 * @param {Object} [config] Configuration options
12523 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12524 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
12525 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
12526 * for more information about setting modes.
12527 * @cfg {boolean} [framed=false] Render the action button with a frame
12529 OO
.ui
.ActionWidget
= function OoUiActionWidget( config
) {
12530 // Configuration initialization
12531 config
= $.extend( { framed
: false }, config
);
12533 // Parent constructor
12534 OO
.ui
.ActionWidget
.parent
.call( this, config
);
12536 // Mixin constructors
12537 OO
.ui
.mixin
.PendingElement
.call( this, config
);
12540 this.action
= config
.action
|| '';
12541 this.modes
= config
.modes
|| [];
12546 this.$element
.addClass( 'oo-ui-actionWidget' );
12551 OO
.inheritClass( OO
.ui
.ActionWidget
, OO
.ui
.ButtonWidget
);
12552 OO
.mixinClass( OO
.ui
.ActionWidget
, OO
.ui
.mixin
.PendingElement
);
12557 * A resize event is emitted when the size of the widget changes.
12565 * Check if the action is configured to be available in the specified `mode`.
12567 * @param {string} mode Name of mode
12568 * @return {boolean} The action is configured with the mode
12570 OO
.ui
.ActionWidget
.prototype.hasMode = function ( mode
) {
12571 return this.modes
.indexOf( mode
) !== -1;
12575 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12579 OO
.ui
.ActionWidget
.prototype.getAction = function () {
12580 return this.action
;
12584 * Get the symbolic name of the mode or modes for which the action is configured to be available.
12586 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
12587 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
12590 * @return {string[]}
12592 OO
.ui
.ActionWidget
.prototype.getModes = function () {
12593 return this.modes
.slice();
12597 * Emit a resize event if the size has changed.
12602 OO
.ui
.ActionWidget
.prototype.propagateResize = function () {
12605 if ( this.isElementAttached() ) {
12606 width
= this.$element
.width();
12607 height
= this.$element
.height();
12609 if ( width
!== this.width
|| height
!== this.height
) {
12610 this.width
= width
;
12611 this.height
= height
;
12612 this.emit( 'resize' );
12622 OO
.ui
.ActionWidget
.prototype.setIcon = function () {
12624 OO
.ui
.mixin
.IconElement
.prototype.setIcon
.apply( this, arguments
);
12625 this.propagateResize();
12633 OO
.ui
.ActionWidget
.prototype.setLabel = function () {
12635 OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.apply( this, arguments
);
12636 this.propagateResize();
12644 OO
.ui
.ActionWidget
.prototype.setFlags = function () {
12646 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags
.apply( this, arguments
);
12647 this.propagateResize();
12655 OO
.ui
.ActionWidget
.prototype.clearFlags = function () {
12657 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags
.apply( this, arguments
);
12658 this.propagateResize();
12664 * Toggle the visibility of the action button.
12666 * @param {boolean} [show] Show button, omit to toggle visibility
12669 OO
.ui
.ActionWidget
.prototype.toggle = function () {
12671 OO
.ui
.ActionWidget
.parent
.prototype.toggle
.apply( this, arguments
);
12672 this.propagateResize();
12678 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
12679 * which is used to display additional information or options.
12682 * // Example of a popup button.
12683 * var popupButton = new OO.ui.PopupButtonWidget( {
12684 * label: 'Popup button with options',
12687 * $content: $( '<p>Additional options here.</p>' ),
12689 * align: 'force-left'
12692 * // Append the button to the DOM.
12693 * $( 'body' ).append( popupButton.$element );
12696 * @extends OO.ui.ButtonWidget
12697 * @mixins OO.ui.mixin.PopupElement
12700 * @param {Object} [config] Configuration options
12702 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
12703 // Parent constructor
12704 OO
.ui
.PopupButtonWidget
.parent
.call( this, config
);
12706 // Mixin constructors
12707 OO
.ui
.mixin
.PopupElement
.call( this, config
);
12710 this.connect( this, { click
: 'onAction' } );
12714 .addClass( 'oo-ui-popupButtonWidget' )
12715 .attr( 'aria-haspopup', 'true' )
12716 .append( this.popup
.$element
);
12721 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
12722 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.mixin
.PopupElement
);
12727 * Handle the button action being triggered.
12731 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
12732 this.popup
.toggle();
12736 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
12737 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
12738 * configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators},
12739 * {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags},
12740 * and {@link OO.ui.mixin.LabelElement labels}. Please see
12741 * the [OOjs UI documentation][1] on MediaWiki for more information.
12744 * // Toggle buttons in the 'off' and 'on' state.
12745 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
12746 * label: 'Toggle Button off'
12748 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
12749 * label: 'Toggle Button on',
12752 * // Append the buttons to the DOM.
12753 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
12755 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
12758 * @extends OO.ui.ToggleWidget
12759 * @mixins OO.ui.mixin.ButtonElement
12760 * @mixins OO.ui.mixin.IconElement
12761 * @mixins OO.ui.mixin.IndicatorElement
12762 * @mixins OO.ui.mixin.LabelElement
12763 * @mixins OO.ui.mixin.TitledElement
12764 * @mixins OO.ui.mixin.FlaggedElement
12765 * @mixins OO.ui.mixin.TabIndexedElement
12768 * @param {Object} [config] Configuration options
12769 * @cfg {boolean} [value=false] The toggle button’s initial on/off
12770 * state. By default, the button is in the 'off' state.
12772 OO
.ui
.ToggleButtonWidget
= function OoUiToggleButtonWidget( config
) {
12773 // Configuration initialization
12774 config
= config
|| {};
12776 // Parent constructor
12777 OO
.ui
.ToggleButtonWidget
.parent
.call( this, config
);
12779 // Mixin constructors
12780 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
12781 OO
.ui
.mixin
.IconElement
.call( this, config
);
12782 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
12783 OO
.ui
.mixin
.LabelElement
.call( this, config
);
12784 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
12785 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
12786 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
12789 this.connect( this, { click
: 'onAction' } );
12792 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
12794 .addClass( 'oo-ui-toggleButtonWidget' )
12795 .append( this.$button
);
12800 OO
.inheritClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.ToggleWidget
);
12801 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
12802 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.IconElement
);
12803 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
12804 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.LabelElement
);
12805 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.TitledElement
);
12806 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
12807 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
12812 * Handle the button action being triggered.
12816 OO
.ui
.ToggleButtonWidget
.prototype.onAction = function () {
12817 this.setValue( !this.value
);
12823 OO
.ui
.ToggleButtonWidget
.prototype.setValue = function ( value
) {
12825 if ( value
!== this.value
) {
12826 // Might be called from parent constructor before ButtonElement constructor
12827 if ( this.$button
) {
12828 this.$button
.attr( 'aria-pressed', value
.toString() );
12830 this.setActive( value
);
12834 OO
.ui
.ToggleButtonWidget
.parent
.prototype.setValue
.call( this, value
);
12842 OO
.ui
.ToggleButtonWidget
.prototype.setButtonElement = function ( $button
) {
12843 if ( this.$button
) {
12844 this.$button
.removeAttr( 'aria-pressed' );
12846 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement
.call( this, $button
);
12847 this.$button
.attr( 'aria-pressed', this.value
.toString() );
12851 * CapsuleMultiSelectWidgets are something like a {@link OO.ui.ComboBoxWidget combo box widget}
12852 * that allows for selecting multiple values.
12854 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
12857 * // Example: A CapsuleMultiSelectWidget.
12858 * var capsule = new OO.ui.CapsuleMultiSelectWidget( {
12859 * label: 'CapsuleMultiSelectWidget',
12860 * selected: [ 'Option 1', 'Option 3' ],
12863 * new OO.ui.MenuOptionWidget( {
12864 * data: 'Option 1',
12865 * label: 'Option One'
12867 * new OO.ui.MenuOptionWidget( {
12868 * data: 'Option 2',
12869 * label: 'Option Two'
12871 * new OO.ui.MenuOptionWidget( {
12872 * data: 'Option 3',
12873 * label: 'Option Three'
12875 * new OO.ui.MenuOptionWidget( {
12876 * data: 'Option 4',
12877 * label: 'Option Four'
12879 * new OO.ui.MenuOptionWidget( {
12880 * data: 'Option 5',
12881 * label: 'Option Five'
12886 * $( 'body' ).append( capsule.$element );
12888 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
12891 * @extends OO.ui.Widget
12892 * @mixins OO.ui.mixin.TabIndexedElement
12893 * @mixins OO.ui.mixin.GroupElement
12896 * @param {Object} [config] Configuration options
12897 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if not present in the menu.
12898 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
12899 * @cfg {Object} [popup] Configuration options to pass to the {@link OO.ui.PopupWidget popup widget}.
12900 * If specified, this popup will be shown instead of the menu (but the menu
12901 * will still be used for item labels and allowArbitrary=false). The widgets
12902 * in the popup should use this.addItemsFromData() or this.addItems() as necessary.
12903 * @cfg {jQuery} [$overlay] Render the menu or popup into a separate layer.
12904 * This configuration is useful in cases where the expanded menu is larger than
12905 * its containing `<div>`. The specified overlay layer is usually on top of
12906 * the containing `<div>` and has a larger area. By default, the menu uses
12907 * relative positioning.
12909 OO
.ui
.CapsuleMultiSelectWidget
= function OoUiCapsuleMultiSelectWidget( config
) {
12912 // Configuration initialization
12913 config
= config
|| {};
12915 // Parent constructor
12916 OO
.ui
.CapsuleMultiSelectWidget
.parent
.call( this, config
);
12918 // Properties (must be set before mixin constructor calls)
12919 this.$input
= config
.popup
? null : $( '<input>' );
12920 this.$handle
= $( '<div>' );
12922 // Mixin constructors
12923 OO
.ui
.mixin
.GroupElement
.call( this, config
);
12924 if ( config
.popup
) {
12925 config
.popup
= $.extend( {}, config
.popup
, {
12929 OO
.ui
.mixin
.PopupElement
.call( this, config
);
12930 $tabFocus
= $( '<span>' );
12931 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: $tabFocus
} ) );
12935 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
12937 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
12938 OO
.ui
.mixin
.IconElement
.call( this, config
);
12941 this.allowArbitrary
= !!config
.allowArbitrary
;
12942 this.$overlay
= config
.$overlay
|| this.$element
;
12943 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend(
12946 $input
: this.$input
,
12947 $container
: this.$element
,
12948 filterFromInput
: true,
12949 disabled
: this.isDisabled()
12955 if ( this.popup
) {
12957 focus
: this.onFocusForPopup
.bind( this )
12959 this.popup
.$element
.on( 'focusout', this.onPopupFocusOut
.bind( this ) );
12960 if ( this.popup
.$autoCloseIgnore
) {
12961 this.popup
.$autoCloseIgnore
.on( 'focusout', this.onPopupFocusOut
.bind( this ) );
12963 this.popup
.connect( this, {
12964 toggle: function ( visible
) {
12965 $tabFocus
.toggle( !visible
);
12970 focus
: this.onInputFocus
.bind( this ),
12971 blur
: this.onInputBlur
.bind( this ),
12972 'propertychange change click mouseup keydown keyup input cut paste select': this.onInputChange
.bind( this ),
12973 keydown
: this.onKeyDown
.bind( this ),
12974 keypress
: this.onKeyPress
.bind( this )
12977 this.menu
.connect( this, {
12978 choose
: 'onMenuChoose',
12979 add
: 'onMenuItemsChange',
12980 remove
: 'onMenuItemsChange'
12983 click
: this.onClick
.bind( this )
12987 if ( this.$input
) {
12988 this.$input
.prop( 'disabled', this.isDisabled() );
12989 this.$input
.attr( {
12991 'aria-autocomplete': 'list'
12993 this.$input
.width( '1em' );
12995 if ( config
.data
) {
12996 this.setItemsFromData( config
.data
);
12998 this.$group
.addClass( 'oo-ui-capsuleMultiSelectWidget-group' );
12999 this.$handle
.addClass( 'oo-ui-capsuleMultiSelectWidget-handle' )
13000 .append( this.$indicator
, this.$icon
, this.$group
);
13001 this.$element
.addClass( 'oo-ui-capsuleMultiSelectWidget' )
13002 .append( this.$handle
);
13003 if ( this.popup
) {
13004 this.$handle
.append( $tabFocus
);
13005 this.$overlay
.append( this.popup
.$element
);
13007 this.$handle
.append( this.$input
);
13008 this.$overlay
.append( this.menu
.$element
);
13010 this.onMenuItemsChange();
13015 OO
.inheritClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.Widget
);
13016 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.GroupElement
);
13017 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.PopupElement
);
13018 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
13019 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.IndicatorElement
);
13020 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.IconElement
);
13027 * A change event is emitted when the set of selected items changes.
13029 * @param {Mixed[]} datas Data of the now-selected items
13035 * Get the data of the items in the capsule
13036 * @return {Mixed[]}
13038 OO
.ui
.CapsuleMultiSelectWidget
.prototype.getItemsData = function () {
13039 return $.map( this.getItems(), function ( e
) { return e
.data
; } );
13043 * Set the items in the capsule by providing data
13045 * @param {Mixed[]} datas
13046 * @return {OO.ui.CapsuleMultiSelectWidget}
13048 OO
.ui
.CapsuleMultiSelectWidget
.prototype.setItemsFromData = function ( datas
) {
13051 items
= this.getItems();
13053 $.each( datas
, function ( i
, data
) {
13055 item
= menu
.getItemFromData( data
);
13058 label
= item
.label
;
13059 } else if ( widget
.allowArbitrary
) {
13060 label
= String( data
);
13066 for ( j
= 0; j
< items
.length
; j
++ ) {
13067 if ( items
[ j
].data
=== data
&& items
[ j
].label
=== label
) {
13069 items
.splice( j
, 1 );
13074 item
= new OO
.ui
.CapsuleItemWidget( { data
: data
, label
: label
} );
13076 widget
.addItems( [ item
], i
);
13079 if ( items
.length
) {
13080 widget
.removeItems( items
);
13087 * Add items to the capsule by providing their data
13089 * @param {Mixed[]} datas
13090 * @return {OO.ui.CapsuleMultiSelectWidget}
13092 OO
.ui
.CapsuleMultiSelectWidget
.prototype.addItemsFromData = function ( datas
) {
13097 $.each( datas
, function ( i
, data
) {
13100 if ( !widget
.getItemFromData( data
) ) {
13101 item
= menu
.getItemFromData( data
);
13103 items
.push( new OO
.ui
.CapsuleItemWidget( { data
: data
, label
: item
.label
} ) );
13104 } else if ( widget
.allowArbitrary
) {
13105 items
.push( new OO
.ui
.CapsuleItemWidget( { data
: data
, label
: String( data
) } ) );
13110 if ( items
.length
) {
13111 this.addItems( items
);
13118 * Remove items by data
13120 * @param {Mixed[]} datas
13121 * @return {OO.ui.CapsuleMultiSelectWidget}
13123 OO
.ui
.CapsuleMultiSelectWidget
.prototype.removeItemsFromData = function ( datas
) {
13127 $.each( datas
, function ( i
, data
) {
13128 var item
= widget
.getItemFromData( data
);
13130 items
.push( item
);
13134 if ( items
.length
) {
13135 this.removeItems( items
);
13144 OO
.ui
.CapsuleMultiSelectWidget
.prototype.addItems = function ( items
) {
13146 oldItems
= this.items
.slice();
13148 OO
.ui
.mixin
.GroupElement
.prototype.addItems
.call( this, items
);
13150 if ( this.items
.length
!== oldItems
.length
) {
13154 for ( i
= 0, l
= oldItems
.length
; same
&& i
< l
; i
++ ) {
13155 same
= same
&& this.items
[ i
] === oldItems
[ i
];
13159 this.emit( 'change', this.getItemsData() );
13168 OO
.ui
.CapsuleMultiSelectWidget
.prototype.removeItems = function ( items
) {
13170 oldItems
= this.items
.slice();
13172 OO
.ui
.mixin
.GroupElement
.prototype.removeItems
.call( this, items
);
13174 if ( this.items
.length
!== oldItems
.length
) {
13178 for ( i
= 0, l
= oldItems
.length
; same
&& i
< l
; i
++ ) {
13179 same
= same
&& this.items
[ i
] === oldItems
[ i
];
13183 this.emit( 'change', this.getItemsData() );
13192 OO
.ui
.CapsuleMultiSelectWidget
.prototype.clearItems = function () {
13193 if ( this.items
.length
) {
13194 OO
.ui
.mixin
.GroupElement
.prototype.clearItems
.call( this );
13195 this.emit( 'change', this.getItemsData() );
13201 * Get the capsule widget's menu.
13202 * @return {OO.ui.MenuSelectWidget} Menu widget
13204 OO
.ui
.CapsuleMultiSelectWidget
.prototype.getMenu = function () {
13209 * Handle focus events
13212 * @param {jQuery.Event} event
13214 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onInputFocus = function () {
13215 if ( !this.isDisabled() ) {
13216 this.menu
.toggle( true );
13221 * Handle blur events
13224 * @param {jQuery.Event} event
13226 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onInputBlur = function () {
13231 * Handle focus events
13234 * @param {jQuery.Event} event
13236 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onFocusForPopup = function () {
13237 if ( !this.isDisabled() ) {
13238 this.popup
.setSize( this.$handle
.width() );
13239 this.popup
.toggle( true );
13240 this.popup
.$element
.find( '*' )
13241 .filter( function () { return OO
.ui
.isFocusableElement( $( this ), true ); } )
13248 * Handles popup focus out events.
13251 * @param {Event} e Focus out event
13253 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onPopupFocusOut = function () {
13254 var widget
= this.popup
;
13256 setTimeout( function () {
13258 widget
.isVisible() &&
13259 !OO
.ui
.contains( widget
.$element
[ 0 ], document
.activeElement
, true ) &&
13260 ( !widget
.$autoCloseIgnore
|| !widget
.$autoCloseIgnore
.has( document
.activeElement
).length
)
13262 widget
.toggle( false );
13268 * Handle mouse click events.
13271 * @param {jQuery.Event} e Mouse click event
13273 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onClick = function ( e
) {
13274 if ( e
.which
=== 1 ) {
13281 * Handle key press events.
13284 * @param {jQuery.Event} e Key press event
13286 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onKeyPress = function ( e
) {
13289 if ( !this.isDisabled() ) {
13290 if ( e
.which
=== OO
.ui
.Keys
.ESCAPE
) {
13295 if ( !this.popup
) {
13296 this.menu
.toggle( true );
13297 if ( e
.which
=== OO
.ui
.Keys
.ENTER
) {
13298 item
= this.menu
.getItemFromLabel( this.$input
.val(), true );
13300 this.addItemsFromData( [ item
.data
] );
13302 } else if ( this.allowArbitrary
&& this.$input
.val().trim() !== '' ) {
13303 this.addItemsFromData( [ this.$input
.val() ] );
13309 // Make sure the input gets resized.
13310 setTimeout( this.onInputChange
.bind( this ), 0 );
13316 * Handle key down events.
13319 * @param {jQuery.Event} e Key down event
13321 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onKeyDown = function ( e
) {
13322 if ( !this.isDisabled() ) {
13323 // 'keypress' event is not triggered for Backspace
13324 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.$input
.val() === '' ) {
13325 if ( this.items
.length
) {
13326 this.removeItems( this.items
.slice( -1 ) );
13334 * Handle input change events.
13337 * @param {jQuery.Event} e Event of some sort
13339 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onInputChange = function () {
13340 if ( !this.isDisabled() ) {
13341 this.$input
.width( this.$input
.val().length
+ 'em' );
13346 * Handle menu choose events.
13349 * @param {OO.ui.OptionWidget} item Chosen item
13351 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onMenuChoose = function ( item
) {
13352 if ( item
&& item
.isVisible() ) {
13353 this.addItemsFromData( [ item
.getData() ] );
13359 * Handle menu item change events.
13363 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onMenuItemsChange = function () {
13364 this.setItemsFromData( this.getItemsData() );
13365 this.$element
.toggleClass( 'oo-ui-capsuleMultiSelectWidget-empty', this.menu
.isEmpty() );
13369 * Clear the input field
13372 OO
.ui
.CapsuleMultiSelectWidget
.prototype.clearInput = function () {
13373 if ( this.$input
) {
13374 this.$input
.val( '' );
13375 this.$input
.width( '1em' );
13377 if ( this.popup
) {
13378 this.popup
.toggle( false );
13380 this.menu
.toggle( false );
13381 this.menu
.selectItem();
13382 this.menu
.highlightItem();
13388 OO
.ui
.CapsuleMultiSelectWidget
.prototype.setDisabled = function ( disabled
) {
13392 OO
.ui
.CapsuleMultiSelectWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
13394 if ( this.$input
) {
13395 this.$input
.prop( 'disabled', this.isDisabled() );
13398 this.menu
.setDisabled( this.isDisabled() );
13400 if ( this.popup
) {
13401 this.popup
.setDisabled( this.isDisabled() );
13404 if ( this.items
) {
13405 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
13406 this.items
[ i
].updateDisabled();
13416 * @return {OO.ui.CapsuleMultiSelectWidget}
13418 OO
.ui
.CapsuleMultiSelectWidget
.prototype.focus = function () {
13419 if ( !this.isDisabled() ) {
13420 if ( this.popup
) {
13421 this.popup
.setSize( this.$handle
.width() );
13422 this.popup
.toggle( true );
13423 this.popup
.$element
.find( '*' )
13424 .filter( function () { return OO
.ui
.isFocusableElement( $( this ), true ); } )
13428 this.menu
.toggle( true );
13429 this.$input
.focus();
13436 * CapsuleItemWidgets are used within a {@link OO.ui.CapsuleMultiSelectWidget
13437 * CapsuleMultiSelectWidget} to display the selected items.
13440 * @extends OO.ui.Widget
13441 * @mixins OO.ui.mixin.ItemWidget
13442 * @mixins OO.ui.mixin.IndicatorElement
13443 * @mixins OO.ui.mixin.LabelElement
13444 * @mixins OO.ui.mixin.FlaggedElement
13445 * @mixins OO.ui.mixin.TabIndexedElement
13448 * @param {Object} [config] Configuration options
13450 OO
.ui
.CapsuleItemWidget
= function OoUiCapsuleItemWidget( config
) {
13451 // Configuration initialization
13452 config
= config
|| {};
13454 // Parent constructor
13455 OO
.ui
.CapsuleItemWidget
.parent
.call( this, config
);
13457 // Properties (must be set before mixin constructor calls)
13458 this.$indicator
= $( '<span>' );
13460 // Mixin constructors
13461 OO
.ui
.mixin
.ItemWidget
.call( this );
13462 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$indicator
, indicator
: 'clear' } ) );
13463 OO
.ui
.mixin
.LabelElement
.call( this, config
);
13464 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
13465 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$indicator
} ) );
13468 this.$indicator
.on( {
13469 keydown
: this.onCloseKeyDown
.bind( this ),
13470 click
: this.onCloseClick
.bind( this )
13472 this.$element
.on( 'click', false );
13476 .addClass( 'oo-ui-capsuleItemWidget' )
13477 .append( this.$indicator
, this.$label
);
13482 OO
.inheritClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.Widget
);
13483 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.ItemWidget
);
13484 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.IndicatorElement
);
13485 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.LabelElement
);
13486 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.FlaggedElement
);
13487 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.TabIndexedElement
);
13492 * Handle close icon clicks
13493 * @param {jQuery.Event} event
13495 OO
.ui
.CapsuleItemWidget
.prototype.onCloseClick = function () {
13496 var element
= this.getElementGroup();
13498 if ( !this.isDisabled() && element
&& $.isFunction( element
.removeItems
) ) {
13499 element
.removeItems( [ this ] );
13505 * Handle close keyboard events
13506 * @param {jQuery.Event} event Key down event
13508 OO
.ui
.CapsuleItemWidget
.prototype.onCloseKeyDown = function ( e
) {
13509 if ( !this.isDisabled() && $.isFunction( this.getElementGroup().removeItems
) ) {
13510 switch ( e
.which
) {
13511 case OO
.ui
.Keys
.ENTER
:
13512 case OO
.ui
.Keys
.BACKSPACE
:
13513 case OO
.ui
.Keys
.SPACE
:
13514 this.getElementGroup().removeItems( [ this ] );
13521 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
13522 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
13523 * users can interact with it.
13525 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
13526 * OO.ui.DropdownInputWidget instead.
13529 * // Example: A DropdownWidget with a menu that contains three options
13530 * var dropDown = new OO.ui.DropdownWidget( {
13531 * label: 'Dropdown menu: Select a menu option',
13534 * new OO.ui.MenuOptionWidget( {
13538 * new OO.ui.MenuOptionWidget( {
13542 * new OO.ui.MenuOptionWidget( {
13550 * $( 'body' ).append( dropDown.$element );
13552 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
13554 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13557 * @extends OO.ui.Widget
13558 * @mixins OO.ui.mixin.IconElement
13559 * @mixins OO.ui.mixin.IndicatorElement
13560 * @mixins OO.ui.mixin.LabelElement
13561 * @mixins OO.ui.mixin.TitledElement
13562 * @mixins OO.ui.mixin.TabIndexedElement
13565 * @param {Object} [config] Configuration options
13566 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
13567 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
13568 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
13569 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
13571 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
13572 // Configuration initialization
13573 config
= $.extend( { indicator
: 'down' }, config
);
13575 // Parent constructor
13576 OO
.ui
.DropdownWidget
.parent
.call( this, config
);
13578 // Properties (must be set before TabIndexedElement constructor call)
13579 this.$handle
= this.$( '<span>' );
13580 this.$overlay
= config
.$overlay
|| this.$element
;
13582 // Mixin constructors
13583 OO
.ui
.mixin
.IconElement
.call( this, config
);
13584 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
13585 OO
.ui
.mixin
.LabelElement
.call( this, config
);
13586 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
13587 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
13590 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend( {
13592 $container
: this.$element
13593 }, config
.menu
) );
13597 click
: this.onClick
.bind( this ),
13598 keypress
: this.onKeyPress
.bind( this )
13600 this.menu
.connect( this, { select
: 'onMenuSelect' } );
13604 .addClass( 'oo-ui-dropdownWidget-handle' )
13605 .append( this.$icon
, this.$label
, this.$indicator
);
13607 .addClass( 'oo-ui-dropdownWidget' )
13608 .append( this.$handle
);
13609 this.$overlay
.append( this.menu
.$element
);
13614 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
13615 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IconElement
);
13616 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IndicatorElement
);
13617 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.LabelElement
);
13618 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TitledElement
);
13619 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TabIndexedElement
);
13626 * @return {OO.ui.MenuSelectWidget} Menu of widget
13628 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
13633 * Handles menu select events.
13636 * @param {OO.ui.MenuOptionWidget} item Selected menu item
13638 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
13642 this.setLabel( null );
13646 selectedLabel
= item
.getLabel();
13648 // If the label is a DOM element, clone it, because setLabel will append() it
13649 if ( selectedLabel
instanceof jQuery
) {
13650 selectedLabel
= selectedLabel
.clone();
13653 this.setLabel( selectedLabel
);
13657 * Handle mouse click events.
13660 * @param {jQuery.Event} e Mouse click event
13662 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
13663 if ( !this.isDisabled() && e
.which
=== 1 ) {
13664 this.menu
.toggle();
13670 * Handle key press events.
13673 * @param {jQuery.Event} e Key press event
13675 OO
.ui
.DropdownWidget
.prototype.onKeyPress = function ( e
) {
13676 if ( !this.isDisabled() &&
13677 ( ( e
.which
=== OO
.ui
.Keys
.SPACE
&& !this.menu
.isVisible() ) || e
.which
=== OO
.ui
.Keys
.ENTER
)
13679 this.menu
.toggle();
13685 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
13686 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
13687 * OO.ui.mixin.IndicatorElement indicators}.
13688 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
13691 * // Example of a file select widget
13692 * var selectFile = new OO.ui.SelectFileWidget();
13693 * $( 'body' ).append( selectFile.$element );
13695 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets
13698 * @extends OO.ui.Widget
13699 * @mixins OO.ui.mixin.IconElement
13700 * @mixins OO.ui.mixin.IndicatorElement
13701 * @mixins OO.ui.mixin.PendingElement
13702 * @mixins OO.ui.mixin.LabelElement
13705 * @param {Object} [config] Configuration options
13706 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
13707 * @cfg {string} [placeholder] Text to display when no file is selected.
13708 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
13709 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
13710 * @cfg {boolean} [showDropTarget=false] Whether to show a drop target. Requires droppable to be true.
13711 * @cfg {boolean} [dragDropUI=false] Deprecated alias for showDropTarget
13713 OO
.ui
.SelectFileWidget
= function OoUiSelectFileWidget( config
) {
13716 // TODO: Remove in next release
13717 if ( config
&& config
.dragDropUI
) {
13718 config
.showDropTarget
= true;
13721 // Configuration initialization
13722 config
= $.extend( {
13724 placeholder
: OO
.ui
.msg( 'ooui-selectfile-placeholder' ),
13725 notsupported
: OO
.ui
.msg( 'ooui-selectfile-not-supported' ),
13727 showDropTarget
: false
13730 // Parent constructor
13731 OO
.ui
.SelectFileWidget
.parent
.call( this, config
);
13733 // Mixin constructors
13734 OO
.ui
.mixin
.IconElement
.call( this, config
);
13735 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
13736 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$info
} ) );
13737 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { autoFitLabel
: true } ) );
13740 this.$info
= $( '<span>' );
13743 this.showDropTarget
= config
.showDropTarget
;
13744 this.isSupported
= this.constructor.static.isSupported();
13745 this.currentFile
= null;
13746 if ( Array
.isArray( config
.accept
) ) {
13747 this.accept
= config
.accept
;
13749 this.accept
= null;
13751 this.placeholder
= config
.placeholder
;
13752 this.notsupported
= config
.notsupported
;
13753 this.onFileSelectedHandler
= this.onFileSelected
.bind( this );
13755 this.selectButton
= new OO
.ui
.ButtonWidget( {
13756 classes
: [ 'oo-ui-selectFileWidget-selectButton' ],
13757 label
: 'Select a file',
13758 disabled
: this.disabled
|| !this.isSupported
13761 this.clearButton
= new OO
.ui
.ButtonWidget( {
13762 classes
: [ 'oo-ui-selectFileWidget-clearButton' ],
13765 disabled
: this.disabled
13769 this.selectButton
.$button
.on( {
13770 keypress
: this.onKeyPress
.bind( this )
13772 this.clearButton
.connect( this, {
13773 click
: 'onClearClick'
13775 if ( config
.droppable
) {
13776 dragHandler
= this.onDragEnterOrOver
.bind( this );
13777 this.$element
.on( {
13778 dragenter
: dragHandler
,
13779 dragover
: dragHandler
,
13780 dragleave
: this.onDragLeave
.bind( this ),
13781 drop
: this.onDrop
.bind( this )
13788 this.$label
.addClass( 'oo-ui-selectFileWidget-label' );
13790 .addClass( 'oo-ui-selectFileWidget-info' )
13791 .append( this.$icon
, this.$label
, this.clearButton
.$element
, this.$indicator
);
13793 .addClass( 'oo-ui-selectFileWidget' )
13794 .append( this.$info
, this.selectButton
.$element
);
13795 if ( config
.droppable
&& config
.showDropTarget
) {
13796 this.$dropTarget
= $( '<div>' )
13797 .addClass( 'oo-ui-selectFileWidget-dropTarget' )
13798 .text( OO
.ui
.msg( 'ooui-selectfile-dragdrop-placeholder' ) )
13800 click
: this.onDropTargetClick
.bind( this )
13802 this.$element
.prepend( this.$dropTarget
);
13808 OO
.inheritClass( OO
.ui
.SelectFileWidget
, OO
.ui
.Widget
);
13809 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.IconElement
);
13810 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.IndicatorElement
);
13811 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.PendingElement
);
13812 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.LabelElement
);
13814 /* Static Properties */
13817 * Check if this widget is supported
13820 * @return {boolean}
13822 OO
.ui
.SelectFileWidget
.static.isSupported = function () {
13824 if ( OO
.ui
.SelectFileWidget
.static.isSupportedCache
=== null ) {
13825 $input
= $( '<input type="file">' );
13826 OO
.ui
.SelectFileWidget
.static.isSupportedCache
= $input
[ 0 ].files
!== undefined;
13828 return OO
.ui
.SelectFileWidget
.static.isSupportedCache
;
13831 OO
.ui
.SelectFileWidget
.static.isSupportedCache
= null;
13838 * A change event is emitted when the on/off state of the toggle changes.
13840 * @param {File|null} value New value
13846 * Get the current value of the field
13848 * @return {File|null}
13850 OO
.ui
.SelectFileWidget
.prototype.getValue = function () {
13851 return this.currentFile
;
13855 * Set the current value of the field
13857 * @param {File|null} file File to select
13859 OO
.ui
.SelectFileWidget
.prototype.setValue = function ( file
) {
13860 if ( this.currentFile
!== file
) {
13861 this.currentFile
= file
;
13863 this.emit( 'change', this.currentFile
);
13868 * Update the user interface when a file is selected or unselected
13872 OO
.ui
.SelectFileWidget
.prototype.updateUI = function () {
13873 if ( !this.isSupported
) {
13874 this.$element
.addClass( 'oo-ui-selectFileWidget-notsupported' );
13875 this.$element
.removeClass( 'oo-ui-selectFileWidget-empty' );
13876 this.setLabel( this.notsupported
);
13878 this.$element
.addClass( 'oo-ui-selectFileWidget-supported' );
13879 if ( this.currentFile
) {
13880 this.$element
.removeClass( 'oo-ui-selectFileWidget-empty' );
13881 this.setLabel( this.currentFile
.name
+
13882 ( this.currentFile
.type
!== '' ? OO
.ui
.msg( 'ooui-semicolon-separator' ) + this.currentFile
.type
: '' )
13885 this.$element
.addClass( 'oo-ui-selectFileWidget-empty' );
13886 this.setLabel( this.placeholder
);
13890 if ( this.$input
) {
13891 this.$input
.attr( 'title', this.getLabel() );
13896 * Add the input to the widget
13900 OO
.ui
.SelectFileWidget
.prototype.addInput = function () {
13901 if ( this.$input
) {
13902 this.$input
.remove();
13905 if ( !this.isSupported
) {
13906 this.$input
= null;
13910 this.$input
= $( '<input type="file">' );
13911 this.$input
.on( 'change', this.onFileSelectedHandler
);
13912 this.$input
.attr( {
13914 title
: this.getLabel()
13916 if ( this.accept
) {
13917 this.$input
.attr( 'accept', this.accept
.join( ', ' ) );
13919 this.selectButton
.$button
.append( this.$input
);
13923 * Determine if we should accept this file
13926 * @param {string} File MIME type
13927 * @return {boolean}
13929 OO
.ui
.SelectFileWidget
.prototype.isAllowedType = function ( mimeType
) {
13932 if ( !this.accept
|| !mimeType
) {
13936 for ( i
= 0; i
< this.accept
.length
; i
++ ) {
13937 mimeTest
= this.accept
[ i
];
13938 if ( mimeTest
=== mimeType
) {
13940 } else if ( mimeTest
.substr( -2 ) === '/*' ) {
13941 mimeTest
= mimeTest
.substr( 0, mimeTest
.length
- 1 );
13942 if ( mimeType
.substr( 0, mimeTest
.length
) === mimeTest
) {
13952 * Handle file selection from the input
13955 * @param {jQuery.Event} e
13957 OO
.ui
.SelectFileWidget
.prototype.onFileSelected = function ( e
) {
13958 var file
= OO
.getProp( e
.target
, 'files', 0 ) || null;
13960 if ( file
&& !this.isAllowedType( file
.type
) ) {
13964 this.setValue( file
);
13969 * Handle clear button click events.
13973 OO
.ui
.SelectFileWidget
.prototype.onClearClick = function () {
13974 this.setValue( null );
13979 * Handle key press events.
13982 * @param {jQuery.Event} e Key press event
13984 OO
.ui
.SelectFileWidget
.prototype.onKeyPress = function ( e
) {
13985 if ( this.isSupported
&& !this.isDisabled() && this.$input
&&
13986 ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
13988 this.$input
.click();
13994 * Handle drop target click events.
13997 * @param {jQuery.Event} e Key press event
13999 OO
.ui
.SelectFileWidget
.prototype.onDropTargetClick = function () {
14000 if ( this.isSupported
&& !this.isDisabled() && this.$input
) {
14001 this.$input
.click();
14007 * Handle drag enter and over events
14010 * @param {jQuery.Event} e Drag event
14012 OO
.ui
.SelectFileWidget
.prototype.onDragEnterOrOver = function ( e
) {
14014 droppableFile
= false,
14015 dt
= e
.originalEvent
.dataTransfer
;
14017 e
.preventDefault();
14018 e
.stopPropagation();
14020 if ( this.isDisabled() || !this.isSupported
) {
14021 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14022 dt
.dropEffect
= 'none';
14026 // DataTransferItem and File both have a type property, but in Chrome files
14027 // have no information at this point.
14028 itemOrFile
= OO
.getProp( dt
, 'items', 0 ) || OO
.getProp( dt
, 'files', 0 );
14029 if ( itemOrFile
) {
14030 if ( this.isAllowedType( itemOrFile
.type
) ) {
14031 droppableFile
= true;
14033 // dt.types is Array-like, but not an Array
14034 } else if ( Array
.prototype.indexOf
.call( OO
.getProp( dt
, 'types' ) || [], 'Files' ) !== -1 ) {
14035 // File information is not available at this point for security so just assume
14036 // it is acceptable for now.
14037 // https://bugzilla.mozilla.org/show_bug.cgi?id=640534
14038 droppableFile
= true;
14041 this.$element
.toggleClass( 'oo-ui-selectFileWidget-canDrop', droppableFile
);
14042 if ( !droppableFile
) {
14043 dt
.dropEffect
= 'none';
14050 * Handle drag leave events
14053 * @param {jQuery.Event} e Drag event
14055 OO
.ui
.SelectFileWidget
.prototype.onDragLeave = function () {
14056 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14060 * Handle drop events
14063 * @param {jQuery.Event} e Drop event
14065 OO
.ui
.SelectFileWidget
.prototype.onDrop = function ( e
) {
14067 dt
= e
.originalEvent
.dataTransfer
;
14069 e
.preventDefault();
14070 e
.stopPropagation();
14071 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14073 if ( this.isDisabled() || !this.isSupported
) {
14077 file
= OO
.getProp( dt
, 'files', 0 );
14078 if ( file
&& !this.isAllowedType( file
.type
) ) {
14082 this.setValue( file
);
14091 OO
.ui
.SelectFileWidget
.prototype.setDisabled = function ( disabled
) {
14092 OO
.ui
.SelectFileWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
14093 if ( this.selectButton
) {
14094 this.selectButton
.setDisabled( disabled
);
14096 if ( this.clearButton
) {
14097 this.clearButton
.setDisabled( disabled
);
14103 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
14104 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
14105 * for a list of icons included in the library.
14108 * // An icon widget with a label
14109 * var myIcon = new OO.ui.IconWidget( {
14111 * iconTitle: 'Help'
14113 * // Create a label.
14114 * var iconLabel = new OO.ui.LabelWidget( {
14117 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
14119 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
14122 * @extends OO.ui.Widget
14123 * @mixins OO.ui.mixin.IconElement
14124 * @mixins OO.ui.mixin.TitledElement
14125 * @mixins OO.ui.mixin.FlaggedElement
14128 * @param {Object} [config] Configuration options
14130 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
14131 // Configuration initialization
14132 config
= config
|| {};
14134 // Parent constructor
14135 OO
.ui
.IconWidget
.parent
.call( this, config
);
14137 // Mixin constructors
14138 OO
.ui
.mixin
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
14139 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
14140 OO
.ui
.mixin
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
14143 this.$element
.addClass( 'oo-ui-iconWidget' );
14148 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
14149 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.IconElement
);
14150 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.TitledElement
);
14151 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.FlaggedElement
);
14153 /* Static Properties */
14155 OO
.ui
.IconWidget
.static.tagName
= 'span';
14158 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
14159 * attention to the status of an item or to clarify the function of a control. For a list of
14160 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
14163 * // Example of an indicator widget
14164 * var indicator1 = new OO.ui.IndicatorWidget( {
14165 * indicator: 'alert'
14168 * // Create a fieldset layout to add a label
14169 * var fieldset = new OO.ui.FieldsetLayout();
14170 * fieldset.addItems( [
14171 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
14173 * $( 'body' ).append( fieldset.$element );
14175 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
14178 * @extends OO.ui.Widget
14179 * @mixins OO.ui.mixin.IndicatorElement
14180 * @mixins OO.ui.mixin.TitledElement
14183 * @param {Object} [config] Configuration options
14185 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
14186 // Configuration initialization
14187 config
= config
|| {};
14189 // Parent constructor
14190 OO
.ui
.IndicatorWidget
.parent
.call( this, config
);
14192 // Mixin constructors
14193 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
14194 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
14197 this.$element
.addClass( 'oo-ui-indicatorWidget' );
14202 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
14203 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.IndicatorElement
);
14204 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.TitledElement
);
14206 /* Static Properties */
14208 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
14211 * InputWidget is the base class for all input widgets, which
14212 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
14213 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
14214 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14216 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14220 * @extends OO.ui.Widget
14221 * @mixins OO.ui.mixin.FlaggedElement
14222 * @mixins OO.ui.mixin.TabIndexedElement
14223 * @mixins OO.ui.mixin.TitledElement
14224 * @mixins OO.ui.mixin.AccessKeyedElement
14227 * @param {Object} [config] Configuration options
14228 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
14229 * @cfg {string} [value=''] The value of the input.
14230 * @cfg {string} [accessKey=''] The access key of the input.
14231 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
14232 * before it is accepted.
14234 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
14235 // Configuration initialization
14236 config
= config
|| {};
14238 // Parent constructor
14239 OO
.ui
.InputWidget
.parent
.call( this, config
);
14242 this.$input
= this.getInputElement( config
);
14244 this.inputFilter
= config
.inputFilter
;
14246 // Mixin constructors
14247 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
14248 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
14249 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
14250 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$input
} ) );
14253 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
14257 .addClass( 'oo-ui-inputWidget-input' )
14258 .attr( 'name', config
.name
)
14259 .prop( 'disabled', this.isDisabled() );
14261 .addClass( 'oo-ui-inputWidget' )
14262 .append( this.$input
);
14263 this.setValue( config
.value
);
14264 this.setAccessKey( config
.accessKey
);
14269 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
14270 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.FlaggedElement
);
14271 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TabIndexedElement
);
14272 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TitledElement
);
14273 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
14275 /* Static Properties */
14277 OO
.ui
.InputWidget
.static.supportsSimpleLabel
= true;
14284 * A change event is emitted when the value of the input changes.
14286 * @param {string} value
14292 * Get input element.
14294 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
14295 * different circumstances. The element must have a `value` property (like form elements).
14298 * @param {Object} config Configuration options
14299 * @return {jQuery} Input element
14301 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
14302 return $( '<input>' );
14306 * Handle potentially value-changing events.
14309 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
14311 OO
.ui
.InputWidget
.prototype.onEdit = function () {
14313 if ( !this.isDisabled() ) {
14314 // Allow the stack to clear so the value will be updated
14315 setTimeout( function () {
14316 widget
.setValue( widget
.$input
.val() );
14322 * Get the value of the input.
14324 * @return {string} Input value
14326 OO
.ui
.InputWidget
.prototype.getValue = function () {
14327 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14328 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14329 var value
= this.$input
.val();
14330 if ( this.value
!== value
) {
14331 this.setValue( value
);
14337 * Set the direction of the input, either RTL (right-to-left) or LTR (left-to-right).
14339 * @param {boolean} isRTL
14340 * Direction is right-to-left
14342 OO
.ui
.InputWidget
.prototype.setRTL = function ( isRTL
) {
14343 this.$input
.prop( 'dir', isRTL
? 'rtl' : 'ltr' );
14347 * Set the value of the input.
14349 * @param {string} value New value
14353 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
14354 value
= this.cleanUpValue( value
);
14355 // Update the DOM if it has changed. Note that with cleanUpValue, it
14356 // is possible for the DOM value to change without this.value changing.
14357 if ( this.$input
.val() !== value
) {
14358 this.$input
.val( value
);
14360 if ( this.value
!== value
) {
14361 this.value
= value
;
14362 this.emit( 'change', this.value
);
14368 * Set the input's access key.
14369 * FIXME: This is the same code as in OO.ui.mixin.ButtonElement, maybe find a better place for it?
14371 * @param {string} accessKey Input's access key, use empty string to remove
14374 OO
.ui
.InputWidget
.prototype.setAccessKey = function ( accessKey
) {
14375 accessKey
= typeof accessKey
=== 'string' && accessKey
.length
? accessKey
: null;
14377 if ( this.accessKey
!== accessKey
) {
14378 if ( this.$input
) {
14379 if ( accessKey
!== null ) {
14380 this.$input
.attr( 'accesskey', accessKey
);
14382 this.$input
.removeAttr( 'accesskey' );
14385 this.accessKey
= accessKey
;
14392 * Clean up incoming value.
14394 * Ensures value is a string, and converts undefined and null to empty string.
14397 * @param {string} value Original value
14398 * @return {string} Cleaned up value
14400 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
14401 if ( value
=== undefined || value
=== null ) {
14403 } else if ( this.inputFilter
) {
14404 return this.inputFilter( String( value
) );
14406 return String( value
);
14411 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
14412 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
14415 OO
.ui
.InputWidget
.prototype.simulateLabelClick = function () {
14416 if ( !this.isDisabled() ) {
14417 if ( this.$input
.is( ':checkbox, :radio' ) ) {
14418 this.$input
.click();
14420 if ( this.$input
.is( ':input' ) ) {
14421 this.$input
[ 0 ].focus();
14429 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
14430 OO
.ui
.InputWidget
.parent
.prototype.setDisabled
.call( this, state
);
14431 if ( this.$input
) {
14432 this.$input
.prop( 'disabled', this.isDisabled() );
14442 OO
.ui
.InputWidget
.prototype.focus = function () {
14443 this.$input
[ 0 ].focus();
14452 OO
.ui
.InputWidget
.prototype.blur = function () {
14453 this.$input
[ 0 ].blur();
14460 OO
.ui
.InputWidget
.prototype.gatherPreInfuseState = function ( node
) {
14462 state
= OO
.ui
.InputWidget
.parent
.prototype.gatherPreInfuseState
.call( this, node
),
14463 $input
= state
.$input
|| $( node
).find( '.oo-ui-inputWidget-input' );
14464 state
.value
= $input
.val();
14465 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
14466 state
.focus
= $input
.is( ':focus' );
14473 OO
.ui
.InputWidget
.prototype.restorePreInfuseState = function ( state
) {
14474 OO
.ui
.InputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
14475 if ( state
.value
!== undefined && state
.value
!== this.getValue() ) {
14476 this.setValue( state
.value
);
14478 if ( state
.focus
) {
14484 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
14485 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
14486 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
14487 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
14488 * [OOjs UI documentation on MediaWiki] [1] for more information.
14491 * // A ButtonInputWidget rendered as an HTML button, the default.
14492 * var button = new OO.ui.ButtonInputWidget( {
14493 * label: 'Input button',
14497 * $( 'body' ).append( button.$element );
14499 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
14502 * @extends OO.ui.InputWidget
14503 * @mixins OO.ui.mixin.ButtonElement
14504 * @mixins OO.ui.mixin.IconElement
14505 * @mixins OO.ui.mixin.IndicatorElement
14506 * @mixins OO.ui.mixin.LabelElement
14507 * @mixins OO.ui.mixin.TitledElement
14510 * @param {Object} [config] Configuration options
14511 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
14512 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
14513 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
14514 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
14515 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
14517 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
14518 // Configuration initialization
14519 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
14521 // Properties (must be set before parent constructor, which calls #setValue)
14522 this.useInputTag
= config
.useInputTag
;
14524 // Parent constructor
14525 OO
.ui
.ButtonInputWidget
.parent
.call( this, config
);
14527 // Mixin constructors
14528 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
14529 OO
.ui
.mixin
.IconElement
.call( this, config
);
14530 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
14531 OO
.ui
.mixin
.LabelElement
.call( this, config
);
14532 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
14535 if ( !config
.useInputTag
) {
14536 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
14538 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
14543 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
14544 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.ButtonElement
);
14545 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IconElement
);
14546 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
14547 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.LabelElement
);
14548 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.TitledElement
);
14550 /* Static Properties */
14553 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
14554 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
14556 OO
.ui
.ButtonInputWidget
.static.supportsSimpleLabel
= false;
14564 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
14565 var type
= [ 'button', 'submit', 'reset' ].indexOf( config
.type
) !== -1 ?
14568 return $( '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + type
+ '">' );
14574 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
14576 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
14577 * text, or `null` for no label
14580 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
14581 OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.call( this, label
);
14583 if ( this.useInputTag
) {
14584 if ( typeof label
=== 'function' ) {
14585 label
= OO
.ui
.resolveMsg( label
);
14587 if ( label
instanceof jQuery
) {
14588 label
= label
.text();
14593 this.$input
.val( label
);
14600 * Set the value of the input.
14602 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
14603 * they do not support {@link #value values}.
14605 * @param {string} value New value
14608 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
14609 if ( !this.useInputTag
) {
14610 OO
.ui
.ButtonInputWidget
.parent
.prototype.setValue
.call( this, value
);
14616 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
14617 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
14618 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
14619 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
14621 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
14624 * // An example of selected, unselected, and disabled checkbox inputs
14625 * var checkbox1=new OO.ui.CheckboxInputWidget( {
14629 * var checkbox2=new OO.ui.CheckboxInputWidget( {
14632 * var checkbox3=new OO.ui.CheckboxInputWidget( {
14636 * // Create a fieldset layout with fields for each checkbox.
14637 * var fieldset = new OO.ui.FieldsetLayout( {
14638 * label: 'Checkboxes'
14640 * fieldset.addItems( [
14641 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
14642 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
14643 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
14645 * $( 'body' ).append( fieldset.$element );
14647 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14650 * @extends OO.ui.InputWidget
14653 * @param {Object} [config] Configuration options
14654 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
14656 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
14657 // Configuration initialization
14658 config
= config
|| {};
14660 // Parent constructor
14661 OO
.ui
.CheckboxInputWidget
.parent
.call( this, config
);
14665 .addClass( 'oo-ui-checkboxInputWidget' )
14666 // Required for pretty styling in MediaWiki theme
14667 .append( $( '<span>' ) );
14668 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
14673 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
14681 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
14682 return $( '<input type="checkbox" />' );
14688 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
14690 if ( !this.isDisabled() ) {
14691 // Allow the stack to clear so the value will be updated
14692 setTimeout( function () {
14693 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
14699 * Set selection state of this checkbox.
14701 * @param {boolean} state `true` for selected
14704 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
14706 if ( this.selected
!== state
) {
14707 this.selected
= state
;
14708 this.$input
.prop( 'checked', this.selected
);
14709 this.emit( 'change', this.selected
);
14715 * Check if this checkbox is selected.
14717 * @return {boolean} Checkbox is selected
14719 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
14720 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14721 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14722 var selected
= this.$input
.prop( 'checked' );
14723 if ( this.selected
!== selected
) {
14724 this.setSelected( selected
);
14726 return this.selected
;
14732 OO
.ui
.CheckboxInputWidget
.prototype.gatherPreInfuseState = function ( node
) {
14734 state
= OO
.ui
.CheckboxInputWidget
.parent
.prototype.gatherPreInfuseState
.call( this, node
),
14735 $input
= $( node
).find( '.oo-ui-inputWidget-input' );
14736 state
.$input
= $input
; // shortcut for performance, used in InputWidget
14737 state
.checked
= $input
.prop( 'checked' );
14744 OO
.ui
.CheckboxInputWidget
.prototype.restorePreInfuseState = function ( state
) {
14745 OO
.ui
.CheckboxInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
14746 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
14747 this.setSelected( state
.checked
);
14752 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
14753 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
14754 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
14755 * more information about input widgets.
14757 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
14758 * are no options. If no `value` configuration option is provided, the first option is selected.
14759 * If you need a state representing no value (no option being selected), use a DropdownWidget.
14761 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
14764 * // Example: A DropdownInputWidget with three options
14765 * var dropdownInput = new OO.ui.DropdownInputWidget( {
14767 * { data: 'a', label: 'First' },
14768 * { data: 'b', label: 'Second'},
14769 * { data: 'c', label: 'Third' }
14772 * $( 'body' ).append( dropdownInput.$element );
14774 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14777 * @extends OO.ui.InputWidget
14778 * @mixins OO.ui.mixin.TitledElement
14781 * @param {Object} [config] Configuration options
14782 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
14783 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
14785 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
14786 // Configuration initialization
14787 config
= config
|| {};
14789 // Properties (must be done before parent constructor which calls #setDisabled)
14790 this.dropdownWidget
= new OO
.ui
.DropdownWidget( config
.dropdown
);
14792 // Parent constructor
14793 OO
.ui
.DropdownInputWidget
.parent
.call( this, config
);
14795 // Mixin constructors
14796 OO
.ui
.mixin
.TitledElement
.call( this, config
);
14799 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
14802 this.setOptions( config
.options
|| [] );
14804 .addClass( 'oo-ui-dropdownInputWidget' )
14805 .append( this.dropdownWidget
.$element
);
14810 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
14811 OO
.mixinClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.mixin
.TitledElement
);
14819 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
14820 return $( '<input type="hidden">' );
14824 * Handles menu select events.
14827 * @param {OO.ui.MenuOptionWidget} item Selected menu item
14829 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
14830 this.setValue( item
.getData() );
14836 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
14837 value
= this.cleanUpValue( value
);
14838 this.dropdownWidget
.getMenu().selectItemByData( value
);
14839 OO
.ui
.DropdownInputWidget
.parent
.prototype.setValue
.call( this, value
);
14846 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
14847 this.dropdownWidget
.setDisabled( state
);
14848 OO
.ui
.DropdownInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
14853 * Set the options available for this input.
14855 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
14858 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
14860 value
= this.getValue(),
14863 // Rebuild the dropdown menu
14864 this.dropdownWidget
.getMenu()
14866 .addItems( options
.map( function ( opt
) {
14867 var optValue
= widget
.cleanUpValue( opt
.data
);
14868 return new OO
.ui
.MenuOptionWidget( {
14870 label
: opt
.label
!== undefined ? opt
.label
: optValue
14874 // Restore the previous value, or reset to something sensible
14875 if ( this.dropdownWidget
.getMenu().getItemFromData( value
) ) {
14876 // Previous value is still available, ensure consistency with the dropdown
14877 this.setValue( value
);
14879 // No longer valid, reset
14880 if ( options
.length
) {
14881 this.setValue( options
[ 0 ].data
);
14891 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
14892 this.dropdownWidget
.getMenu().toggle( true );
14899 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
14900 this.dropdownWidget
.getMenu().toggle( false );
14905 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
14906 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
14907 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
14908 * please see the [OOjs UI documentation on MediaWiki][1].
14910 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
14913 * // An example of selected, unselected, and disabled radio inputs
14914 * var radio1 = new OO.ui.RadioInputWidget( {
14918 * var radio2 = new OO.ui.RadioInputWidget( {
14921 * var radio3 = new OO.ui.RadioInputWidget( {
14925 * // Create a fieldset layout with fields for each radio button.
14926 * var fieldset = new OO.ui.FieldsetLayout( {
14927 * label: 'Radio inputs'
14929 * fieldset.addItems( [
14930 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
14931 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
14932 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
14934 * $( 'body' ).append( fieldset.$element );
14936 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14939 * @extends OO.ui.InputWidget
14942 * @param {Object} [config] Configuration options
14943 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
14945 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
14946 // Configuration initialization
14947 config
= config
|| {};
14949 // Parent constructor
14950 OO
.ui
.RadioInputWidget
.parent
.call( this, config
);
14954 .addClass( 'oo-ui-radioInputWidget' )
14955 // Required for pretty styling in MediaWiki theme
14956 .append( $( '<span>' ) );
14957 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
14962 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
14970 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
14971 return $( '<input type="radio" />' );
14977 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
14978 // RadioInputWidget doesn't track its state.
14982 * Set selection state of this radio button.
14984 * @param {boolean} state `true` for selected
14987 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
14988 // RadioInputWidget doesn't track its state.
14989 this.$input
.prop( 'checked', state
);
14994 * Check if this radio button is selected.
14996 * @return {boolean} Radio is selected
14998 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
14999 return this.$input
.prop( 'checked' );
15005 OO
.ui
.RadioInputWidget
.prototype.gatherPreInfuseState = function ( node
) {
15007 state
= OO
.ui
.RadioInputWidget
.parent
.prototype.gatherPreInfuseState
.call( this, node
),
15008 $input
= $( node
).find( '.oo-ui-inputWidget-input' );
15009 state
.$input
= $input
; // shortcut for performance, used in InputWidget
15010 state
.checked
= $input
.prop( 'checked' );
15017 OO
.ui
.RadioInputWidget
.prototype.restorePreInfuseState = function ( state
) {
15018 OO
.ui
.RadioInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
15019 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
15020 this.setSelected( state
.checked
);
15025 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
15026 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
15027 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
15028 * more information about input widgets.
15030 * This and OO.ui.DropdownInputWidget support the same configuration options.
15033 * // Example: A RadioSelectInputWidget with three options
15034 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
15036 * { data: 'a', label: 'First' },
15037 * { data: 'b', label: 'Second'},
15038 * { data: 'c', label: 'Third' }
15041 * $( 'body' ).append( radioSelectInput.$element );
15043 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15046 * @extends OO.ui.InputWidget
15049 * @param {Object} [config] Configuration options
15050 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15052 OO
.ui
.RadioSelectInputWidget
= function OoUiRadioSelectInputWidget( config
) {
15053 // Configuration initialization
15054 config
= config
|| {};
15056 // Properties (must be done before parent constructor which calls #setDisabled)
15057 this.radioSelectWidget
= new OO
.ui
.RadioSelectWidget();
15059 // Parent constructor
15060 OO
.ui
.RadioSelectInputWidget
.parent
.call( this, config
);
15063 this.radioSelectWidget
.connect( this, { select
: 'onMenuSelect' } );
15066 this.setOptions( config
.options
|| [] );
15068 .addClass( 'oo-ui-radioSelectInputWidget' )
15069 .append( this.radioSelectWidget
.$element
);
15074 OO
.inheritClass( OO
.ui
.RadioSelectInputWidget
, OO
.ui
.InputWidget
);
15076 /* Static Properties */
15078 OO
.ui
.RadioSelectInputWidget
.static.supportsSimpleLabel
= false;
15086 OO
.ui
.RadioSelectInputWidget
.prototype.getInputElement = function () {
15087 return $( '<input type="hidden">' );
15091 * Handles menu select events.
15094 * @param {OO.ui.RadioOptionWidget} item Selected menu item
15096 OO
.ui
.RadioSelectInputWidget
.prototype.onMenuSelect = function ( item
) {
15097 this.setValue( item
.getData() );
15103 OO
.ui
.RadioSelectInputWidget
.prototype.setValue = function ( value
) {
15104 value
= this.cleanUpValue( value
);
15105 this.radioSelectWidget
.selectItemByData( value
);
15106 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setValue
.call( this, value
);
15113 OO
.ui
.RadioSelectInputWidget
.prototype.setDisabled = function ( state
) {
15114 this.radioSelectWidget
.setDisabled( state
);
15115 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
15120 * Set the options available for this input.
15122 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15125 OO
.ui
.RadioSelectInputWidget
.prototype.setOptions = function ( options
) {
15127 value
= this.getValue(),
15130 // Rebuild the radioSelect menu
15131 this.radioSelectWidget
15133 .addItems( options
.map( function ( opt
) {
15134 var optValue
= widget
.cleanUpValue( opt
.data
);
15135 return new OO
.ui
.RadioOptionWidget( {
15137 label
: opt
.label
!== undefined ? opt
.label
: optValue
15141 // Restore the previous value, or reset to something sensible
15142 if ( this.radioSelectWidget
.getItemFromData( value
) ) {
15143 // Previous value is still available, ensure consistency with the radioSelect
15144 this.setValue( value
);
15146 // No longer valid, reset
15147 if ( options
.length
) {
15148 this.setValue( options
[ 0 ].data
);
15158 OO
.ui
.RadioSelectInputWidget
.prototype.gatherPreInfuseState = function ( node
) {
15159 var state
= OO
.ui
.RadioSelectInputWidget
.parent
.prototype.gatherPreInfuseState
.call( this, node
);
15160 state
.value
= $( node
).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
15165 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
15166 * size of the field as well as its presentation. In addition, these widgets can be configured
15167 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
15168 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
15169 * which modifies incoming values rather than validating them.
15170 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
15172 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15175 * // Example of a text input widget
15176 * var textInput = new OO.ui.TextInputWidget( {
15177 * value: 'Text input'
15179 * $( 'body' ).append( textInput.$element );
15181 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15184 * @extends OO.ui.InputWidget
15185 * @mixins OO.ui.mixin.IconElement
15186 * @mixins OO.ui.mixin.IndicatorElement
15187 * @mixins OO.ui.mixin.PendingElement
15188 * @mixins OO.ui.mixin.LabelElement
15191 * @param {Object} [config] Configuration options
15192 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
15193 * 'email' or 'url'. Ignored if `multiline` is true.
15195 * Some values of `type` result in additional behaviors:
15197 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
15198 * empties the text field
15199 * @cfg {string} [placeholder] Placeholder text
15200 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
15201 * instruct the browser to focus this widget.
15202 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
15203 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
15204 * @cfg {boolean} [multiline=false] Allow multiple lines of text
15205 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
15206 * specifies minimum number of rows to display.
15207 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
15208 * Use the #maxRows config to specify a maximum number of displayed rows.
15209 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
15210 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
15211 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
15212 * the value or placeholder text: `'before'` or `'after'`
15213 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
15214 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
15215 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
15216 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
15217 * (the value must contain only numbers); when RegExp, a regular expression that must match the
15218 * value for it to be considered valid; when Function, a function receiving the value as parameter
15219 * that must return true, or promise resolving to true, for it to be considered valid.
15221 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
15222 // Configuration initialization
15223 config
= $.extend( {
15225 labelPosition
: 'after'
15227 if ( config
.type
=== 'search' ) {
15228 if ( config
.icon
=== undefined ) {
15229 config
.icon
= 'search';
15231 // indicator: 'clear' is set dynamically later, depending on value
15233 if ( config
.required
) {
15234 if ( config
.indicator
=== undefined ) {
15235 config
.indicator
= 'required';
15239 // Parent constructor
15240 OO
.ui
.TextInputWidget
.parent
.call( this, config
);
15242 // Mixin constructors
15243 OO
.ui
.mixin
.IconElement
.call( this, config
);
15244 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
15245 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$input
} ) );
15246 OO
.ui
.mixin
.LabelElement
.call( this, config
);
15249 this.type
= this.getSaneType( config
);
15250 this.readOnly
= false;
15251 this.multiline
= !!config
.multiline
;
15252 this.autosize
= !!config
.autosize
;
15253 this.minRows
= config
.rows
!== undefined ? config
.rows
: '';
15254 this.maxRows
= config
.maxRows
|| Math
.max( 2 * ( this.minRows
|| 0 ), 10 );
15255 this.validate
= null;
15257 // Clone for resizing
15258 if ( this.autosize
) {
15259 this.$clone
= this.$input
15261 .insertAfter( this.$input
)
15262 .attr( 'aria-hidden', 'true' )
15263 .addClass( 'oo-ui-element-hidden' );
15266 this.setValidation( config
.validate
);
15267 this.setLabelPosition( config
.labelPosition
);
15271 keypress
: this.onKeyPress
.bind( this ),
15272 blur
: this.onBlur
.bind( this )
15275 focus
: this.onElementAttach
.bind( this )
15277 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
15278 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
15279 this.on( 'labelChange', this.updatePosition
.bind( this ) );
15280 this.connect( this, {
15281 change
: 'onChange',
15282 disable
: 'onDisable'
15287 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type
)
15288 .append( this.$icon
, this.$indicator
);
15289 this.setReadOnly( !!config
.readOnly
);
15290 this.updateSearchIndicator();
15291 if ( config
.placeholder
) {
15292 this.$input
.attr( 'placeholder', config
.placeholder
);
15294 if ( config
.maxLength
!== undefined ) {
15295 this.$input
.attr( 'maxlength', config
.maxLength
);
15297 if ( config
.autofocus
) {
15298 this.$input
.attr( 'autofocus', 'autofocus' );
15300 if ( config
.required
) {
15301 this.$input
.attr( 'required', 'required' );
15302 this.$input
.attr( 'aria-required', 'true' );
15304 if ( config
.autocomplete
=== false ) {
15305 this.$input
.attr( 'autocomplete', 'off' );
15307 if ( this.multiline
&& config
.rows
) {
15308 this.$input
.attr( 'rows', config
.rows
);
15310 if ( this.label
|| config
.autosize
) {
15311 this.installParentChangeDetector();
15317 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
15318 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IconElement
);
15319 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
15320 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.PendingElement
);
15321 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.LabelElement
);
15323 /* Static Properties */
15325 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
15333 * An `enter` event is emitted when the user presses 'enter' inside the text box.
15335 * Not emitted if the input is multiline.
15343 * Handle icon mouse down events.
15346 * @param {jQuery.Event} e Mouse down event
15349 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
15350 if ( e
.which
=== 1 ) {
15351 this.$input
[ 0 ].focus();
15357 * Handle indicator mouse down events.
15360 * @param {jQuery.Event} e Mouse down event
15363 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
15364 if ( e
.which
=== 1 ) {
15365 if ( this.type
=== 'search' ) {
15366 // Clear the text field
15367 this.setValue( '' );
15369 this.$input
[ 0 ].focus();
15375 * Handle key press events.
15378 * @param {jQuery.Event} e Key press event
15379 * @fires enter If enter key is pressed and input is not multiline
15381 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
15382 if ( e
.which
=== OO
.ui
.Keys
.ENTER
&& !this.multiline
) {
15383 this.emit( 'enter', e
);
15388 * Handle blur events.
15391 * @param {jQuery.Event} e Blur event
15393 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
15394 this.setValidityFlag();
15398 * Handle element attach events.
15401 * @param {jQuery.Event} e Element attach event
15403 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
15404 // Any previously calculated size is now probably invalid if we reattached elsewhere
15405 this.valCache
= null;
15407 this.positionLabel();
15411 * Handle change events.
15413 * @param {string} value
15416 OO
.ui
.TextInputWidget
.prototype.onChange = function () {
15417 this.updateSearchIndicator();
15418 this.setValidityFlag();
15423 * Handle disable events.
15425 * @param {boolean} disabled Element is disabled
15428 OO
.ui
.TextInputWidget
.prototype.onDisable = function () {
15429 this.updateSearchIndicator();
15433 * Check if the input is {@link #readOnly read-only}.
15435 * @return {boolean}
15437 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
15438 return this.readOnly
;
15442 * Set the {@link #readOnly read-only} state of the input.
15444 * @param {boolean} state Make input read-only
15447 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
15448 this.readOnly
= !!state
;
15449 this.$input
.prop( 'readOnly', this.readOnly
);
15450 this.updateSearchIndicator();
15455 * Support function for making #onElementAttach work across browsers.
15457 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
15458 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
15460 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
15461 * first time that the element gets attached to the documented.
15463 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
15464 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
15465 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
15468 if ( MutationObserver
) {
15469 // The new way. If only it wasn't so ugly.
15471 if ( this.$element
.closest( 'html' ).length
) {
15472 // Widget is attached already, do nothing. This breaks the functionality of this function when
15473 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
15474 // would require observation of the whole document, which would hurt performance of other,
15475 // more important code.
15479 // Find topmost node in the tree
15480 topmostNode
= this.$element
[ 0 ];
15481 while ( topmostNode
.parentNode
) {
15482 topmostNode
= topmostNode
.parentNode
;
15485 // We have no way to detect the $element being attached somewhere without observing the entire
15486 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
15487 // parent node of $element, and instead detect when $element is removed from it (and thus
15488 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
15489 // doesn't get attached, we end up back here and create the parent.
15491 mutationObserver
= new MutationObserver( function ( mutations
) {
15492 var i
, j
, removedNodes
;
15493 for ( i
= 0; i
< mutations
.length
; i
++ ) {
15494 removedNodes
= mutations
[ i
].removedNodes
;
15495 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
15496 if ( removedNodes
[ j
] === topmostNode
) {
15497 setTimeout( onRemove
, 0 );
15504 onRemove = function () {
15505 // If the node was attached somewhere else, report it
15506 if ( widget
.$element
.closest( 'html' ).length
) {
15507 widget
.onElementAttach();
15509 mutationObserver
.disconnect();
15510 widget
.installParentChangeDetector();
15513 // Create a fake parent and observe it
15514 fakeParentNode
= $( '<div>' ).append( topmostNode
)[ 0 ];
15515 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
15517 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
15518 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
15519 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
15524 * Automatically adjust the size of the text input.
15526 * This only affects #multiline inputs that are {@link #autosize autosized}.
15530 OO
.ui
.TextInputWidget
.prototype.adjustSize = function () {
15531 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
, idealHeight
;
15533 if ( this.multiline
&& this.autosize
&& this.$input
.val() !== this.valCache
) {
15535 .val( this.$input
.val() )
15536 .attr( 'rows', this.minRows
)
15537 // Set inline height property to 0 to measure scroll height
15538 .css( 'height', 0 );
15540 this.$clone
.removeClass( 'oo-ui-element-hidden' );
15542 this.valCache
= this.$input
.val();
15544 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
15546 // Remove inline height property to measure natural heights
15547 this.$clone
.css( 'height', '' );
15548 innerHeight
= this.$clone
.innerHeight();
15549 outerHeight
= this.$clone
.outerHeight();
15551 // Measure max rows height
15553 .attr( 'rows', this.maxRows
)
15554 .css( 'height', 'auto' )
15556 maxInnerHeight
= this.$clone
.innerHeight();
15558 // Difference between reported innerHeight and scrollHeight with no scrollbars present
15559 // Equals 1 on Blink-based browsers and 0 everywhere else
15560 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
15561 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
15563 this.$clone
.addClass( 'oo-ui-element-hidden' );
15565 // Only apply inline height when expansion beyond natural height is needed
15566 if ( idealHeight
> innerHeight
) {
15567 // Use the difference between the inner and outer height as a buffer
15568 this.$input
.css( 'height', idealHeight
+ ( outerHeight
- innerHeight
) );
15570 this.$input
.css( 'height', '' );
15580 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
15581 return config
.multiline
?
15582 $( '<textarea>' ) :
15583 $( '<input type="' + this.getSaneType( config
) + '" />' );
15587 * Get sanitized value for 'type' for given config.
15589 * @param {Object} config Configuration options
15590 * @return {string|null}
15593 OO
.ui
.TextInputWidget
.prototype.getSaneType = function ( config
) {
15594 var type
= [ 'text', 'password', 'search', 'email', 'url' ].indexOf( config
.type
) !== -1 ?
15597 return config
.multiline
? 'multiline' : type
;
15601 * Check if the input supports multiple lines.
15603 * @return {boolean}
15605 OO
.ui
.TextInputWidget
.prototype.isMultiline = function () {
15606 return !!this.multiline
;
15610 * Check if the input automatically adjusts its size.
15612 * @return {boolean}
15614 OO
.ui
.TextInputWidget
.prototype.isAutosizing = function () {
15615 return !!this.autosize
;
15619 * Select the entire text of the input.
15623 OO
.ui
.TextInputWidget
.prototype.select = function () {
15624 this.$input
.select();
15629 * Focus the input and move the cursor to the end.
15631 OO
.ui
.TextInputWidget
.prototype.moveCursorToEnd = function () {
15633 element
= this.$input
[ 0 ];
15635 if ( element
.selectionStart
!== undefined ) {
15636 element
.selectionStart
= element
.selectionEnd
= element
.value
.length
;
15637 } else if ( element
.createTextRange
) {
15639 textRange
= element
.createTextRange();
15640 textRange
.collapse( false );
15641 textRange
.select();
15646 * Set the validation pattern.
15648 * The validation pattern is either a regular expression, a function, or the symbolic name of a
15649 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
15650 * value must contain only numbers).
15652 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
15653 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
15655 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
15656 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
15657 this.validate
= validate
;
15659 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
15664 * Sets the 'invalid' flag appropriately.
15666 * @param {boolean} [isValid] Optionally override validation result
15668 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
15670 setFlag = function ( valid
) {
15672 widget
.$input
.attr( 'aria-invalid', 'true' );
15674 widget
.$input
.removeAttr( 'aria-invalid' );
15676 widget
.setFlags( { invalid
: !valid
} );
15679 if ( isValid
!== undefined ) {
15680 setFlag( isValid
);
15682 this.getValidity().then( function () {
15691 * Check if a value is valid.
15693 * This method returns a promise that resolves with a boolean `true` if the current value is
15694 * considered valid according to the supplied {@link #validate validation pattern}.
15697 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
15699 OO
.ui
.TextInputWidget
.prototype.isValid = function () {
15702 if ( this.validate
instanceof Function
) {
15703 result
= this.validate( this.getValue() );
15704 if ( $.isFunction( result
.promise
) ) {
15705 return result
.promise();
15707 return $.Deferred().resolve( !!result
).promise();
15710 return $.Deferred().resolve( !!this.getValue().match( this.validate
) ).promise();
15715 * Get the validity of current value.
15717 * This method returns a promise that resolves if the value is valid and rejects if
15718 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
15720 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
15722 OO
.ui
.TextInputWidget
.prototype.getValidity = function () {
15723 var result
, promise
;
15725 function rejectOrResolve( valid
) {
15727 return $.Deferred().resolve().promise();
15729 return $.Deferred().reject().promise();
15733 if ( this.validate
instanceof Function
) {
15734 result
= this.validate( this.getValue() );
15736 if ( $.isFunction( result
.promise
) ) {
15737 promise
= $.Deferred();
15739 result
.then( function ( valid
) {
15749 return promise
.promise();
15751 return rejectOrResolve( result
);
15754 return rejectOrResolve( this.getValue().match( this.validate
) );
15759 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
15761 * @param {string} labelPosition Label position, 'before' or 'after'
15764 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
15765 this.labelPosition
= labelPosition
;
15766 this.updatePosition();
15771 * Deprecated alias of #setLabelPosition
15773 * @deprecated Use setLabelPosition instead.
15775 OO
.ui
.TextInputWidget
.prototype.setPosition
=
15776 OO
.ui
.TextInputWidget
.prototype.setLabelPosition
;
15779 * Update the position of the inline label.
15781 * This method is called by #setLabelPosition, and can also be called on its own if
15782 * something causes the label to be mispositioned.
15786 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
15787 var after
= this.labelPosition
=== 'after';
15790 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
15791 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
15793 this.positionLabel();
15799 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
15800 * already empty or when it's not editable.
15802 OO
.ui
.TextInputWidget
.prototype.updateSearchIndicator = function () {
15803 if ( this.type
=== 'search' ) {
15804 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
15805 this.setIndicator( null );
15807 this.setIndicator( 'clear' );
15813 * Position the label by setting the correct padding on the input.
15818 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
15819 var after
, rtl
, property
;
15820 // Clear old values
15822 // Clear old values if present
15824 'padding-right': '',
15828 if ( this.label
) {
15829 this.$element
.append( this.$label
);
15831 this.$label
.detach();
15835 after
= this.labelPosition
=== 'after';
15836 rtl
= this.$element
.css( 'direction' ) === 'rtl';
15837 property
= after
=== rtl
? 'padding-left' : 'padding-right';
15839 this.$input
.css( property
, this.$label
.outerWidth( true ) );
15847 OO
.ui
.TextInputWidget
.prototype.gatherPreInfuseState = function ( node
) {
15849 state
= OO
.ui
.TextInputWidget
.parent
.prototype.gatherPreInfuseState
.call( this, node
),
15850 $input
= $( node
).find( '.oo-ui-inputWidget-input' );
15851 state
.$input
= $input
; // shortcut for performance, used in InputWidget
15852 if ( this.multiline
) {
15853 state
.scrollTop
= $input
.scrollTop();
15861 OO
.ui
.TextInputWidget
.prototype.restorePreInfuseState = function ( state
) {
15862 OO
.ui
.TextInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
15863 if ( state
.scrollTop
!== undefined ) {
15864 this.$input
.scrollTop( state
.scrollTop
);
15869 * ComboBoxWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
15870 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
15871 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
15873 * - by typing a value in the text input field. If the value exactly matches the value of a menu
15874 * option, that option will appear to be selected.
15875 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
15878 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
15881 * // Example: A ComboBoxWidget.
15882 * var comboBox = new OO.ui.ComboBoxWidget( {
15883 * label: 'ComboBoxWidget',
15884 * input: { value: 'Option One' },
15887 * new OO.ui.MenuOptionWidget( {
15888 * data: 'Option 1',
15889 * label: 'Option One'
15891 * new OO.ui.MenuOptionWidget( {
15892 * data: 'Option 2',
15893 * label: 'Option Two'
15895 * new OO.ui.MenuOptionWidget( {
15896 * data: 'Option 3',
15897 * label: 'Option Three'
15899 * new OO.ui.MenuOptionWidget( {
15900 * data: 'Option 4',
15901 * label: 'Option Four'
15903 * new OO.ui.MenuOptionWidget( {
15904 * data: 'Option 5',
15905 * label: 'Option Five'
15910 * $( 'body' ).append( comboBox.$element );
15912 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
15915 * @extends OO.ui.Widget
15916 * @mixins OO.ui.mixin.TabIndexedElement
15919 * @param {Object} [config] Configuration options
15920 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
15921 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
15922 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
15923 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
15924 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
15926 OO
.ui
.ComboBoxWidget
= function OoUiComboBoxWidget( config
) {
15927 // Configuration initialization
15928 config
= config
|| {};
15930 // Parent constructor
15931 OO
.ui
.ComboBoxWidget
.parent
.call( this, config
);
15933 // Properties (must be set before TabIndexedElement constructor call)
15934 this.$indicator
= this.$( '<span>' );
15936 // Mixin constructors
15937 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$indicator
} ) );
15940 this.$overlay
= config
.$overlay
|| this.$element
;
15941 this.input
= new OO
.ui
.TextInputWidget( $.extend(
15944 $indicator
: this.$indicator
,
15945 disabled
: this.isDisabled()
15949 this.input
.$input
.eq( 0 ).attr( {
15951 'aria-autocomplete': 'list'
15953 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend(
15957 $container
: this.input
.$element
,
15958 disabled
: this.isDisabled()
15964 this.$indicator
.on( {
15965 click
: this.onClick
.bind( this ),
15966 keypress
: this.onKeyPress
.bind( this )
15968 this.input
.connect( this, {
15969 change
: 'onInputChange',
15970 enter
: 'onInputEnter'
15972 this.menu
.connect( this, {
15973 choose
: 'onMenuChoose',
15974 add
: 'onMenuItemsChange',
15975 remove
: 'onMenuItemsChange'
15979 this.$element
.addClass( 'oo-ui-comboBoxWidget' ).append( this.input
.$element
);
15980 this.$overlay
.append( this.menu
.$element
);
15981 this.onMenuItemsChange();
15986 OO
.inheritClass( OO
.ui
.ComboBoxWidget
, OO
.ui
.Widget
);
15987 OO
.mixinClass( OO
.ui
.ComboBoxWidget
, OO
.ui
.mixin
.TabIndexedElement
);
15992 * Get the combobox's menu.
15993 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
15995 OO
.ui
.ComboBoxWidget
.prototype.getMenu = function () {
16000 * Get the combobox's text input widget.
16001 * @return {OO.ui.TextInputWidget} Text input widget
16003 OO
.ui
.ComboBoxWidget
.prototype.getInput = function () {
16008 * Handle input change events.
16011 * @param {string} value New value
16013 OO
.ui
.ComboBoxWidget
.prototype.onInputChange = function ( value
) {
16014 var match
= this.menu
.getItemFromData( value
);
16016 this.menu
.selectItem( match
);
16017 if ( this.menu
.getHighlightedItem() ) {
16018 this.menu
.highlightItem( match
);
16021 if ( !this.isDisabled() ) {
16022 this.menu
.toggle( true );
16027 * Handle mouse click events.
16031 * @param {jQuery.Event} e Mouse click event
16033 OO
.ui
.ComboBoxWidget
.prototype.onClick = function ( e
) {
16034 if ( !this.isDisabled() && e
.which
=== 1 ) {
16035 this.menu
.toggle();
16036 this.input
.$input
[ 0 ].focus();
16042 * Handle key press events.
16046 * @param {jQuery.Event} e Key press event
16048 OO
.ui
.ComboBoxWidget
.prototype.onKeyPress = function ( e
) {
16049 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
16050 this.menu
.toggle();
16051 this.input
.$input
[ 0 ].focus();
16057 * Handle input enter events.
16061 OO
.ui
.ComboBoxWidget
.prototype.onInputEnter = function () {
16062 if ( !this.isDisabled() ) {
16063 this.menu
.toggle( false );
16068 * Handle menu choose events.
16071 * @param {OO.ui.OptionWidget} item Chosen item
16073 OO
.ui
.ComboBoxWidget
.prototype.onMenuChoose = function ( item
) {
16074 this.input
.setValue( item
.getData() );
16078 * Handle menu item change events.
16082 OO
.ui
.ComboBoxWidget
.prototype.onMenuItemsChange = function () {
16083 var match
= this.menu
.getItemFromData( this.input
.getValue() );
16084 this.menu
.selectItem( match
);
16085 if ( this.menu
.getHighlightedItem() ) {
16086 this.menu
.highlightItem( match
);
16088 this.$element
.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu
.isEmpty() );
16094 OO
.ui
.ComboBoxWidget
.prototype.setDisabled = function ( disabled
) {
16096 OO
.ui
.ComboBoxWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
16098 if ( this.input
) {
16099 this.input
.setDisabled( this.isDisabled() );
16102 this.menu
.setDisabled( this.isDisabled() );
16109 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
16110 * be configured with a `label` option that is set to a string, a label node, or a function:
16112 * - String: a plaintext string
16113 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
16114 * label that includes a link or special styling, such as a gray color or additional graphical elements.
16115 * - Function: a function that will produce a string in the future. Functions are used
16116 * in cases where the value of the label is not currently defined.
16118 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
16119 * will come into focus when the label is clicked.
16122 * // Examples of LabelWidgets
16123 * var label1 = new OO.ui.LabelWidget( {
16124 * label: 'plaintext label'
16126 * var label2 = new OO.ui.LabelWidget( {
16127 * label: $( '<a href="default.html">jQuery label</a>' )
16129 * // Create a fieldset layout with fields for each example
16130 * var fieldset = new OO.ui.FieldsetLayout();
16131 * fieldset.addItems( [
16132 * new OO.ui.FieldLayout( label1 ),
16133 * new OO.ui.FieldLayout( label2 )
16135 * $( 'body' ).append( fieldset.$element );
16139 * @extends OO.ui.Widget
16140 * @mixins OO.ui.mixin.LabelElement
16143 * @param {Object} [config] Configuration options
16144 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
16145 * Clicking the label will focus the specified input field.
16147 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
16148 // Configuration initialization
16149 config
= config
|| {};
16151 // Parent constructor
16152 OO
.ui
.LabelWidget
.parent
.call( this, config
);
16154 // Mixin constructors
16155 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
16156 OO
.ui
.mixin
.TitledElement
.call( this, config
);
16159 this.input
= config
.input
;
16162 if ( this.input
instanceof OO
.ui
.InputWidget
) {
16163 this.$element
.on( 'click', this.onClick
.bind( this ) );
16167 this.$element
.addClass( 'oo-ui-labelWidget' );
16172 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
16173 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.LabelElement
);
16174 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.TitledElement
);
16176 /* Static Properties */
16178 OO
.ui
.LabelWidget
.static.tagName
= 'span';
16183 * Handles label mouse click events.
16186 * @param {jQuery.Event} e Mouse click event
16188 OO
.ui
.LabelWidget
.prototype.onClick = function () {
16189 this.input
.simulateLabelClick();
16194 * OptionWidgets are special elements that can be selected and configured with data. The
16195 * data is often unique for each option, but it does not have to be. OptionWidgets are used
16196 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
16197 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
16199 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16202 * @extends OO.ui.Widget
16203 * @mixins OO.ui.mixin.LabelElement
16204 * @mixins OO.ui.mixin.FlaggedElement
16207 * @param {Object} [config] Configuration options
16209 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
16210 // Configuration initialization
16211 config
= config
|| {};
16213 // Parent constructor
16214 OO
.ui
.OptionWidget
.parent
.call( this, config
);
16216 // Mixin constructors
16217 OO
.ui
.mixin
.ItemWidget
.call( this );
16218 OO
.ui
.mixin
.LabelElement
.call( this, config
);
16219 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
16222 this.selected
= false;
16223 this.highlighted
= false;
16224 this.pressed
= false;
16228 .data( 'oo-ui-optionWidget', this )
16229 .attr( 'role', 'option' )
16230 .attr( 'aria-selected', 'false' )
16231 .addClass( 'oo-ui-optionWidget' )
16232 .append( this.$label
);
16237 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
16238 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.ItemWidget
);
16239 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.LabelElement
);
16240 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.FlaggedElement
);
16242 /* Static Properties */
16244 OO
.ui
.OptionWidget
.static.selectable
= true;
16246 OO
.ui
.OptionWidget
.static.highlightable
= true;
16248 OO
.ui
.OptionWidget
.static.pressable
= true;
16250 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
16255 * Check if the option can be selected.
16257 * @return {boolean} Item is selectable
16259 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
16260 return this.constructor.static.selectable
&& !this.isDisabled() && this.isVisible();
16264 * Check if the option can be highlighted. A highlight indicates that the option
16265 * may be selected when a user presses enter or clicks. Disabled items cannot
16268 * @return {boolean} Item is highlightable
16270 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
16271 return this.constructor.static.highlightable
&& !this.isDisabled() && this.isVisible();
16275 * Check if the option can be pressed. The pressed state occurs when a user mouses
16276 * down on an item, but has not yet let go of the mouse.
16278 * @return {boolean} Item is pressable
16280 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
16281 return this.constructor.static.pressable
&& !this.isDisabled() && this.isVisible();
16285 * Check if the option is selected.
16287 * @return {boolean} Item is selected
16289 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
16290 return this.selected
;
16294 * Check if the option is highlighted. A highlight indicates that the
16295 * item may be selected when a user presses enter or clicks.
16297 * @return {boolean} Item is highlighted
16299 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
16300 return this.highlighted
;
16304 * Check if the option is pressed. The pressed state occurs when a user mouses
16305 * down on an item, but has not yet let go of the mouse. The item may appear
16306 * selected, but it will not be selected until the user releases the mouse.
16308 * @return {boolean} Item is pressed
16310 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
16311 return this.pressed
;
16315 * Set the option’s selected state. In general, all modifications to the selection
16316 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
16317 * method instead of this method.
16319 * @param {boolean} [state=false] Select option
16322 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
16323 if ( this.constructor.static.selectable
) {
16324 this.selected
= !!state
;
16326 .toggleClass( 'oo-ui-optionWidget-selected', state
)
16327 .attr( 'aria-selected', state
.toString() );
16328 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
16329 this.scrollElementIntoView();
16331 this.updateThemeClasses();
16337 * Set the option’s highlighted state. In general, all programmatic
16338 * modifications to the highlight should be handled by the
16339 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
16340 * method instead of this method.
16342 * @param {boolean} [state=false] Highlight option
16345 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
16346 if ( this.constructor.static.highlightable
) {
16347 this.highlighted
= !!state
;
16348 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
16349 this.updateThemeClasses();
16355 * Set the option’s pressed state. In general, all
16356 * programmatic modifications to the pressed state should be handled by the
16357 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
16358 * method instead of this method.
16360 * @param {boolean} [state=false] Press option
16363 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
16364 if ( this.constructor.static.pressable
) {
16365 this.pressed
= !!state
;
16366 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
16367 this.updateThemeClasses();
16373 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
16374 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
16375 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
16376 * options. For more information about options and selects, please see the
16377 * [OOjs UI documentation on MediaWiki][1].
16380 * // Decorated options in a select widget
16381 * var select = new OO.ui.SelectWidget( {
16383 * new OO.ui.DecoratedOptionWidget( {
16385 * label: 'Option with icon',
16388 * new OO.ui.DecoratedOptionWidget( {
16390 * label: 'Option with indicator',
16391 * indicator: 'next'
16395 * $( 'body' ).append( select.$element );
16397 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16400 * @extends OO.ui.OptionWidget
16401 * @mixins OO.ui.mixin.IconElement
16402 * @mixins OO.ui.mixin.IndicatorElement
16405 * @param {Object} [config] Configuration options
16407 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
16408 // Parent constructor
16409 OO
.ui
.DecoratedOptionWidget
.parent
.call( this, config
);
16411 // Mixin constructors
16412 OO
.ui
.mixin
.IconElement
.call( this, config
);
16413 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
16417 .addClass( 'oo-ui-decoratedOptionWidget' )
16418 .prepend( this.$icon
)
16419 .append( this.$indicator
);
16424 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
16425 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IconElement
);
16426 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IndicatorElement
);
16429 * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that
16430 * can be selected and configured with data. The class is
16431 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
16432 * [OOjs UI documentation on MediaWiki] [1] for more information.
16434 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
16437 * @extends OO.ui.DecoratedOptionWidget
16438 * @mixins OO.ui.mixin.ButtonElement
16439 * @mixins OO.ui.mixin.TabIndexedElement
16440 * @mixins OO.ui.mixin.TitledElement
16443 * @param {Object} [config] Configuration options
16445 OO
.ui
.ButtonOptionWidget
= function OoUiButtonOptionWidget( config
) {
16446 // Configuration initialization
16447 config
= config
|| {};
16449 // Parent constructor
16450 OO
.ui
.ButtonOptionWidget
.parent
.call( this, config
);
16452 // Mixin constructors
16453 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
16454 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
16455 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, {
16456 $tabIndexed
: this.$button
,
16461 this.$element
.addClass( 'oo-ui-buttonOptionWidget' );
16462 this.$button
.append( this.$element
.contents() );
16463 this.$element
.append( this.$button
);
16468 OO
.inheritClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
16469 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.ButtonElement
);
16470 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.TitledElement
);
16471 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.TabIndexedElement
);
16473 /* Static Properties */
16475 // Allow button mouse down events to pass through so they can be handled by the parent select widget
16476 OO
.ui
.ButtonOptionWidget
.static.cancelButtonMouseDownEvents
= false;
16478 OO
.ui
.ButtonOptionWidget
.static.highlightable
= false;
16485 OO
.ui
.ButtonOptionWidget
.prototype.setSelected = function ( state
) {
16486 OO
.ui
.ButtonOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
16488 if ( this.constructor.static.selectable
) {
16489 this.setActive( state
);
16496 * RadioOptionWidget is an option widget that looks like a radio button.
16497 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
16498 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
16500 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
16503 * @extends OO.ui.OptionWidget
16506 * @param {Object} [config] Configuration options
16508 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
16509 // Configuration initialization
16510 config
= config
|| {};
16512 // Properties (must be done before parent constructor which calls #setDisabled)
16513 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
16515 // Parent constructor
16516 OO
.ui
.RadioOptionWidget
.parent
.call( this, config
);
16519 this.radio
.$input
.on( 'focus', this.onInputFocus
.bind( this ) );
16522 // Remove implicit role, we're handling it ourselves
16523 this.radio
.$input
.attr( 'role', 'presentation' );
16525 .addClass( 'oo-ui-radioOptionWidget' )
16526 .attr( 'role', 'radio' )
16527 .attr( 'aria-checked', 'false' )
16528 .removeAttr( 'aria-selected' )
16529 .prepend( this.radio
.$element
);
16534 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
16536 /* Static Properties */
16538 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
16540 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
16542 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
16544 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
16549 * @param {jQuery.Event} e Focus event
16552 OO
.ui
.RadioOptionWidget
.prototype.onInputFocus = function () {
16553 this.radio
.$input
.blur();
16554 this.$element
.parent().focus();
16560 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
16561 OO
.ui
.RadioOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
16563 this.radio
.setSelected( state
);
16565 .attr( 'aria-checked', state
.toString() )
16566 .removeAttr( 'aria-selected' );
16574 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
16575 OO
.ui
.RadioOptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
16577 this.radio
.setDisabled( this.isDisabled() );
16583 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
16584 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
16585 * the [OOjs UI documentation on MediaWiki] [1] for more information.
16587 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
16590 * @extends OO.ui.DecoratedOptionWidget
16593 * @param {Object} [config] Configuration options
16595 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
16596 // Configuration initialization
16597 config
= $.extend( { icon
: 'check' }, config
);
16599 // Parent constructor
16600 OO
.ui
.MenuOptionWidget
.parent
.call( this, config
);
16604 .attr( 'role', 'menuitem' )
16605 .addClass( 'oo-ui-menuOptionWidget' );
16610 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
16612 /* Static Properties */
16614 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
16617 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
16618 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
16621 * var myDropdown = new OO.ui.DropdownWidget( {
16624 * new OO.ui.MenuSectionOptionWidget( {
16627 * new OO.ui.MenuOptionWidget( {
16629 * label: 'Welsh Corgi'
16631 * new OO.ui.MenuOptionWidget( {
16633 * label: 'Standard Poodle'
16635 * new OO.ui.MenuSectionOptionWidget( {
16638 * new OO.ui.MenuOptionWidget( {
16645 * $( 'body' ).append( myDropdown.$element );
16649 * @extends OO.ui.DecoratedOptionWidget
16652 * @param {Object} [config] Configuration options
16654 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
16655 // Parent constructor
16656 OO
.ui
.MenuSectionOptionWidget
.parent
.call( this, config
);
16659 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' );
16664 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
16666 /* Static Properties */
16668 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
16670 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
16673 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
16675 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
16676 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
16680 * @extends OO.ui.DecoratedOptionWidget
16683 * @param {Object} [config] Configuration options
16684 * @cfg {number} [level] Indentation level
16685 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
16687 OO
.ui
.OutlineOptionWidget
= function OoUiOutlineOptionWidget( config
) {
16688 // Configuration initialization
16689 config
= config
|| {};
16691 // Parent constructor
16692 OO
.ui
.OutlineOptionWidget
.parent
.call( this, config
);
16696 this.movable
= !!config
.movable
;
16697 this.removable
= !!config
.removable
;
16700 this.$element
.addClass( 'oo-ui-outlineOptionWidget' );
16701 this.setLevel( config
.level
);
16706 OO
.inheritClass( OO
.ui
.OutlineOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
16708 /* Static Properties */
16710 OO
.ui
.OutlineOptionWidget
.static.highlightable
= false;
16712 OO
.ui
.OutlineOptionWidget
.static.scrollIntoViewOnSelect
= true;
16714 OO
.ui
.OutlineOptionWidget
.static.levelClass
= 'oo-ui-outlineOptionWidget-level-';
16716 OO
.ui
.OutlineOptionWidget
.static.levels
= 3;
16721 * Check if item is movable.
16723 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16725 * @return {boolean} Item is movable
16727 OO
.ui
.OutlineOptionWidget
.prototype.isMovable = function () {
16728 return this.movable
;
16732 * Check if item is removable.
16734 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16736 * @return {boolean} Item is removable
16738 OO
.ui
.OutlineOptionWidget
.prototype.isRemovable = function () {
16739 return this.removable
;
16743 * Get indentation level.
16745 * @return {number} Indentation level
16747 OO
.ui
.OutlineOptionWidget
.prototype.getLevel = function () {
16754 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16756 * @param {boolean} movable Item is movable
16759 OO
.ui
.OutlineOptionWidget
.prototype.setMovable = function ( movable
) {
16760 this.movable
= !!movable
;
16761 this.updateThemeClasses();
16766 * Set removability.
16768 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16770 * @param {boolean} movable Item is removable
16773 OO
.ui
.OutlineOptionWidget
.prototype.setRemovable = function ( removable
) {
16774 this.removable
= !!removable
;
16775 this.updateThemeClasses();
16780 * Set indentation level.
16782 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
16785 OO
.ui
.OutlineOptionWidget
.prototype.setLevel = function ( level
) {
16786 var levels
= this.constructor.static.levels
,
16787 levelClass
= this.constructor.static.levelClass
,
16790 this.level
= level
? Math
.max( 0, Math
.min( levels
- 1, level
) ) : 0;
16792 if ( this.level
=== i
) {
16793 this.$element
.addClass( levelClass
+ i
);
16795 this.$element
.removeClass( levelClass
+ i
);
16798 this.updateThemeClasses();
16804 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
16806 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
16807 * {@link OO.ui.CardLayout card layouts}. See {@link OO.ui.IndexLayout IndexLayout}
16811 * @extends OO.ui.OptionWidget
16814 * @param {Object} [config] Configuration options
16816 OO
.ui
.TabOptionWidget
= function OoUiTabOptionWidget( config
) {
16817 // Configuration initialization
16818 config
= config
|| {};
16820 // Parent constructor
16821 OO
.ui
.TabOptionWidget
.parent
.call( this, config
);
16824 this.$element
.addClass( 'oo-ui-tabOptionWidget' );
16829 OO
.inheritClass( OO
.ui
.TabOptionWidget
, OO
.ui
.OptionWidget
);
16831 /* Static Properties */
16833 OO
.ui
.TabOptionWidget
.static.highlightable
= false;
16836 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
16837 * By default, each popup has an anchor that points toward its origin.
16838 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
16841 * // A popup widget.
16842 * var popup = new OO.ui.PopupWidget( {
16843 * $content: $( '<p>Hi there!</p>' ),
16848 * $( 'body' ).append( popup.$element );
16849 * // To display the popup, toggle the visibility to 'true'.
16850 * popup.toggle( true );
16852 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
16855 * @extends OO.ui.Widget
16856 * @mixins OO.ui.mixin.LabelElement
16859 * @param {Object} [config] Configuration options
16860 * @cfg {number} [width=320] Width of popup in pixels
16861 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
16862 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
16863 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
16864 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
16865 * popup is leaning towards the right of the screen.
16866 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
16867 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
16868 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
16869 * sentence in the given language.
16870 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
16871 * See the [OOjs UI docs on MediaWiki][3] for an example.
16872 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
16873 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
16874 * @cfg {jQuery} [$content] Content to append to the popup's body
16875 * @cfg {jQuery} [$footer] Content to append to the popup's footer
16876 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
16877 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
16878 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
16880 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
16881 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
16883 * @cfg {boolean} [padded] Add padding to the popup's body
16885 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
16886 // Configuration initialization
16887 config
= config
|| {};
16889 // Parent constructor
16890 OO
.ui
.PopupWidget
.parent
.call( this, config
);
16892 // Properties (must be set before ClippableElement constructor call)
16893 this.$body
= $( '<div>' );
16894 this.$popup
= $( '<div>' );
16896 // Mixin constructors
16897 OO
.ui
.mixin
.LabelElement
.call( this, config
);
16898 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, {
16899 $clippable
: this.$body
,
16900 $clippableContainer
: this.$popup
16904 this.$head
= $( '<div>' );
16905 this.$footer
= $( '<div>' );
16906 this.$anchor
= $( '<div>' );
16907 // If undefined, will be computed lazily in updateDimensions()
16908 this.$container
= config
.$container
;
16909 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
16910 this.autoClose
= !!config
.autoClose
;
16911 this.$autoCloseIgnore
= config
.$autoCloseIgnore
;
16912 this.transitionTimeout
= null;
16913 this.anchor
= null;
16914 this.width
= config
.width
!== undefined ? config
.width
: 320;
16915 this.height
= config
.height
!== undefined ? config
.height
: null;
16916 this.setAlignment( config
.align
);
16917 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
16918 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
16919 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
16922 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
16925 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
16926 this.$body
.addClass( 'oo-ui-popupWidget-body' );
16927 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
16929 .addClass( 'oo-ui-popupWidget-head' )
16930 .append( this.$label
, this.closeButton
.$element
);
16931 this.$footer
.addClass( 'oo-ui-popupWidget-footer' );
16932 if ( !config
.head
) {
16933 this.$head
.addClass( 'oo-ui-element-hidden' );
16935 if ( !config
.$footer
) {
16936 this.$footer
.addClass( 'oo-ui-element-hidden' );
16939 .addClass( 'oo-ui-popupWidget-popup' )
16940 .append( this.$head
, this.$body
, this.$footer
);
16942 .addClass( 'oo-ui-popupWidget' )
16943 .append( this.$popup
, this.$anchor
);
16944 // Move content, which was added to #$element by OO.ui.Widget, to the body
16945 if ( config
.$content
instanceof jQuery
) {
16946 this.$body
.append( config
.$content
);
16948 if ( config
.$footer
instanceof jQuery
) {
16949 this.$footer
.append( config
.$footer
);
16951 if ( config
.padded
) {
16952 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
16955 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
16956 // that reference properties not initialized at that time of parent class construction
16957 // TODO: Find a better way to handle post-constructor setup
16958 this.visible
= false;
16959 this.$element
.addClass( 'oo-ui-element-hidden' );
16964 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
16965 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.LabelElement
);
16966 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.ClippableElement
);
16971 * Handles mouse down events.
16974 * @param {MouseEvent} e Mouse down event
16976 OO
.ui
.PopupWidget
.prototype.onMouseDown = function ( e
) {
16978 this.isVisible() &&
16979 !$.contains( this.$element
[ 0 ], e
.target
) &&
16980 ( !this.$autoCloseIgnore
|| !this.$autoCloseIgnore
.has( e
.target
).length
)
16982 this.toggle( false );
16987 * Bind mouse down listener.
16991 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
16992 // Capture clicks outside popup
16993 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler
);
16997 * Handles close button click events.
17001 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
17002 if ( this.isVisible() ) {
17003 this.toggle( false );
17008 * Unbind mouse down listener.
17012 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
17013 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler
);
17017 * Handles key down events.
17020 * @param {KeyboardEvent} e Key down event
17022 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
17024 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
17027 this.toggle( false );
17028 e
.preventDefault();
17029 e
.stopPropagation();
17034 * Bind key down listener.
17038 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
17039 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler
);
17043 * Unbind key down listener.
17047 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
17048 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler
);
17052 * Show, hide, or toggle the visibility of the anchor.
17054 * @param {boolean} [show] Show anchor, omit to toggle
17056 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
17057 show
= show
=== undefined ? !this.anchored
: !!show
;
17059 if ( this.anchored
!== show
) {
17061 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
17063 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
17065 this.anchored
= show
;
17070 * Check if the anchor is visible.
17072 * @return {boolean} Anchor is visible
17074 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
17075 return this.anchor
;
17081 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
17083 show
= show
=== undefined ? !this.isVisible() : !!show
;
17085 change
= show
!== this.isVisible();
17088 OO
.ui
.PopupWidget
.parent
.prototype.toggle
.call( this, show
);
17092 if ( this.autoClose
) {
17093 this.bindMouseDownListener();
17094 this.bindKeyDownListener();
17096 this.updateDimensions();
17097 this.toggleClipping( true );
17099 this.toggleClipping( false );
17100 if ( this.autoClose
) {
17101 this.unbindMouseDownListener();
17102 this.unbindKeyDownListener();
17111 * Set the size of the popup.
17113 * Changing the size may also change the popup's position depending on the alignment.
17115 * @param {number} width Width in pixels
17116 * @param {number} height Height in pixels
17117 * @param {boolean} [transition=false] Use a smooth transition
17120 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
17121 this.width
= width
;
17122 this.height
= height
!== undefined ? height
: null;
17123 if ( this.isVisible() ) {
17124 this.updateDimensions( transition
);
17129 * Update the size and position.
17131 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
17132 * be called automatically.
17134 * @param {boolean} [transition=false] Use a smooth transition
17137 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
17138 var popupOffset
, originOffset
, containerLeft
, containerWidth
, containerRight
,
17139 popupLeft
, popupRight
, overlapLeft
, overlapRight
, anchorWidth
,
17140 align
= this.align
,
17143 if ( !this.$container
) {
17144 // Lazy-initialize $container if not specified in constructor
17145 this.$container
= $( this.getClosestScrollableElementContainer() );
17148 // Set height and width before measuring things, since it might cause our measurements
17149 // to change (e.g. due to scrollbars appearing or disappearing)
17152 height
: this.height
!== null ? this.height
: 'auto'
17155 // If we are in RTL, we need to flip the alignment, unless it is center
17156 if ( align
=== 'forwards' || align
=== 'backwards' ) {
17157 if ( this.$container
.css( 'direction' ) === 'rtl' ) {
17158 align
= ( { forwards
: 'force-left', backwards
: 'force-right' } )[ this.align
];
17160 align
= ( { forwards
: 'force-right', backwards
: 'force-left' } )[ this.align
];
17165 // Compute initial popupOffset based on alignment
17166 popupOffset
= this.width
* ( { 'force-left': -1, center
: -0.5, 'force-right': 0 } )[ align
];
17168 // Figure out if this will cause the popup to go beyond the edge of the container
17169 originOffset
= this.$element
.offset().left
;
17170 containerLeft
= this.$container
.offset().left
;
17171 containerWidth
= this.$container
.innerWidth();
17172 containerRight
= containerLeft
+ containerWidth
;
17173 popupLeft
= popupOffset
- this.containerPadding
;
17174 popupRight
= popupOffset
+ this.containerPadding
+ this.width
+ this.containerPadding
;
17175 overlapLeft
= ( originOffset
+ popupLeft
) - containerLeft
;
17176 overlapRight
= containerRight
- ( originOffset
+ popupRight
);
17178 // Adjust offset to make the popup not go beyond the edge, if needed
17179 if ( overlapRight
< 0 ) {
17180 popupOffset
+= overlapRight
;
17181 } else if ( overlapLeft
< 0 ) {
17182 popupOffset
-= overlapLeft
;
17185 // Adjust offset to avoid anchor being rendered too close to the edge
17186 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
17187 // TODO: Find a measurement that works for CSS anchors and image anchors
17188 anchorWidth
= this.$anchor
[ 0 ].scrollWidth
* 2;
17189 if ( popupOffset
+ this.width
< anchorWidth
) {
17190 popupOffset
= anchorWidth
- this.width
;
17191 } else if ( -popupOffset
< anchorWidth
) {
17192 popupOffset
= -anchorWidth
;
17195 // Prevent transition from being interrupted
17196 clearTimeout( this.transitionTimeout
);
17197 if ( transition
) {
17198 // Enable transition
17199 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
17202 // Position body relative to anchor
17203 this.$popup
.css( 'margin-left', popupOffset
);
17205 if ( transition
) {
17206 // Prevent transitioning after transition is complete
17207 this.transitionTimeout
= setTimeout( function () {
17208 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
17211 // Prevent transitioning immediately
17212 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
17215 // Reevaluate clipping state since we've relocated and resized the popup
17222 * Set popup alignment
17223 * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17224 * `backwards` or `forwards`.
17226 OO
.ui
.PopupWidget
.prototype.setAlignment = function ( align
) {
17227 // Validate alignment and transform deprecated values
17228 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align
) > -1 ) {
17229 this.align
= { left
: 'force-right', right
: 'force-left' }[ align
] || align
;
17231 this.align
= 'center';
17236 * Get popup alignment
17237 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17238 * `backwards` or `forwards`.
17240 OO
.ui
.PopupWidget
.prototype.getAlignment = function () {
17245 * Progress bars visually display the status of an operation, such as a download,
17246 * and can be either determinate or indeterminate:
17248 * - **determinate** process bars show the percent of an operation that is complete.
17250 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
17251 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
17252 * not use percentages.
17254 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
17257 * // Examples of determinate and indeterminate progress bars.
17258 * var progressBar1 = new OO.ui.ProgressBarWidget( {
17261 * var progressBar2 = new OO.ui.ProgressBarWidget();
17263 * // Create a FieldsetLayout to layout progress bars
17264 * var fieldset = new OO.ui.FieldsetLayout;
17265 * fieldset.addItems( [
17266 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
17267 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
17269 * $( 'body' ).append( fieldset.$element );
17272 * @extends OO.ui.Widget
17275 * @param {Object} [config] Configuration options
17276 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
17277 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
17278 * By default, the progress bar is indeterminate.
17280 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
17281 // Configuration initialization
17282 config
= config
|| {};
17284 // Parent constructor
17285 OO
.ui
.ProgressBarWidget
.parent
.call( this, config
);
17288 this.$bar
= $( '<div>' );
17289 this.progress
= null;
17292 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
17293 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
17296 role
: 'progressbar',
17297 'aria-valuemin': 0,
17298 'aria-valuemax': 100
17300 .addClass( 'oo-ui-progressBarWidget' )
17301 .append( this.$bar
);
17306 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
17308 /* Static Properties */
17310 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
17315 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
17317 * @return {number|boolean} Progress percent
17319 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
17320 return this.progress
;
17324 * Set the percent of the process completed or `false` for an indeterminate process.
17326 * @param {number|boolean} progress Progress percent or `false` for indeterminate
17328 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
17329 this.progress
= progress
;
17331 if ( progress
!== false ) {
17332 this.$bar
.css( 'width', this.progress
+ '%' );
17333 this.$element
.attr( 'aria-valuenow', this.progress
);
17335 this.$bar
.css( 'width', '' );
17336 this.$element
.removeAttr( 'aria-valuenow' );
17338 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress
);
17342 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
17343 * and a menu of search results, which is displayed beneath the query
17344 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
17345 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
17346 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
17348 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
17349 * the [OOjs UI demos][1] for an example.
17351 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
17354 * @extends OO.ui.Widget
17357 * @param {Object} [config] Configuration options
17358 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
17359 * @cfg {string} [value] Initial query value
17361 OO
.ui
.SearchWidget
= function OoUiSearchWidget( config
) {
17362 // Configuration initialization
17363 config
= config
|| {};
17365 // Parent constructor
17366 OO
.ui
.SearchWidget
.parent
.call( this, config
);
17369 this.query
= new OO
.ui
.TextInputWidget( {
17371 placeholder
: config
.placeholder
,
17372 value
: config
.value
17374 this.results
= new OO
.ui
.SelectWidget();
17375 this.$query
= $( '<div>' );
17376 this.$results
= $( '<div>' );
17379 this.query
.connect( this, {
17380 change
: 'onQueryChange',
17381 enter
: 'onQueryEnter'
17383 this.query
.$input
.on( 'keydown', this.onQueryKeydown
.bind( this ) );
17387 .addClass( 'oo-ui-searchWidget-query' )
17388 .append( this.query
.$element
);
17390 .addClass( 'oo-ui-searchWidget-results' )
17391 .append( this.results
.$element
);
17393 .addClass( 'oo-ui-searchWidget' )
17394 .append( this.$results
, this.$query
);
17399 OO
.inheritClass( OO
.ui
.SearchWidget
, OO
.ui
.Widget
);
17404 * Handle query key down events.
17407 * @param {jQuery.Event} e Key down event
17409 OO
.ui
.SearchWidget
.prototype.onQueryKeydown = function ( e
) {
17410 var highlightedItem
, nextItem
,
17411 dir
= e
.which
=== OO
.ui
.Keys
.DOWN
? 1 : ( e
.which
=== OO
.ui
.Keys
.UP
? -1 : 0 );
17414 highlightedItem
= this.results
.getHighlightedItem();
17415 if ( !highlightedItem
) {
17416 highlightedItem
= this.results
.getSelectedItem();
17418 nextItem
= this.results
.getRelativeSelectableItem( highlightedItem
, dir
);
17419 this.results
.highlightItem( nextItem
);
17420 nextItem
.scrollElementIntoView();
17425 * Handle select widget select events.
17427 * Clears existing results. Subclasses should repopulate items according to new query.
17430 * @param {string} value New value
17432 OO
.ui
.SearchWidget
.prototype.onQueryChange = function () {
17434 this.results
.clearItems();
17438 * Handle select widget enter key events.
17440 * Chooses highlighted item.
17443 * @param {string} value New value
17445 OO
.ui
.SearchWidget
.prototype.onQueryEnter = function () {
17447 this.results
.chooseItem( this.results
.getHighlightedItem() );
17451 * Get the query input.
17453 * @return {OO.ui.TextInputWidget} Query input
17455 OO
.ui
.SearchWidget
.prototype.getQuery = function () {
17460 * Get the search results menu.
17462 * @return {OO.ui.SelectWidget} Menu of search results
17464 OO
.ui
.SearchWidget
.prototype.getResults = function () {
17465 return this.results
;
17469 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
17470 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
17471 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
17474 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
17475 * information, please see the [OOjs UI documentation on MediaWiki][1].
17478 * // Example of a select widget with three options
17479 * var select = new OO.ui.SelectWidget( {
17481 * new OO.ui.OptionWidget( {
17483 * label: 'Option One',
17485 * new OO.ui.OptionWidget( {
17487 * label: 'Option Two',
17489 * new OO.ui.OptionWidget( {
17491 * label: 'Option Three',
17495 * $( 'body' ).append( select.$element );
17497 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17501 * @extends OO.ui.Widget
17502 * @mixins OO.ui.mixin.GroupWidget
17505 * @param {Object} [config] Configuration options
17506 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
17507 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
17508 * the [OOjs UI documentation on MediaWiki] [2] for examples.
17509 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17511 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
17512 // Configuration initialization
17513 config
= config
|| {};
17515 // Parent constructor
17516 OO
.ui
.SelectWidget
.parent
.call( this, config
);
17518 // Mixin constructors
17519 OO
.ui
.mixin
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
17522 this.pressed
= false;
17523 this.selecting
= null;
17524 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
17525 this.onMouseMoveHandler
= this.onMouseMove
.bind( this );
17526 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
17527 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
17528 this.keyPressBuffer
= '';
17529 this.keyPressBufferTimer
= null;
17532 this.connect( this, {
17535 this.$element
.on( {
17536 mousedown
: this.onMouseDown
.bind( this ),
17537 mouseover
: this.onMouseOver
.bind( this ),
17538 mouseleave
: this.onMouseLeave
.bind( this )
17543 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
17544 .attr( 'role', 'listbox' );
17545 if ( Array
.isArray( config
.items
) ) {
17546 this.addItems( config
.items
);
17552 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
17554 // Need to mixin base class as well
17555 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupElement
);
17556 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupWidget
);
17559 OO
.ui
.SelectWidget
.static.passAllFilter = function () {
17568 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
17570 * @param {OO.ui.OptionWidget|null} item Highlighted item
17576 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
17577 * pressed state of an option.
17579 * @param {OO.ui.OptionWidget|null} item Pressed item
17585 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
17587 * @param {OO.ui.OptionWidget|null} item Selected item
17592 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
17593 * @param {OO.ui.OptionWidget} item Chosen item
17599 * An `add` event is emitted when options are added to the select with the #addItems method.
17601 * @param {OO.ui.OptionWidget[]} items Added items
17602 * @param {number} index Index of insertion point
17608 * A `remove` event is emitted when options are removed from the select with the #clearItems
17609 * or #removeItems methods.
17611 * @param {OO.ui.OptionWidget[]} items Removed items
17617 * Handle mouse down events.
17620 * @param {jQuery.Event} e Mouse down event
17622 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
17625 if ( !this.isDisabled() && e
.which
=== 1 ) {
17626 this.togglePressed( true );
17627 item
= this.getTargetItem( e
);
17628 if ( item
&& item
.isSelectable() ) {
17629 this.pressItem( item
);
17630 this.selecting
= item
;
17631 OO
.ui
.addCaptureEventListener(
17632 this.getElementDocument(),
17634 this.onMouseUpHandler
17636 OO
.ui
.addCaptureEventListener(
17637 this.getElementDocument(),
17639 this.onMouseMoveHandler
17647 * Handle mouse up events.
17650 * @param {jQuery.Event} e Mouse up event
17652 OO
.ui
.SelectWidget
.prototype.onMouseUp = function ( e
) {
17655 this.togglePressed( false );
17656 if ( !this.selecting
) {
17657 item
= this.getTargetItem( e
);
17658 if ( item
&& item
.isSelectable() ) {
17659 this.selecting
= item
;
17662 if ( !this.isDisabled() && e
.which
=== 1 && this.selecting
) {
17663 this.pressItem( null );
17664 this.chooseItem( this.selecting
);
17665 this.selecting
= null;
17668 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup',
17669 this.onMouseUpHandler
);
17670 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mousemove',
17671 this.onMouseMoveHandler
);
17677 * Handle mouse move events.
17680 * @param {jQuery.Event} e Mouse move event
17682 OO
.ui
.SelectWidget
.prototype.onMouseMove = function ( e
) {
17685 if ( !this.isDisabled() && this.pressed
) {
17686 item
= this.getTargetItem( e
);
17687 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
17688 this.pressItem( item
);
17689 this.selecting
= item
;
17696 * Handle mouse over events.
17699 * @param {jQuery.Event} e Mouse over event
17701 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
17704 if ( !this.isDisabled() ) {
17705 item
= this.getTargetItem( e
);
17706 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
17712 * Handle mouse leave events.
17715 * @param {jQuery.Event} e Mouse over event
17717 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
17718 if ( !this.isDisabled() ) {
17719 this.highlightItem( null );
17725 * Handle key down events.
17728 * @param {jQuery.Event} e Key down event
17730 OO
.ui
.SelectWidget
.prototype.onKeyDown = function ( e
) {
17733 currentItem
= this.getHighlightedItem() || this.getSelectedItem();
17735 if ( !this.isDisabled() && this.isVisible() ) {
17736 switch ( e
.keyCode
) {
17737 case OO
.ui
.Keys
.ENTER
:
17738 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
17739 // Was only highlighted, now let's select it. No-op if already selected.
17740 this.chooseItem( currentItem
);
17744 case OO
.ui
.Keys
.UP
:
17745 case OO
.ui
.Keys
.LEFT
:
17746 this.clearKeyPressBuffer();
17747 nextItem
= this.getRelativeSelectableItem( currentItem
, -1 );
17750 case OO
.ui
.Keys
.DOWN
:
17751 case OO
.ui
.Keys
.RIGHT
:
17752 this.clearKeyPressBuffer();
17753 nextItem
= this.getRelativeSelectableItem( currentItem
, 1 );
17756 case OO
.ui
.Keys
.ESCAPE
:
17757 case OO
.ui
.Keys
.TAB
:
17758 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
17759 currentItem
.setHighlighted( false );
17761 this.unbindKeyDownListener();
17762 this.unbindKeyPressListener();
17763 // Don't prevent tabbing away / defocusing
17769 if ( nextItem
.constructor.static.highlightable
) {
17770 this.highlightItem( nextItem
);
17772 this.chooseItem( nextItem
);
17774 nextItem
.scrollElementIntoView();
17778 // Can't just return false, because e is not always a jQuery event
17779 e
.preventDefault();
17780 e
.stopPropagation();
17786 * Bind key down listener.
17790 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
17791 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler
);
17795 * Unbind key down listener.
17799 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
17800 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler
);
17804 * Clear the key-press buffer
17808 OO
.ui
.SelectWidget
.prototype.clearKeyPressBuffer = function () {
17809 if ( this.keyPressBufferTimer
) {
17810 clearTimeout( this.keyPressBufferTimer
);
17811 this.keyPressBufferTimer
= null;
17813 this.keyPressBuffer
= '';
17817 * Handle key press events.
17820 * @param {jQuery.Event} e Key press event
17822 OO
.ui
.SelectWidget
.prototype.onKeyPress = function ( e
) {
17823 var c
, filter
, item
;
17825 if ( !e
.charCode
) {
17826 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.keyPressBuffer
!== '' ) {
17827 this.keyPressBuffer
= this.keyPressBuffer
.substr( 0, this.keyPressBuffer
.length
- 1 );
17832 if ( String
.fromCodePoint
) {
17833 c
= String
.fromCodePoint( e
.charCode
);
17835 c
= String
.fromCharCode( e
.charCode
);
17838 if ( this.keyPressBufferTimer
) {
17839 clearTimeout( this.keyPressBufferTimer
);
17841 this.keyPressBufferTimer
= setTimeout( this.clearKeyPressBuffer
.bind( this ), 1500 );
17843 item
= this.getHighlightedItem() || this.getSelectedItem();
17845 if ( this.keyPressBuffer
=== c
) {
17846 // Common (if weird) special case: typing "xxxx" will cycle through all
17847 // the items beginning with "x".
17849 item
= this.getRelativeSelectableItem( item
, 1 );
17852 this.keyPressBuffer
+= c
;
17855 filter
= this.getItemMatcher( this.keyPressBuffer
, false );
17856 if ( !item
|| !filter( item
) ) {
17857 item
= this.getRelativeSelectableItem( item
, 1, filter
);
17860 if ( item
.constructor.static.highlightable
) {
17861 this.highlightItem( item
);
17863 this.chooseItem( item
);
17865 item
.scrollElementIntoView();
17872 * Get a matcher for the specific string
17875 * @param {string} s String to match against items
17876 * @param {boolean} [exact=false] Only accept exact matches
17877 * @return {Function} function ( OO.ui.OptionItem ) => boolean
17879 OO
.ui
.SelectWidget
.prototype.getItemMatcher = function ( s
, exact
) {
17882 if ( s
.normalize
) {
17885 s
= exact
? s
.trim() : s
.replace( /^\s+/, '' );
17886 re
= '^\\s*' + s
.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
17890 re
= new RegExp( re
, 'i' );
17891 return function ( item
) {
17892 var l
= item
.getLabel();
17893 if ( typeof l
!== 'string' ) {
17894 l
= item
.$label
.text();
17896 if ( l
.normalize
) {
17899 return re
.test( l
);
17904 * Bind key press listener.
17908 OO
.ui
.SelectWidget
.prototype.bindKeyPressListener = function () {
17909 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler
);
17913 * Unbind key down listener.
17915 * If you override this, be sure to call this.clearKeyPressBuffer() from your
17920 OO
.ui
.SelectWidget
.prototype.unbindKeyPressListener = function () {
17921 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler
);
17922 this.clearKeyPressBuffer();
17926 * Visibility change handler
17929 * @param {boolean} visible
17931 OO
.ui
.SelectWidget
.prototype.onToggle = function ( visible
) {
17933 this.clearKeyPressBuffer();
17938 * Get the closest item to a jQuery.Event.
17941 * @param {jQuery.Event} e
17942 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
17944 OO
.ui
.SelectWidget
.prototype.getTargetItem = function ( e
) {
17945 return $( e
.target
).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
17949 * Get selected item.
17951 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
17953 OO
.ui
.SelectWidget
.prototype.getSelectedItem = function () {
17956 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
17957 if ( this.items
[ i
].isSelected() ) {
17958 return this.items
[ i
];
17965 * Get highlighted item.
17967 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
17969 OO
.ui
.SelectWidget
.prototype.getHighlightedItem = function () {
17972 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
17973 if ( this.items
[ i
].isHighlighted() ) {
17974 return this.items
[ i
];
17981 * Toggle pressed state.
17983 * Press is a state that occurs when a user mouses down on an item, but
17984 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
17985 * until the user releases the mouse.
17987 * @param {boolean} pressed An option is being pressed
17989 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
17990 if ( pressed
=== undefined ) {
17991 pressed
= !this.pressed
;
17993 if ( pressed
!== this.pressed
) {
17995 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
17996 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
17997 this.pressed
= pressed
;
18002 * Highlight an option. If the `item` param is omitted, no options will be highlighted
18003 * and any existing highlight will be removed. The highlight is mutually exclusive.
18005 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
18009 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
18010 var i
, len
, highlighted
,
18013 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18014 highlighted
= this.items
[ i
] === item
;
18015 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
18016 this.items
[ i
].setHighlighted( highlighted
);
18021 this.emit( 'highlight', item
);
18028 * Fetch an item by its label.
18030 * @param {string} label Label of the item to select.
18031 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18032 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
18034 OO
.ui
.SelectWidget
.prototype.getItemFromLabel = function ( label
, prefix
) {
18035 var i
, item
, found
,
18036 len
= this.items
.length
,
18037 filter
= this.getItemMatcher( label
, true );
18039 for ( i
= 0; i
< len
; i
++ ) {
18040 item
= this.items
[ i
];
18041 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
18048 filter
= this.getItemMatcher( label
, false );
18049 for ( i
= 0; i
< len
; i
++ ) {
18050 item
= this.items
[ i
];
18051 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
18067 * Programmatically select an option by its label. If the item does not exist,
18068 * all options will be deselected.
18070 * @param {string} [label] Label of the item to select.
18071 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18075 OO
.ui
.SelectWidget
.prototype.selectItemByLabel = function ( label
, prefix
) {
18076 var itemFromLabel
= this.getItemFromLabel( label
, !!prefix
);
18077 if ( label
=== undefined || !itemFromLabel
) {
18078 return this.selectItem();
18080 return this.selectItem( itemFromLabel
);
18084 * Programmatically select an option by its data. If the `data` parameter is omitted,
18085 * or if the item does not exist, all options will be deselected.
18087 * @param {Object|string} [data] Value of the item to select, omit to deselect all
18091 OO
.ui
.SelectWidget
.prototype.selectItemByData = function ( data
) {
18092 var itemFromData
= this.getItemFromData( data
);
18093 if ( data
=== undefined || !itemFromData
) {
18094 return this.selectItem();
18096 return this.selectItem( itemFromData
);
18100 * Programmatically select an option by its reference. If the `item` parameter is omitted,
18101 * all options will be deselected.
18103 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
18107 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
18108 var i
, len
, selected
,
18111 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18112 selected
= this.items
[ i
] === item
;
18113 if ( this.items
[ i
].isSelected() !== selected
) {
18114 this.items
[ i
].setSelected( selected
);
18119 this.emit( 'select', item
);
18128 * Press is a state that occurs when a user mouses down on an item, but has not
18129 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
18130 * releases the mouse.
18132 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
18136 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
18137 var i
, len
, pressed
,
18140 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18141 pressed
= this.items
[ i
] === item
;
18142 if ( this.items
[ i
].isPressed() !== pressed
) {
18143 this.items
[ i
].setPressed( pressed
);
18148 this.emit( 'press', item
);
18157 * Note that ‘choose’ should never be modified programmatically. A user can choose
18158 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
18159 * use the #selectItem method.
18161 * This method is identical to #selectItem, but may vary in subclasses that take additional action
18162 * when users choose an item with the keyboard or mouse.
18164 * @param {OO.ui.OptionWidget} item Item to choose
18168 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
18169 this.selectItem( item
);
18170 this.emit( 'choose', item
);
18176 * Get an option by its position relative to the specified item (or to the start of the option array,
18177 * if item is `null`). The direction in which to search through the option array is specified with a
18178 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
18179 * `null` if there are no options in the array.
18181 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
18182 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
18183 * @param {Function} filter Only consider items for which this function returns
18184 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
18185 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
18187 OO
.ui
.SelectWidget
.prototype.getRelativeSelectableItem = function ( item
, direction
, filter
) {
18188 var currentIndex
, nextIndex
, i
,
18189 increase
= direction
> 0 ? 1 : -1,
18190 len
= this.items
.length
;
18192 if ( !$.isFunction( filter
) ) {
18193 filter
= OO
.ui
.SelectWidget
.static.passAllFilter
;
18196 if ( item
instanceof OO
.ui
.OptionWidget
) {
18197 currentIndex
= this.items
.indexOf( item
);
18198 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
18200 // If no item is selected and moving forward, start at the beginning.
18201 // If moving backward, start at the end.
18202 nextIndex
= direction
> 0 ? 0 : len
- 1;
18205 for ( i
= 0; i
< len
; i
++ ) {
18206 item
= this.items
[ nextIndex
];
18207 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
18210 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
18216 * Get the next selectable item or `null` if there are no selectable items.
18217 * Disabled options and menu-section markers and breaks are not selectable.
18219 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
18221 OO
.ui
.SelectWidget
.prototype.getFirstSelectableItem = function () {
18224 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18225 item
= this.items
[ i
];
18226 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() ) {
18235 * Add an array of options to the select. Optionally, an index number can be used to
18236 * specify an insertion point.
18238 * @param {OO.ui.OptionWidget[]} items Items to add
18239 * @param {number} [index] Index to insert items after
18243 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
18245 OO
.ui
.mixin
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
18247 // Always provide an index, even if it was omitted
18248 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
18254 * Remove the specified array of options from the select. Options will be detached
18255 * from the DOM, not removed, so they can be reused later. To remove all options from
18256 * the select, you may wish to use the #clearItems method instead.
18258 * @param {OO.ui.OptionWidget[]} items Items to remove
18262 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
18265 // Deselect items being removed
18266 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
18268 if ( item
.isSelected() ) {
18269 this.selectItem( null );
18274 OO
.ui
.mixin
.GroupWidget
.prototype.removeItems
.call( this, items
);
18276 this.emit( 'remove', items
);
18282 * Clear all options from the select. Options will be detached from the DOM, not removed,
18283 * so that they can be reused later. To remove a subset of options from the select, use
18284 * the #removeItems method.
18289 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
18290 var items
= this.items
.slice();
18293 OO
.ui
.mixin
.GroupWidget
.prototype.clearItems
.call( this );
18296 this.selectItem( null );
18298 this.emit( 'remove', items
);
18304 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
18305 * button options and is used together with
18306 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
18307 * highlighting, choosing, and selecting mutually exclusive options. Please see
18308 * the [OOjs UI documentation on MediaWiki] [1] for more information.
18311 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
18312 * var option1 = new OO.ui.ButtonOptionWidget( {
18314 * label: 'Option 1',
18315 * title: 'Button option 1'
18318 * var option2 = new OO.ui.ButtonOptionWidget( {
18320 * label: 'Option 2',
18321 * title: 'Button option 2'
18324 * var option3 = new OO.ui.ButtonOptionWidget( {
18326 * label: 'Option 3',
18327 * title: 'Button option 3'
18330 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
18331 * items: [ option1, option2, option3 ]
18333 * $( 'body' ).append( buttonSelect.$element );
18335 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18338 * @extends OO.ui.SelectWidget
18339 * @mixins OO.ui.mixin.TabIndexedElement
18342 * @param {Object} [config] Configuration options
18344 OO
.ui
.ButtonSelectWidget
= function OoUiButtonSelectWidget( config
) {
18345 // Parent constructor
18346 OO
.ui
.ButtonSelectWidget
.parent
.call( this, config
);
18348 // Mixin constructors
18349 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
18352 this.$element
.on( {
18353 focus
: this.bindKeyDownListener
.bind( this ),
18354 blur
: this.unbindKeyDownListener
.bind( this )
18358 this.$element
.addClass( 'oo-ui-buttonSelectWidget' );
18363 OO
.inheritClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.SelectWidget
);
18364 OO
.mixinClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
18367 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
18368 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
18369 * an interface for adding, removing and selecting options.
18370 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18372 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
18373 * OO.ui.RadioSelectInputWidget instead.
18376 * // A RadioSelectWidget with RadioOptions.
18377 * var option1 = new OO.ui.RadioOptionWidget( {
18379 * label: 'Selected radio option'
18382 * var option2 = new OO.ui.RadioOptionWidget( {
18384 * label: 'Unselected radio option'
18387 * var radioSelect=new OO.ui.RadioSelectWidget( {
18388 * items: [ option1, option2 ]
18391 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
18392 * radioSelect.selectItem( option1 );
18394 * $( 'body' ).append( radioSelect.$element );
18396 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18400 * @extends OO.ui.SelectWidget
18401 * @mixins OO.ui.mixin.TabIndexedElement
18404 * @param {Object} [config] Configuration options
18406 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
18407 // Parent constructor
18408 OO
.ui
.RadioSelectWidget
.parent
.call( this, config
);
18410 // Mixin constructors
18411 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
18414 this.$element
.on( {
18415 focus
: this.bindKeyDownListener
.bind( this ),
18416 blur
: this.unbindKeyDownListener
.bind( this )
18421 .addClass( 'oo-ui-radioSelectWidget' )
18422 .attr( 'role', 'radiogroup' );
18427 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
18428 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
18431 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
18432 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
18433 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxWidget ComboBoxWidget},
18434 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
18435 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
18436 * and customized to be opened, closed, and displayed as needed.
18438 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
18439 * mouse outside the menu.
18441 * Menus also have support for keyboard interaction:
18443 * - Enter/Return key: choose and select a menu option
18444 * - Up-arrow key: highlight the previous menu option
18445 * - Down-arrow key: highlight the next menu option
18446 * - Esc key: hide the menu
18448 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18449 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18452 * @extends OO.ui.SelectWidget
18453 * @mixins OO.ui.mixin.ClippableElement
18456 * @param {Object} [config] Configuration options
18457 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
18458 * the text the user types. This config is used by {@link OO.ui.ComboBoxWidget ComboBoxWidget}
18459 * and {@link OO.ui.mixin.LookupElement LookupElement}
18460 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
18461 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiSelectWidget CapsuleMultiSelectWidget}
18462 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
18463 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
18464 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
18465 * that button, unless the button (or its parent widget) is passed in here.
18466 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
18467 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
18469 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
18470 // Configuration initialization
18471 config
= config
|| {};
18473 // Parent constructor
18474 OO
.ui
.MenuSelectWidget
.parent
.call( this, config
);
18476 // Mixin constructors
18477 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
18480 this.newItems
= null;
18481 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
18482 this.filterFromInput
= !!config
.filterFromInput
;
18483 this.$input
= config
.$input
? config
.$input
: config
.input
? config
.input
.$input
: null;
18484 this.$widget
= config
.widget
? config
.widget
.$element
: null;
18485 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
18486 this.onInputEditHandler
= OO
.ui
.debounce( this.updateItemVisibility
.bind( this ), 100 );
18490 .addClass( 'oo-ui-menuSelectWidget' )
18491 .attr( 'role', 'menu' );
18493 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
18494 // that reference properties not initialized at that time of parent class construction
18495 // TODO: Find a better way to handle post-constructor setup
18496 this.visible
= false;
18497 this.$element
.addClass( 'oo-ui-element-hidden' );
18502 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
18503 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.ClippableElement
);
18508 * Handles document mouse down events.
18511 * @param {jQuery.Event} e Key down event
18513 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
18515 !OO
.ui
.contains( this.$element
[ 0 ], e
.target
, true ) &&
18516 ( !this.$widget
|| !OO
.ui
.contains( this.$widget
[ 0 ], e
.target
, true ) )
18518 this.toggle( false );
18525 OO
.ui
.MenuSelectWidget
.prototype.onKeyDown = function ( e
) {
18526 var currentItem
= this.getHighlightedItem() || this.getSelectedItem();
18528 if ( !this.isDisabled() && this.isVisible() ) {
18529 switch ( e
.keyCode
) {
18530 case OO
.ui
.Keys
.LEFT
:
18531 case OO
.ui
.Keys
.RIGHT
:
18532 // Do nothing if a text field is associated, arrow keys will be handled natively
18533 if ( !this.$input
) {
18534 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
18537 case OO
.ui
.Keys
.ESCAPE
:
18538 case OO
.ui
.Keys
.TAB
:
18539 if ( currentItem
) {
18540 currentItem
.setHighlighted( false );
18542 this.toggle( false );
18543 // Don't prevent tabbing away, prevent defocusing
18544 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
18545 e
.preventDefault();
18546 e
.stopPropagation();
18550 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
18557 * Update menu item visibility after input changes.
18560 OO
.ui
.MenuSelectWidget
.prototype.updateItemVisibility = function () {
18562 len
= this.items
.length
,
18563 showAll
= !this.isVisible(),
18564 filter
= showAll
? null : this.getItemMatcher( this.$input
.val() );
18566 for ( i
= 0; i
< len
; i
++ ) {
18567 item
= this.items
[ i
];
18568 if ( item
instanceof OO
.ui
.OptionWidget
) {
18569 item
.toggle( showAll
|| filter( item
) );
18573 // Reevaluate clipping
18580 OO
.ui
.MenuSelectWidget
.prototype.bindKeyDownListener = function () {
18581 if ( this.$input
) {
18582 this.$input
.on( 'keydown', this.onKeyDownHandler
);
18584 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyDownListener
.call( this );
18591 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyDownListener = function () {
18592 if ( this.$input
) {
18593 this.$input
.off( 'keydown', this.onKeyDownHandler
);
18595 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyDownListener
.call( this );
18602 OO
.ui
.MenuSelectWidget
.prototype.bindKeyPressListener = function () {
18603 if ( this.$input
) {
18604 if ( this.filterFromInput
) {
18605 this.$input
.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
18608 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyPressListener
.call( this );
18615 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyPressListener = function () {
18616 if ( this.$input
) {
18617 if ( this.filterFromInput
) {
18618 this.$input
.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
18619 this.updateItemVisibility();
18622 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyPressListener
.call( this );
18629 * When a user chooses an item, the menu is closed.
18631 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
18632 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
18633 * @param {OO.ui.OptionWidget} item Item to choose
18636 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
18637 OO
.ui
.MenuSelectWidget
.parent
.prototype.chooseItem
.call( this, item
);
18638 this.toggle( false );
18645 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
18649 OO
.ui
.MenuSelectWidget
.parent
.prototype.addItems
.call( this, items
, index
);
18652 if ( !this.newItems
) {
18653 this.newItems
= [];
18656 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
18658 if ( this.isVisible() ) {
18659 // Defer fitting label until item has been attached
18662 this.newItems
.push( item
);
18666 // Reevaluate clipping
18675 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
18677 OO
.ui
.MenuSelectWidget
.parent
.prototype.removeItems
.call( this, items
);
18679 // Reevaluate clipping
18688 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
18690 OO
.ui
.MenuSelectWidget
.parent
.prototype.clearItems
.call( this );
18692 // Reevaluate clipping
18701 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
18702 var i
, len
, change
;
18704 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
18705 change
= visible
!== this.isVisible();
18708 OO
.ui
.MenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
18712 this.bindKeyDownListener();
18713 this.bindKeyPressListener();
18715 if ( this.newItems
&& this.newItems
.length
) {
18716 for ( i
= 0, len
= this.newItems
.length
; i
< len
; i
++ ) {
18717 this.newItems
[ i
].fitLabel();
18719 this.newItems
= null;
18721 this.toggleClipping( true );
18724 if ( this.autoHide
) {
18725 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler
);
18728 this.unbindKeyDownListener();
18729 this.unbindKeyPressListener();
18730 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler
);
18731 this.toggleClipping( false );
18739 * FloatingMenuSelectWidget is a menu that will stick under a specified
18740 * container, even when it is inserted elsewhere in the document (for example,
18741 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
18742 * menu from being clipped too aggresively.
18744 * The menu's position is automatically calculated and maintained when the menu
18745 * is toggled or the window is resized.
18747 * See OO.ui.ComboBoxWidget for an example of a widget that uses this class.
18750 * @extends OO.ui.MenuSelectWidget
18753 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
18754 * Deprecated, omit this parameter and specify `$container` instead.
18755 * @param {Object} [config] Configuration options
18756 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
18758 OO
.ui
.FloatingMenuSelectWidget
= function OoUiFloatingMenuSelectWidget( inputWidget
, config
) {
18759 // Allow 'inputWidget' parameter and config for backwards compatibility
18760 if ( OO
.isPlainObject( inputWidget
) && config
=== undefined ) {
18761 config
= inputWidget
;
18762 inputWidget
= config
.inputWidget
;
18765 // Configuration initialization
18766 config
= config
|| {};
18768 // Parent constructor
18769 OO
.ui
.FloatingMenuSelectWidget
.parent
.call( this, config
);
18772 this.inputWidget
= inputWidget
; // For backwards compatibility
18773 this.$container
= config
.$container
|| this.inputWidget
.$element
;
18774 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
18777 this.$element
.addClass( 'oo-ui-floatingMenuSelectWidget' );
18778 // For backwards compatibility
18779 this.$element
.addClass( 'oo-ui-textInputMenuSelectWidget' );
18784 OO
.inheritClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.MenuSelectWidget
);
18786 // For backwards compatibility
18787 OO
.ui
.TextInputMenuSelectWidget
= OO
.ui
.FloatingMenuSelectWidget
;
18792 * Handle window resize event.
18795 * @param {jQuery.Event} e Window resize event
18797 OO
.ui
.FloatingMenuSelectWidget
.prototype.onWindowResize = function () {
18804 OO
.ui
.FloatingMenuSelectWidget
.prototype.toggle = function ( visible
) {
18806 visible
= visible
=== undefined ? !this.isVisible() : !!visible
;
18808 change
= visible
!== this.isVisible();
18810 if ( change
&& visible
) {
18811 // Make sure the width is set before the parent method runs.
18812 // After this we have to call this.position(); again to actually
18813 // position ourselves correctly.
18818 OO
.ui
.FloatingMenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
18821 if ( this.isVisible() ) {
18823 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler
);
18825 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler
);
18833 * Position the menu.
18838 OO
.ui
.FloatingMenuSelectWidget
.prototype.position = function () {
18839 var $container
= this.$container
,
18840 pos
= OO
.ui
.Element
.static.getRelativePosition( $container
, this.$element
.offsetParent() );
18842 // Position under input
18843 pos
.top
+= $container
.height();
18844 this.$element
.css( pos
);
18847 this.setIdealSize( $container
.width() );
18848 // We updated the position, so re-evaluate the clipping state
18855 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
18856 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
18858 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
18861 * @extends OO.ui.SelectWidget
18862 * @mixins OO.ui.mixin.TabIndexedElement
18865 * @param {Object} [config] Configuration options
18867 OO
.ui
.OutlineSelectWidget
= function OoUiOutlineSelectWidget( config
) {
18868 // Parent constructor
18869 OO
.ui
.OutlineSelectWidget
.parent
.call( this, config
);
18871 // Mixin constructors
18872 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
18875 this.$element
.on( {
18876 focus
: this.bindKeyDownListener
.bind( this ),
18877 blur
: this.unbindKeyDownListener
.bind( this )
18881 this.$element
.addClass( 'oo-ui-outlineSelectWidget' );
18886 OO
.inheritClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.SelectWidget
);
18887 OO
.mixinClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
18890 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
18892 * **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.**
18895 * @extends OO.ui.SelectWidget
18896 * @mixins OO.ui.mixin.TabIndexedElement
18899 * @param {Object} [config] Configuration options
18901 OO
.ui
.TabSelectWidget
= function OoUiTabSelectWidget( config
) {
18902 // Parent constructor
18903 OO
.ui
.TabSelectWidget
.parent
.call( this, config
);
18905 // Mixin constructors
18906 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
18909 this.$element
.on( {
18910 focus
: this.bindKeyDownListener
.bind( this ),
18911 blur
: this.unbindKeyDownListener
.bind( this )
18915 this.$element
.addClass( 'oo-ui-tabSelectWidget' );
18920 OO
.inheritClass( OO
.ui
.TabSelectWidget
, OO
.ui
.SelectWidget
);
18921 OO
.mixinClass( OO
.ui
.TabSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
18924 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
18925 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
18926 * (to adjust the value in increments) to allow the user to enter a number.
18929 * // Example: A NumberInputWidget.
18930 * var numberInput = new OO.ui.NumberInputWidget( {
18931 * label: 'NumberInputWidget',
18932 * input: { value: 5, min: 1, max: 10 }
18934 * $( 'body' ).append( numberInput.$element );
18937 * @extends OO.ui.Widget
18940 * @param {Object} [config] Configuration options
18941 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
18942 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
18943 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
18944 * @cfg {boolean} [isInteger=false] Whether the field accepts only integer values.
18945 * @cfg {number} [min=-Infinity] Minimum allowed value
18946 * @cfg {number} [max=Infinity] Maximum allowed value
18947 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
18948 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
18950 OO
.ui
.NumberInputWidget
= function OoUiNumberInputWidget( config
) {
18951 // Configuration initialization
18952 config
= $.extend( {
18960 // Parent constructor
18961 OO
.ui
.NumberInputWidget
.parent
.call( this, config
);
18964 this.input
= new OO
.ui
.TextInputWidget( $.extend(
18966 disabled
: this.isDisabled()
18970 this.minusButton
= new OO
.ui
.ButtonWidget( $.extend(
18972 disabled
: this.isDisabled(),
18975 config
.minusButton
,
18977 classes
: [ 'oo-ui-numberInputWidget-minusButton' ],
18981 this.plusButton
= new OO
.ui
.ButtonWidget( $.extend(
18983 disabled
: this.isDisabled(),
18988 classes
: [ 'oo-ui-numberInputWidget-plusButton' ],
18994 this.input
.connect( this, {
18995 change
: this.emit
.bind( this, 'change' ),
18996 enter
: this.emit
.bind( this, 'enter' )
18998 this.input
.$input
.on( {
18999 keydown
: this.onKeyDown
.bind( this ),
19000 'wheel mousewheel DOMMouseScroll': this.onWheel
.bind( this )
19002 this.plusButton
.connect( this, {
19003 click
: [ 'onButtonClick', +1 ]
19005 this.minusButton
.connect( this, {
19006 click
: [ 'onButtonClick', -1 ]
19010 this.setIsInteger( !!config
.isInteger
);
19011 this.setRange( config
.min
, config
.max
);
19012 this.setStep( config
.step
, config
.pageStep
);
19014 this.$field
= $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' )
19016 this.minusButton
.$element
,
19017 this.input
.$element
,
19018 this.plusButton
.$element
19020 this.$element
.addClass( 'oo-ui-numberInputWidget' ).append( this.$field
);
19021 this.input
.setValidation( this.validateNumber
.bind( this ) );
19026 OO
.inheritClass( OO
.ui
.NumberInputWidget
, OO
.ui
.Widget
);
19031 * A `change` event is emitted when the value of the input changes.
19037 * An `enter` event is emitted when the user presses 'enter' inside the text box.
19045 * Set whether only integers are allowed
19046 * @param {boolean} flag
19048 OO
.ui
.NumberInputWidget
.prototype.setIsInteger = function ( flag
) {
19049 this.isInteger
= !!flag
;
19050 this.input
.setValidityFlag();
19054 * Get whether only integers are allowed
19055 * @return {boolean} Flag value
19057 OO
.ui
.NumberInputWidget
.prototype.getIsInteger = function () {
19058 return this.isInteger
;
19062 * Set the range of allowed values
19063 * @param {number} min Minimum allowed value
19064 * @param {number} max Maximum allowed value
19066 OO
.ui
.NumberInputWidget
.prototype.setRange = function ( min
, max
) {
19068 throw new Error( 'Minimum (' + min
+ ') must not be greater than maximum (' + max
+ ')' );
19072 this.input
.setValidityFlag();
19076 * Get the current range
19077 * @return {number[]} Minimum and maximum values
19079 OO
.ui
.NumberInputWidget
.prototype.getRange = function () {
19080 return [ this.min
, this.max
];
19084 * Set the stepping deltas
19085 * @param {number} step Normal step
19086 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
19088 OO
.ui
.NumberInputWidget
.prototype.setStep = function ( step
, pageStep
) {
19090 throw new Error( 'Step value must be positive' );
19092 if ( pageStep
=== null ) {
19093 pageStep
= step
* 10;
19094 } else if ( pageStep
<= 0 ) {
19095 throw new Error( 'Page step value must be positive' );
19098 this.pageStep
= pageStep
;
19102 * Get the current stepping values
19103 * @return {number[]} Step and page step
19105 OO
.ui
.NumberInputWidget
.prototype.getStep = function () {
19106 return [ this.step
, this.pageStep
];
19110 * Get the current value of the widget
19113 OO
.ui
.NumberInputWidget
.prototype.getValue = function () {
19114 return this.input
.getValue();
19118 * Get the current value of the widget as a number
19119 * @return {number} May be NaN, or an invalid number
19121 OO
.ui
.NumberInputWidget
.prototype.getNumericValue = function () {
19122 return +this.input
.getValue();
19126 * Set the value of the widget
19127 * @param {string} value Invalid values are allowed
19129 OO
.ui
.NumberInputWidget
.prototype.setValue = function ( value
) {
19130 this.input
.setValue( value
);
19134 * Adjust the value of the widget
19135 * @param {number} delta Adjustment amount
19137 OO
.ui
.NumberInputWidget
.prototype.adjustValue = function ( delta
) {
19138 var n
, v
= this.getNumericValue();
19141 if ( isNaN( delta
) || !isFinite( delta
) ) {
19142 throw new Error( 'Delta must be a finite number' );
19145 if ( isNaN( v
) ) {
19149 n
= Math
.max( Math
.min( n
, this.max
), this.min
);
19150 if ( this.isInteger
) {
19151 n
= Math
.round( n
);
19156 this.setValue( n
);
19163 * @param {string} value Field value
19164 * @return {boolean}
19166 OO
.ui
.NumberInputWidget
.prototype.validateNumber = function ( value
) {
19168 if ( isNaN( n
) || !isFinite( n
) ) {
19172 /*jshint bitwise: false */
19173 if ( this.isInteger
&& ( n
| 0 ) !== n
) {
19176 /*jshint bitwise: true */
19178 if ( n
< this.min
|| n
> this.max
) {
19186 * Handle mouse click events.
19189 * @param {number} dir +1 or -1
19191 OO
.ui
.NumberInputWidget
.prototype.onButtonClick = function ( dir
) {
19192 this.adjustValue( dir
* this.step
);
19196 * Handle mouse wheel events.
19199 * @param {jQuery.Event} event
19201 OO
.ui
.NumberInputWidget
.prototype.onWheel = function ( event
) {
19204 // Standard 'wheel' event
19205 if ( event
.originalEvent
.deltaMode
!== undefined ) {
19206 this.sawWheelEvent
= true;
19208 if ( event
.originalEvent
.deltaY
) {
19209 delta
= -event
.originalEvent
.deltaY
;
19210 } else if ( event
.originalEvent
.deltaX
) {
19211 delta
= event
.originalEvent
.deltaX
;
19214 // Non-standard events
19215 if ( !this.sawWheelEvent
) {
19216 if ( event
.originalEvent
.wheelDeltaX
) {
19217 delta
= -event
.originalEvent
.wheelDeltaX
;
19218 } else if ( event
.originalEvent
.wheelDeltaY
) {
19219 delta
= event
.originalEvent
.wheelDeltaY
;
19220 } else if ( event
.originalEvent
.wheelDelta
) {
19221 delta
= event
.originalEvent
.wheelDelta
;
19222 } else if ( event
.originalEvent
.detail
) {
19223 delta
= -event
.originalEvent
.detail
;
19228 delta
= delta
< 0 ? -1 : 1;
19229 this.adjustValue( delta
* this.step
);
19236 * Handle key down events.
19240 * @param {jQuery.Event} e Key down event
19242 OO
.ui
.NumberInputWidget
.prototype.onKeyDown = function ( e
) {
19243 if ( !this.isDisabled() ) {
19244 switch ( e
.which
) {
19245 case OO
.ui
.Keys
.UP
:
19246 this.adjustValue( this.step
);
19248 case OO
.ui
.Keys
.DOWN
:
19249 this.adjustValue( -this.step
);
19251 case OO
.ui
.Keys
.PAGEUP
:
19252 this.adjustValue( this.pageStep
);
19254 case OO
.ui
.Keys
.PAGEDOWN
:
19255 this.adjustValue( -this.pageStep
);
19264 OO
.ui
.NumberInputWidget
.prototype.setDisabled = function ( disabled
) {
19266 OO
.ui
.NumberInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
19268 if ( this.input
) {
19269 this.input
.setDisabled( this.isDisabled() );
19271 if ( this.minusButton
) {
19272 this.minusButton
.setDisabled( this.isDisabled() );
19274 if ( this.plusButton
) {
19275 this.plusButton
.setDisabled( this.isDisabled() );
19282 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
19283 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
19284 * visually by a slider in the leftmost position.
19287 * // Toggle switches in the 'off' and 'on' position.
19288 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
19289 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
19293 * // Create a FieldsetLayout to layout and label switches
19294 * var fieldset = new OO.ui.FieldsetLayout( {
19295 * label: 'Toggle switches'
19297 * fieldset.addItems( [
19298 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
19299 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
19301 * $( 'body' ).append( fieldset.$element );
19304 * @extends OO.ui.ToggleWidget
19305 * @mixins OO.ui.mixin.TabIndexedElement
19308 * @param {Object} [config] Configuration options
19309 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
19310 * By default, the toggle switch is in the 'off' position.
19312 OO
.ui
.ToggleSwitchWidget
= function OoUiToggleSwitchWidget( config
) {
19313 // Parent constructor
19314 OO
.ui
.ToggleSwitchWidget
.parent
.call( this, config
);
19316 // Mixin constructors
19317 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
19320 this.dragging
= false;
19321 this.dragStart
= null;
19322 this.sliding
= false;
19323 this.$glow
= $( '<span>' );
19324 this.$grip
= $( '<span>' );
19327 this.$element
.on( {
19328 click
: this.onClick
.bind( this ),
19329 keypress
: this.onKeyPress
.bind( this )
19333 this.$glow
.addClass( 'oo-ui-toggleSwitchWidget-glow' );
19334 this.$grip
.addClass( 'oo-ui-toggleSwitchWidget-grip' );
19336 .addClass( 'oo-ui-toggleSwitchWidget' )
19337 .attr( 'role', 'checkbox' )
19338 .append( this.$glow
, this.$grip
);
19343 OO
.inheritClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.ToggleWidget
);
19344 OO
.mixinClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.mixin
.TabIndexedElement
);
19349 * Handle mouse click events.
19352 * @param {jQuery.Event} e Mouse click event
19354 OO
.ui
.ToggleSwitchWidget
.prototype.onClick = function ( e
) {
19355 if ( !this.isDisabled() && e
.which
=== 1 ) {
19356 this.setValue( !this.value
);
19362 * Handle key press events.
19365 * @param {jQuery.Event} e Key press event
19367 OO
.ui
.ToggleSwitchWidget
.prototype.onKeyPress = function ( e
) {
19368 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
19369 this.setValue( !this.value
);
19375 * Deprecated aliases for classes in the `OO.ui.mixin` namespace.
19379 * @inheritdoc OO.ui.mixin.ButtonElement
19380 * @deprecated Use {@link OO.ui.mixin.ButtonElement} instead.
19382 OO
.ui
.ButtonElement
= OO
.ui
.mixin
.ButtonElement
;
19385 * @inheritdoc OO.ui.mixin.ClippableElement
19386 * @deprecated Use {@link OO.ui.mixin.ClippableElement} instead.
19388 OO
.ui
.ClippableElement
= OO
.ui
.mixin
.ClippableElement
;
19391 * @inheritdoc OO.ui.mixin.DraggableElement
19392 * @deprecated Use {@link OO.ui.mixin.DraggableElement} instead.
19394 OO
.ui
.DraggableElement
= OO
.ui
.mixin
.DraggableElement
;
19397 * @inheritdoc OO.ui.mixin.DraggableGroupElement
19398 * @deprecated Use {@link OO.ui.mixin.DraggableGroupElement} instead.
19400 OO
.ui
.DraggableGroupElement
= OO
.ui
.mixin
.DraggableGroupElement
;
19403 * @inheritdoc OO.ui.mixin.FlaggedElement
19404 * @deprecated Use {@link OO.ui.mixin.FlaggedElement} instead.
19406 OO
.ui
.FlaggedElement
= OO
.ui
.mixin
.FlaggedElement
;
19409 * @inheritdoc OO.ui.mixin.GroupElement
19410 * @deprecated Use {@link OO.ui.mixin.GroupElement} instead.
19412 OO
.ui
.GroupElement
= OO
.ui
.mixin
.GroupElement
;
19415 * @inheritdoc OO.ui.mixin.GroupWidget
19416 * @deprecated Use {@link OO.ui.mixin.GroupWidget} instead.
19418 OO
.ui
.GroupWidget
= OO
.ui
.mixin
.GroupWidget
;
19421 * @inheritdoc OO.ui.mixin.IconElement
19422 * @deprecated Use {@link OO.ui.mixin.IconElement} instead.
19424 OO
.ui
.IconElement
= OO
.ui
.mixin
.IconElement
;
19427 * @inheritdoc OO.ui.mixin.IndicatorElement
19428 * @deprecated Use {@link OO.ui.mixin.IndicatorElement} instead.
19430 OO
.ui
.IndicatorElement
= OO
.ui
.mixin
.IndicatorElement
;
19433 * @inheritdoc OO.ui.mixin.ItemWidget
19434 * @deprecated Use {@link OO.ui.mixin.ItemWidget} instead.
19436 OO
.ui
.ItemWidget
= OO
.ui
.mixin
.ItemWidget
;
19439 * @inheritdoc OO.ui.mixin.LabelElement
19440 * @deprecated Use {@link OO.ui.mixin.LabelElement} instead.
19442 OO
.ui
.LabelElement
= OO
.ui
.mixin
.LabelElement
;
19445 * @inheritdoc OO.ui.mixin.LookupElement
19446 * @deprecated Use {@link OO.ui.mixin.LookupElement} instead.
19448 OO
.ui
.LookupElement
= OO
.ui
.mixin
.LookupElement
;
19451 * @inheritdoc OO.ui.mixin.PendingElement
19452 * @deprecated Use {@link OO.ui.mixin.PendingElement} instead.
19454 OO
.ui
.PendingElement
= OO
.ui
.mixin
.PendingElement
;
19457 * @inheritdoc OO.ui.mixin.PopupElement
19458 * @deprecated Use {@link OO.ui.mixin.PopupElement} instead.
19460 OO
.ui
.PopupElement
= OO
.ui
.mixin
.PopupElement
;
19463 * @inheritdoc OO.ui.mixin.TabIndexedElement
19464 * @deprecated Use {@link OO.ui.mixin.TabIndexedElement} instead.
19466 OO
.ui
.TabIndexedElement
= OO
.ui
.mixin
.TabIndexedElement
;
19469 * @inheritdoc OO.ui.mixin.TitledElement
19470 * @deprecated Use {@link OO.ui.mixin.TitledElement} instead.
19472 OO
.ui
.TitledElement
= OO
.ui
.mixin
.TitledElement
;