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-29T21:20:38Z
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
) {
71 element
= $element
[ 0 ];
73 // Anything disabled is not focusable
74 if ( element
.disabled
) {
78 // Check if the element is visible
80 // This is quicker than calling $element.is( ':visible' )
81 $.expr
.filters
.visible( element
) &&
82 // Check that all parents are visible
83 !$element
.parents().addBack().filter( function () {
84 return $.css( this, 'visibility' ) === 'hidden';
90 // Check if the element is ContentEditable, which is the string 'true'
91 if ( element
.contentEditable
=== 'true' ) {
95 // Anything with a non-negative numeric tabIndex is focusable.
96 // Use .prop to avoid browser bugs
97 if ( $element
.prop( 'tabIndex' ) >= 0 ) {
101 // Some element types are naturally focusable
102 // (indexOf is much faster than regex in Chrome and about the
103 // same in FF: https://jsperf.com/regex-vs-indexof-array2)
104 nodeName
= element
.nodeName
.toLowerCase();
105 if ( [ 'input', 'select', 'textarea', 'button', 'object' ].indexOf( nodeName
) !== -1 ) {
109 // Links and areas are focusable if they have an href
110 if ( ( nodeName
=== 'a' || nodeName
=== 'area' ) && $element
.attr( 'href' ) !== undefined ) {
118 * Find a focusable child
120 * @param {jQuery} $container Container to search in
121 * @param {boolean} [backwards] Search backwards
122 * @return {jQuery} Focusable child, an empty jQuery object if none found
124 OO
.ui
.findFocusable = function ( $container
, backwards
) {
125 var $focusable
= $( [] ),
126 // $focusableCandidates is a superset of things that
127 // could get matched by isFocusableElement
128 $focusableCandidates
= $container
129 .find( 'input, select, textarea, button, object, a, area, [contenteditable], [tabindex]' );
132 $focusableCandidates
= Array
.prototype.reverse
.call( $focusableCandidates
);
135 $focusableCandidates
.each( function () {
136 var $this = $( this );
137 if ( OO
.ui
.isFocusableElement( $this ) ) {
146 * Get the user's language and any fallback languages.
148 * These language codes are used to localize user interface elements in the user's language.
150 * In environments that provide a localization system, this function should be overridden to
151 * return the user's language(s). The default implementation returns English (en) only.
153 * @return {string[]} Language codes, in descending order of priority
155 OO
.ui
.getUserLanguages = function () {
160 * Get a value in an object keyed by language code.
162 * @param {Object.<string,Mixed>} obj Object keyed by language code
163 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
164 * @param {string} [fallback] Fallback code, used if no matching language can be found
165 * @return {Mixed} Local value
167 OO
.ui
.getLocalValue = function ( obj
, lang
, fallback
) {
170 // Requested language
174 // Known user language
175 langs
= OO
.ui
.getUserLanguages();
176 for ( i
= 0, len
= langs
.length
; i
< len
; i
++ ) {
183 if ( obj
[ fallback
] ) {
184 return obj
[ fallback
];
186 // First existing language
187 for ( lang
in obj
) {
195 * Check if a node is contained within another node
197 * Similar to jQuery#contains except a list of containers can be supplied
198 * and a boolean argument allows you to include the container in the match list
200 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
201 * @param {HTMLElement} contained Node to find
202 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
203 * @return {boolean} The node is in the list of target nodes
205 OO
.ui
.contains = function ( containers
, contained
, matchContainers
) {
207 if ( !Array
.isArray( containers
) ) {
208 containers
= [ containers
];
210 for ( i
= containers
.length
- 1; i
>= 0; i
-- ) {
211 if ( ( matchContainers
&& contained
=== containers
[ i
] ) || $.contains( containers
[ i
], contained
) ) {
219 * Return a function, that, as long as it continues to be invoked, will not
220 * be triggered. The function will be called after it stops being called for
221 * N milliseconds. If `immediate` is passed, trigger the function on the
222 * leading edge, instead of the trailing.
224 * Ported from: http://underscorejs.org/underscore.js
226 * @param {Function} func
227 * @param {number} wait
228 * @param {boolean} immediate
231 OO
.ui
.debounce = function ( func
, wait
, immediate
) {
236 later = function () {
239 func
.apply( context
, args
);
242 if ( immediate
&& !timeout
) {
243 func
.apply( context
, args
);
245 clearTimeout( timeout
);
246 timeout
= setTimeout( later
, wait
);
251 * Proxy for `node.addEventListener( eventName, handler, true )`, if the browser supports it.
252 * Otherwise falls back to non-capturing event listeners.
254 * @param {HTMLElement} node
255 * @param {string} eventName
256 * @param {Function} handler
258 OO
.ui
.addCaptureEventListener = function ( node
, eventName
, handler
) {
259 if ( node
.addEventListener
) {
260 node
.addEventListener( eventName
, handler
, true );
262 node
.attachEvent( 'on' + eventName
, handler
);
267 * Proxy for `node.removeEventListener( eventName, handler, true )`, if the browser supports it.
268 * Otherwise falls back to non-capturing event listeners.
270 * @param {HTMLElement} node
271 * @param {string} eventName
272 * @param {Function} handler
274 OO
.ui
.removeCaptureEventListener = function ( node
, eventName
, handler
) {
275 if ( node
.addEventListener
) {
276 node
.removeEventListener( eventName
, handler
, true );
278 node
.detachEvent( 'on' + eventName
, handler
);
283 * Reconstitute a JavaScript object corresponding to a widget created by
284 * the PHP implementation.
286 * This is an alias for `OO.ui.Element.static.infuse()`.
288 * @param {string|HTMLElement|jQuery} idOrNode
289 * A DOM id (if a string) or node for the widget to infuse.
290 * @return {OO.ui.Element}
291 * The `OO.ui.Element` corresponding to this (infusable) document node.
293 OO
.ui
.infuse = function ( idOrNode
) {
294 return OO
.ui
.Element
.static.infuse( idOrNode
);
299 * Message store for the default implementation of OO.ui.msg
301 * Environments that provide a localization system should not use this, but should override
302 * OO.ui.msg altogether.
307 // Tool tip for a button that moves items in a list down one place
308 'ooui-outline-control-move-down': 'Move item down',
309 // Tool tip for a button that moves items in a list up one place
310 'ooui-outline-control-move-up': 'Move item up',
311 // Tool tip for a button that removes items from a list
312 'ooui-outline-control-remove': 'Remove item',
313 // Label for the toolbar group that contains a list of all other available tools
314 'ooui-toolbar-more': 'More',
315 // Label for the fake tool that expands the full list of tools in a toolbar group
316 'ooui-toolgroup-expand': 'More',
317 // Label for the fake tool that collapses the full list of tools in a toolbar group
318 'ooui-toolgroup-collapse': 'Fewer',
319 // Default label for the accept button of a confirmation dialog
320 'ooui-dialog-message-accept': 'OK',
321 // Default label for the reject button of a confirmation dialog
322 'ooui-dialog-message-reject': 'Cancel',
323 // Title for process dialog error description
324 'ooui-dialog-process-error': 'Something went wrong',
325 // Label for process dialog dismiss error button, visible when describing errors
326 'ooui-dialog-process-dismiss': 'Dismiss',
327 // Label for process dialog retry action button, visible when describing only recoverable errors
328 'ooui-dialog-process-retry': 'Try again',
329 // Label for process dialog retry action button, visible when describing only warnings
330 'ooui-dialog-process-continue': 'Continue',
331 // Label for the file selection widget's select file button
332 'ooui-selectfile-button-select': 'Select a file',
333 // Label for the file selection widget if file selection is not supported
334 'ooui-selectfile-not-supported': 'File selection is not supported',
335 // Label for the file selection widget when no file is currently selected
336 'ooui-selectfile-placeholder': 'No file is selected',
337 // Label for the file selection widget's drop target
338 'ooui-selectfile-dragdrop-placeholder': 'Drop file here'
342 * Get a localized message.
344 * In environments that provide a localization system, this function should be overridden to
345 * return the message translated in the user's language. The default implementation always returns
348 * After the message key, message parameters may optionally be passed. In the default implementation,
349 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
350 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
351 * they support unnamed, ordered message parameters.
354 * @param {string} key Message key
355 * @param {Mixed...} [params] Message parameters
356 * @return {string} Translated message with parameters substituted
358 OO
.ui
.msg = function ( key
) {
359 var message
= messages
[ key
],
360 params
= Array
.prototype.slice
.call( arguments
, 1 );
361 if ( typeof message
=== 'string' ) {
362 // Perform $1 substitution
363 message
= message
.replace( /\$(\d+)/g, function ( unused
, n
) {
364 var i
= parseInt( n
, 10 );
365 return params
[ i
- 1 ] !== undefined ? params
[ i
- 1 ] : '$' + n
;
368 // Return placeholder if message not found
369 message
= '[' + key
+ ']';
375 * Package a message and arguments for deferred resolution.
377 * Use this when you are statically specifying a message and the message may not yet be present.
379 * @param {string} key Message key
380 * @param {Mixed...} [params] Message parameters
381 * @return {Function} Function that returns the resolved message when executed
383 OO
.ui
.deferMsg = function () {
384 var args
= arguments
;
386 return OO
.ui
.msg
.apply( OO
.ui
, args
);
393 * If the message is a function it will be executed, otherwise it will pass through directly.
395 * @param {Function|string} msg Deferred message, or message text
396 * @return {string} Resolved message
398 OO
.ui
.resolveMsg = function ( msg
) {
399 if ( $.isFunction( msg
) ) {
406 * @param {string} url
409 OO
.ui
.isSafeUrl = function ( url
) {
411 // Keep in sync with php/Tag.php
413 'bitcoin:', 'ftp:', 'ftps:', 'geo:', 'git:', 'gopher:', 'http:', 'https:', 'irc:', 'ircs:',
414 'magnet:', 'mailto:', 'mms:', 'news:', 'nntp:', 'redis:', 'sftp:', 'sip:', 'sips:', 'sms:', 'ssh:',
415 'svn:', 'tel:', 'telnet:', 'urn:', 'worldwind:', 'xmpp:'
418 if ( url
.indexOf( ':' ) === -1 ) {
423 protocol
= url
.split( ':', 1 )[ 0 ] + ':';
424 if ( !protocol
.match( /^([A-za-z0-9\+\.\-])+:/ ) ) {
425 // Not a valid protocol, safe
429 // Safe if in the whitelist
430 return whitelist
.indexOf( protocol
) !== -1;
440 * Namespace for OOjs UI mixins.
442 * Mixins are named according to the type of object they are intended to
443 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
444 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
445 * is intended to be mixed in to an instance of OO.ui.Widget.
453 * PendingElement is a mixin that is used to create elements that notify users that something is happening
454 * and that they should wait before proceeding. The pending state is visually represented with a pending
455 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
456 * field of a {@link OO.ui.TextInputWidget text input widget}.
458 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
459 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
460 * in process dialogs.
463 * function MessageDialog( config ) {
464 * MessageDialog.parent.call( this, config );
466 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
468 * MessageDialog.static.actions = [
469 * { action: 'save', label: 'Done', flags: 'primary' },
470 * { label: 'Cancel', flags: 'safe' }
473 * MessageDialog.prototype.initialize = function () {
474 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
475 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
476 * 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>' );
477 * this.$body.append( this.content.$element );
479 * MessageDialog.prototype.getBodyHeight = function () {
482 * MessageDialog.prototype.getActionProcess = function ( action ) {
484 * if ( action === 'save' ) {
485 * dialog.getActions().get({actions: 'save'})[0].pushPending();
486 * return new OO.ui.Process()
488 * .next( function () {
489 * dialog.getActions().get({actions: 'save'})[0].popPending();
492 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
495 * var windowManager = new OO.ui.WindowManager();
496 * $( 'body' ).append( windowManager.$element );
498 * var dialog = new MessageDialog();
499 * windowManager.addWindows( [ dialog ] );
500 * windowManager.openWindow( dialog );
506 * @param {Object} [config] Configuration options
507 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
509 OO
.ui
.mixin
.PendingElement
= function OoUiMixinPendingElement( config
) {
510 // Configuration initialization
511 config
= config
|| {};
515 this.$pending
= null;
518 this.setPendingElement( config
.$pending
|| this.$element
);
523 OO
.initClass( OO
.ui
.mixin
.PendingElement
);
528 * Set the pending element (and clean up any existing one).
530 * @param {jQuery} $pending The element to set to pending.
532 OO
.ui
.mixin
.PendingElement
.prototype.setPendingElement = function ( $pending
) {
533 if ( this.$pending
) {
534 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
537 this.$pending
= $pending
;
538 if ( this.pending
> 0 ) {
539 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
544 * Check if an element is pending.
546 * @return {boolean} Element is pending
548 OO
.ui
.mixin
.PendingElement
.prototype.isPending = function () {
549 return !!this.pending
;
553 * Increase the pending counter. The pending state will remain active until the counter is zero
554 * (i.e., the number of calls to #pushPending and #popPending is the same).
558 OO
.ui
.mixin
.PendingElement
.prototype.pushPending = function () {
559 if ( this.pending
=== 0 ) {
560 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
561 this.updateThemeClasses();
569 * Decrease the pending counter. The pending state will remain active until the counter is zero
570 * (i.e., the number of calls to #pushPending and #popPending is the same).
574 OO
.ui
.mixin
.PendingElement
.prototype.popPending = function () {
575 if ( this.pending
=== 1 ) {
576 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
577 this.updateThemeClasses();
579 this.pending
= Math
.max( 0, this.pending
- 1 );
585 * ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them.
586 * Actions can be made available for specific contexts (modes) and circumstances
587 * (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
589 * ActionSets contain two types of actions:
591 * - 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.
592 * - Other: Other actions include all non-special visible actions.
594 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
597 * // Example: An action set used in a process dialog
598 * function MyProcessDialog( config ) {
599 * MyProcessDialog.parent.call( this, config );
601 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
602 * MyProcessDialog.static.title = 'An action set in a process dialog';
603 * // An action set that uses modes ('edit' and 'help' mode, in this example).
604 * MyProcessDialog.static.actions = [
605 * { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] },
606 * { action: 'help', modes: 'edit', label: 'Help' },
607 * { modes: 'edit', label: 'Cancel', flags: 'safe' },
608 * { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
611 * MyProcessDialog.prototype.initialize = function () {
612 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
613 * this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
614 * 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>' );
615 * this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
616 * 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>' );
617 * this.stackLayout = new OO.ui.StackLayout( {
618 * items: [ this.panel1, this.panel2 ]
620 * this.$body.append( this.stackLayout.$element );
622 * MyProcessDialog.prototype.getSetupProcess = function ( data ) {
623 * return MyProcessDialog.parent.prototype.getSetupProcess.call( this, data )
624 * .next( function () {
625 * this.actions.setMode( 'edit' );
628 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
629 * if ( action === 'help' ) {
630 * this.actions.setMode( 'help' );
631 * this.stackLayout.setItem( this.panel2 );
632 * } else if ( action === 'back' ) {
633 * this.actions.setMode( 'edit' );
634 * this.stackLayout.setItem( this.panel1 );
635 * } else if ( action === 'continue' ) {
637 * return new OO.ui.Process( function () {
641 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
643 * MyProcessDialog.prototype.getBodyHeight = function () {
644 * return this.panel1.$element.outerHeight( true );
646 * var windowManager = new OO.ui.WindowManager();
647 * $( 'body' ).append( windowManager.$element );
648 * var dialog = new MyProcessDialog( {
651 * windowManager.addWindows( [ dialog ] );
652 * windowManager.openWindow( dialog );
654 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
658 * @mixins OO.EventEmitter
661 * @param {Object} [config] Configuration options
663 OO
.ui
.ActionSet
= function OoUiActionSet( config
) {
664 // Configuration initialization
665 config
= config
|| {};
667 // Mixin constructors
668 OO
.EventEmitter
.call( this );
673 actions
: 'getAction',
677 this.categorized
= {};
680 this.organized
= false;
681 this.changing
= false;
682 this.changed
= false;
687 OO
.mixinClass( OO
.ui
.ActionSet
, OO
.EventEmitter
);
689 /* Static Properties */
692 * Symbolic name of the flags used to identify special actions. Special actions are displayed in the
693 * header of a {@link OO.ui.ProcessDialog process dialog}.
694 * See the [OOjs UI documentation on MediaWiki][2] for more information and examples.
696 * [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
703 OO
.ui
.ActionSet
.static.specialFlags
= [ 'safe', 'primary' ];
710 * A 'click' event is emitted when an action is clicked.
712 * @param {OO.ui.ActionWidget} action Action that was clicked
718 * A 'resize' event is emitted when an action widget is resized.
720 * @param {OO.ui.ActionWidget} action Action that was resized
726 * An 'add' event is emitted when actions are {@link #method-add added} to the action set.
728 * @param {OO.ui.ActionWidget[]} added Actions added
734 * A 'remove' event is emitted when actions are {@link #method-remove removed}
735 * or {@link #clear cleared}.
737 * @param {OO.ui.ActionWidget[]} added Actions removed
743 * A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
744 * or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed.
751 * Handle action change events.
756 OO
.ui
.ActionSet
.prototype.onActionChange = function () {
757 this.organized
= false;
758 if ( this.changing
) {
761 this.emit( 'change' );
766 * Check if an action is one of the special actions.
768 * @param {OO.ui.ActionWidget} action Action to check
769 * @return {boolean} Action is special
771 OO
.ui
.ActionSet
.prototype.isSpecial = function ( action
) {
774 for ( flag
in this.special
) {
775 if ( action
=== this.special
[ flag
] ) {
784 * Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
787 * @param {Object} [filters] Filters to use, omit to get all actions
788 * @param {string|string[]} [filters.actions] Actions that action widgets must have
789 * @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
790 * @param {string|string[]} [filters.modes] Modes that action widgets must have
791 * @param {boolean} [filters.visible] Action widgets must be visible
792 * @param {boolean} [filters.disabled] Action widgets must be disabled
793 * @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
795 OO
.ui
.ActionSet
.prototype.get = function ( filters
) {
796 var i
, len
, list
, category
, actions
, index
, match
, matches
;
801 // Collect category candidates
803 for ( category
in this.categorized
) {
804 list
= filters
[ category
];
806 if ( !Array
.isArray( list
) ) {
809 for ( i
= 0, len
= list
.length
; i
< len
; i
++ ) {
810 actions
= this.categorized
[ category
][ list
[ i
] ];
811 if ( Array
.isArray( actions
) ) {
812 matches
.push
.apply( matches
, actions
);
817 // Remove by boolean filters
818 for ( i
= 0, len
= matches
.length
; i
< len
; i
++ ) {
819 match
= matches
[ i
];
821 ( filters
.visible
!== undefined && match
.isVisible() !== filters
.visible
) ||
822 ( filters
.disabled
!== undefined && match
.isDisabled() !== filters
.disabled
)
824 matches
.splice( i
, 1 );
830 for ( i
= 0, len
= matches
.length
; i
< len
; i
++ ) {
831 match
= matches
[ i
];
832 index
= matches
.lastIndexOf( match
);
833 while ( index
!== i
) {
834 matches
.splice( index
, 1 );
836 index
= matches
.lastIndexOf( match
);
841 return this.list
.slice();
845 * Get 'special' actions.
847 * Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'.
848 * Special flags can be configured in subclasses by changing the static #specialFlags property.
850 * @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
852 OO
.ui
.ActionSet
.prototype.getSpecial = function () {
854 return $.extend( {}, this.special
);
858 * Get 'other' actions.
860 * Other actions include all non-special visible action widgets.
862 * @return {OO.ui.ActionWidget[]} 'Other' action widgets
864 OO
.ui
.ActionSet
.prototype.getOthers = function () {
866 return this.others
.slice();
870 * Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
871 * to be available in the specified mode will be made visible. All other actions will be hidden.
873 * @param {string} mode The mode. Only actions configured to be available in the specified
874 * mode will be made visible.
879 OO
.ui
.ActionSet
.prototype.setMode = function ( mode
) {
882 this.changing
= true;
883 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
884 action
= this.list
[ i
];
885 action
.toggle( action
.hasMode( mode
) );
888 this.organized
= false;
889 this.changing
= false;
890 this.emit( 'change' );
896 * Set the abilities of the specified actions.
898 * Action widgets that are configured with the specified actions will be enabled
899 * or disabled based on the boolean values specified in the `actions`
902 * @param {Object.<string,boolean>} actions A list keyed by action name with boolean
903 * values that indicate whether or not the action should be enabled.
906 OO
.ui
.ActionSet
.prototype.setAbilities = function ( actions
) {
907 var i
, len
, action
, item
;
909 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
910 item
= this.list
[ i
];
911 action
= item
.getAction();
912 if ( actions
[ action
] !== undefined ) {
913 item
.setDisabled( !actions
[ action
] );
921 * Executes a function once per action.
923 * When making changes to multiple actions, use this method instead of iterating over the actions
924 * manually to defer emitting a #change event until after all actions have been changed.
926 * @param {Object|null} actions Filters to use to determine which actions to iterate over; see #get
927 * @param {Function} callback Callback to run for each action; callback is invoked with three
928 * arguments: the action, the action's index, the list of actions being iterated over
931 OO
.ui
.ActionSet
.prototype.forEach = function ( filter
, callback
) {
932 this.changed
= false;
933 this.changing
= true;
934 this.get( filter
).forEach( callback
);
935 this.changing
= false;
936 if ( this.changed
) {
937 this.emit( 'change' );
944 * Add action widgets to the action set.
946 * @param {OO.ui.ActionWidget[]} actions Action widgets to add
951 OO
.ui
.ActionSet
.prototype.add = function ( actions
) {
954 this.changing
= true;
955 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
956 action
= actions
[ i
];
957 action
.connect( this, {
958 click
: [ 'emit', 'click', action
],
959 resize
: [ 'emit', 'resize', action
],
960 toggle
: [ 'onActionChange' ]
962 this.list
.push( action
);
964 this.organized
= false;
965 this.emit( 'add', actions
);
966 this.changing
= false;
967 this.emit( 'change' );
973 * Remove action widgets from the set.
975 * To remove all actions, you may wish to use the #clear method instead.
977 * @param {OO.ui.ActionWidget[]} actions Action widgets to remove
982 OO
.ui
.ActionSet
.prototype.remove = function ( actions
) {
983 var i
, len
, index
, action
;
985 this.changing
= true;
986 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
987 action
= actions
[ i
];
988 index
= this.list
.indexOf( action
);
989 if ( index
!== -1 ) {
990 action
.disconnect( this );
991 this.list
.splice( index
, 1 );
994 this.organized
= false;
995 this.emit( 'remove', actions
);
996 this.changing
= false;
997 this.emit( 'change' );
1003 * Remove all action widets from the set.
1005 * To remove only specified actions, use the {@link #method-remove remove} method instead.
1011 OO
.ui
.ActionSet
.prototype.clear = function () {
1013 removed
= this.list
.slice();
1015 this.changing
= true;
1016 for ( i
= 0, len
= this.list
.length
; i
< len
; i
++ ) {
1017 action
= this.list
[ i
];
1018 action
.disconnect( this );
1023 this.organized
= false;
1024 this.emit( 'remove', removed
);
1025 this.changing
= false;
1026 this.emit( 'change' );
1034 * This is called whenever organized information is requested. It will only reorganize the actions
1035 * if something has changed since the last time it ran.
1040 OO
.ui
.ActionSet
.prototype.organize = function () {
1041 var i
, iLen
, j
, jLen
, flag
, action
, category
, list
, item
, special
,
1042 specialFlags
= this.constructor.static.specialFlags
;
1044 if ( !this.organized
) {
1045 this.categorized
= {};
1048 for ( i
= 0, iLen
= this.list
.length
; i
< iLen
; i
++ ) {
1049 action
= this.list
[ i
];
1050 if ( action
.isVisible() ) {
1051 // Populate categories
1052 for ( category
in this.categories
) {
1053 if ( !this.categorized
[ category
] ) {
1054 this.categorized
[ category
] = {};
1056 list
= action
[ this.categories
[ category
] ]();
1057 if ( !Array
.isArray( list
) ) {
1060 for ( j
= 0, jLen
= list
.length
; j
< jLen
; j
++ ) {
1062 if ( !this.categorized
[ category
][ item
] ) {
1063 this.categorized
[ category
][ item
] = [];
1065 this.categorized
[ category
][ item
].push( action
);
1068 // Populate special/others
1070 for ( j
= 0, jLen
= specialFlags
.length
; j
< jLen
; j
++ ) {
1071 flag
= specialFlags
[ j
];
1072 if ( !this.special
[ flag
] && action
.hasFlag( flag
) ) {
1073 this.special
[ flag
] = action
;
1079 this.others
.push( action
);
1083 this.organized
= true;
1090 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
1091 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
1092 * connected to them and can't be interacted with.
1098 * @param {Object} [config] Configuration options
1099 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
1100 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
1102 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
1103 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
1104 * @cfg {string} [text] Text to insert
1105 * @cfg {Array} [content] An array of content elements to append (after #text).
1106 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
1107 * Instances of OO.ui.Element will have their $element appended.
1108 * @cfg {jQuery} [$content] Content elements to append (after #text)
1109 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
1110 * Data can also be specified with the #setData method.
1112 OO
.ui
.Element
= function OoUiElement( config
) {
1113 // Configuration initialization
1114 config
= config
|| {};
1118 this.visible
= true;
1119 this.data
= config
.data
;
1120 this.$element
= config
.$element
||
1121 $( document
.createElement( this.getTagName() ) );
1122 this.elementGroup
= null;
1123 this.debouncedUpdateThemeClassesHandler
= OO
.ui
.debounce( this.debouncedUpdateThemeClasses
);
1126 if ( Array
.isArray( config
.classes
) ) {
1127 this.$element
.addClass( config
.classes
.join( ' ' ) );
1130 this.$element
.attr( 'id', config
.id
);
1132 if ( config
.text
) {
1133 this.$element
.text( config
.text
);
1135 if ( config
.content
) {
1136 // The `content` property treats plain strings as text; use an
1137 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
1138 // appropriate $element appended.
1139 this.$element
.append( config
.content
.map( function ( v
) {
1140 if ( typeof v
=== 'string' ) {
1141 // Escape string so it is properly represented in HTML.
1142 return document
.createTextNode( v
);
1143 } else if ( v
instanceof OO
.ui
.HtmlSnippet
) {
1145 return v
.toString();
1146 } else if ( v
instanceof OO
.ui
.Element
) {
1152 if ( config
.$content
) {
1153 // The `$content` property treats plain strings as HTML.
1154 this.$element
.append( config
.$content
);
1160 OO
.initClass( OO
.ui
.Element
);
1162 /* Static Properties */
1165 * The name of the HTML tag used by the element.
1167 * The static value may be ignored if the #getTagName method is overridden.
1171 * @property {string}
1173 OO
.ui
.Element
.static.tagName
= 'div';
1175 /* Static Methods */
1178 * Reconstitute a JavaScript object corresponding to a widget created
1179 * by the PHP implementation.
1181 * @param {string|HTMLElement|jQuery} idOrNode
1182 * A DOM id (if a string) or node for the widget to infuse.
1183 * @return {OO.ui.Element}
1184 * The `OO.ui.Element` corresponding to this (infusable) document node.
1185 * For `Tag` objects emitted on the HTML side (used occasionally for content)
1186 * the value returned is a newly-created Element wrapping around the existing
1189 OO
.ui
.Element
.static.infuse = function ( idOrNode
) {
1190 var obj
= OO
.ui
.Element
.static.unsafeInfuse( idOrNode
, false );
1191 // Verify that the type matches up.
1192 // FIXME: uncomment after T89721 is fixed (see T90929)
1194 if ( !( obj instanceof this['class'] ) ) {
1195 throw new Error( 'Infusion type mismatch!' );
1202 * Implementation helper for `infuse`; skips the type check and has an
1203 * extra property so that only the top-level invocation touches the DOM.
1205 * @param {string|HTMLElement|jQuery} idOrNode
1206 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
1207 * when the top-level widget of this infusion is inserted into DOM,
1208 * replacing the original node; or false for top-level invocation.
1209 * @return {OO.ui.Element}
1211 OO
.ui
.Element
.static.unsafeInfuse = function ( idOrNode
, domPromise
) {
1212 // look for a cached result of a previous infusion.
1213 var id
, $elem
, data
, cls
, parts
, parent
, obj
, top
, state
;
1214 if ( typeof idOrNode
=== 'string' ) {
1216 $elem
= $( document
.getElementById( id
) );
1218 $elem
= $( idOrNode
);
1219 id
= $elem
.attr( 'id' );
1221 if ( !$elem
.length
) {
1222 throw new Error( 'Widget not found: ' + id
);
1224 data
= $elem
.data( 'ooui-infused' ) || $elem
[ 0 ].oouiInfused
;
1227 if ( data
=== true ) {
1228 throw new Error( 'Circular dependency! ' + id
);
1232 data
= $elem
.attr( 'data-ooui' );
1234 throw new Error( 'No infusion data found: ' + id
);
1237 data
= $.parseJSON( data
);
1241 if ( !( data
&& data
._
) ) {
1242 throw new Error( 'No valid infusion data found: ' + id
);
1244 if ( data
._
=== 'Tag' ) {
1245 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
1246 return new OO
.ui
.Element( { $element
: $elem
} );
1248 parts
= data
._
.split( '.' );
1249 cls
= OO
.getProp
.apply( OO
, [ window
].concat( parts
) );
1250 if ( cls
=== undefined ) {
1251 // The PHP output might be old and not including the "OO.ui" prefix
1252 // TODO: Remove this back-compat after next major release
1253 cls
= OO
.getProp
.apply( OO
, [ OO
.ui
].concat( parts
) );
1254 if ( cls
=== undefined ) {
1255 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
1259 // Verify that we're creating an OO.ui.Element instance
1260 parent
= cls
.parent
;
1262 while ( parent
!== undefined ) {
1263 if ( parent
=== OO
.ui
.Element
) {
1268 parent
= parent
.parent
;
1271 if ( parent
!== OO
.ui
.Element
) {
1272 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
1275 if ( domPromise
=== false ) {
1277 domPromise
= top
.promise();
1279 $elem
.data( 'ooui-infused', true ); // prevent loops
1280 data
.id
= id
; // implicit
1281 data
= OO
.copy( data
, null, function deserialize( value
) {
1282 if ( OO
.isPlainObject( value
) ) {
1284 return OO
.ui
.Element
.static.unsafeInfuse( value
.tag
, domPromise
);
1287 return new OO
.ui
.HtmlSnippet( value
.html
);
1291 // jscs:disable requireCapitalizedConstructors
1292 obj
= new cls( data
); // rebuild widget
1293 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
1294 state
= obj
.gatherPreInfuseState( $elem
);
1295 // now replace old DOM with this new DOM.
1297 $elem
.replaceWith( obj
.$element
);
1298 // This element is now gone from the DOM, but if anyone is holding a reference to it,
1299 // let's allow them to OO.ui.infuse() it and do what they expect (T105828).
1300 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
1301 $elem
[ 0 ].oouiInfused
= obj
;
1304 obj
.$element
.data( 'ooui-infused', obj
);
1305 // set the 'data-ooui' attribute so we can identify infused widgets
1306 obj
.$element
.attr( 'data-ooui', '' );
1307 // restore dynamic state after the new element is inserted into DOM
1308 domPromise
.done( obj
.restorePreInfuseState
.bind( obj
, state
) );
1313 * Get a jQuery function within a specific document.
1316 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
1317 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
1319 * @return {Function} Bound jQuery function
1321 OO
.ui
.Element
.static.getJQuery = function ( context
, $iframe
) {
1322 function wrapper( selector
) {
1323 return $( selector
, wrapper
.context
);
1326 wrapper
.context
= this.getDocument( context
);
1329 wrapper
.$iframe
= $iframe
;
1336 * Get the document of an element.
1339 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
1340 * @return {HTMLDocument|null} Document object
1342 OO
.ui
.Element
.static.getDocument = function ( obj
) {
1343 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
1344 return ( obj
[ 0 ] && obj
[ 0 ].ownerDocument
) ||
1345 // Empty jQuery selections might have a context
1348 obj
.ownerDocument
||
1352 ( obj
.nodeType
=== 9 && obj
) ||
1357 * Get the window of an element or document.
1360 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
1361 * @return {Window} Window object
1363 OO
.ui
.Element
.static.getWindow = function ( obj
) {
1364 var doc
= this.getDocument( obj
);
1366 // Standard Document.defaultView is IE9+
1367 return doc
.parentWindow
|| doc
.defaultView
;
1371 * Get the direction of an element or document.
1374 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
1375 * @return {string} Text direction, either 'ltr' or 'rtl'
1377 OO
.ui
.Element
.static.getDir = function ( obj
) {
1380 if ( obj
instanceof jQuery
) {
1383 isDoc
= obj
.nodeType
=== 9;
1384 isWin
= obj
.document
!== undefined;
1385 if ( isDoc
|| isWin
) {
1391 return $( obj
).css( 'direction' );
1395 * Get the offset between two frames.
1397 * TODO: Make this function not use recursion.
1400 * @param {Window} from Window of the child frame
1401 * @param {Window} [to=window] Window of the parent frame
1402 * @param {Object} [offset] Offset to start with, used internally
1403 * @return {Object} Offset object, containing left and top properties
1405 OO
.ui
.Element
.static.getFrameOffset = function ( from, to
, offset
) {
1406 var i
, len
, frames
, frame
, rect
;
1412 offset
= { top
: 0, left
: 0 };
1414 if ( from.parent
=== from ) {
1418 // Get iframe element
1419 frames
= from.parent
.document
.getElementsByTagName( 'iframe' );
1420 for ( i
= 0, len
= frames
.length
; i
< len
; i
++ ) {
1421 if ( frames
[ i
].contentWindow
=== from ) {
1422 frame
= frames
[ i
];
1427 // Recursively accumulate offset values
1429 rect
= frame
.getBoundingClientRect();
1430 offset
.left
+= rect
.left
;
1431 offset
.top
+= rect
.top
;
1432 if ( from !== to
) {
1433 this.getFrameOffset( from.parent
, offset
);
1440 * Get the offset between two elements.
1442 * The two elements may be in a different frame, but in that case the frame $element is in must
1443 * be contained in the frame $anchor is in.
1446 * @param {jQuery} $element Element whose position to get
1447 * @param {jQuery} $anchor Element to get $element's position relative to
1448 * @return {Object} Translated position coordinates, containing top and left properties
1450 OO
.ui
.Element
.static.getRelativePosition = function ( $element
, $anchor
) {
1451 var iframe
, iframePos
,
1452 pos
= $element
.offset(),
1453 anchorPos
= $anchor
.offset(),
1454 elementDocument
= this.getDocument( $element
),
1455 anchorDocument
= this.getDocument( $anchor
);
1457 // If $element isn't in the same document as $anchor, traverse up
1458 while ( elementDocument
!== anchorDocument
) {
1459 iframe
= elementDocument
.defaultView
.frameElement
;
1461 throw new Error( '$element frame is not contained in $anchor frame' );
1463 iframePos
= $( iframe
).offset();
1464 pos
.left
+= iframePos
.left
;
1465 pos
.top
+= iframePos
.top
;
1466 elementDocument
= iframe
.ownerDocument
;
1468 pos
.left
-= anchorPos
.left
;
1469 pos
.top
-= anchorPos
.top
;
1474 * Get element border sizes.
1477 * @param {HTMLElement} el Element to measure
1478 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1480 OO
.ui
.Element
.static.getBorders = function ( el
) {
1481 var doc
= el
.ownerDocument
,
1483 // Standard Document.defaultView is IE9+
1484 win
= doc
.parentWindow
|| doc
.defaultView
,
1485 style
= win
&& win
.getComputedStyle
?
1486 win
.getComputedStyle( el
, null ) :
1488 // Standard getComputedStyle() is IE9+
1491 top
= parseFloat( style
? style
.borderTopWidth
: $el
.css( 'borderTopWidth' ) ) || 0,
1492 left
= parseFloat( style
? style
.borderLeftWidth
: $el
.css( 'borderLeftWidth' ) ) || 0,
1493 bottom
= parseFloat( style
? style
.borderBottomWidth
: $el
.css( 'borderBottomWidth' ) ) || 0,
1494 right
= parseFloat( style
? style
.borderRightWidth
: $el
.css( 'borderRightWidth' ) ) || 0;
1505 * Get dimensions of an element or window.
1508 * @param {HTMLElement|Window} el Element to measure
1509 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1511 OO
.ui
.Element
.static.getDimensions = function ( el
) {
1513 doc
= el
.ownerDocument
|| el
.document
,
1515 // Standard Document.defaultView is IE9+
1516 win
= doc
.parentWindow
|| doc
.defaultView
;
1518 if ( win
=== el
|| el
=== doc
.documentElement
) {
1521 borders
: { top
: 0, left
: 0, bottom
: 0, right
: 0 },
1523 top
: $win
.scrollTop(),
1524 left
: $win
.scrollLeft()
1526 scrollbar
: { right
: 0, bottom
: 0 },
1530 bottom
: $win
.innerHeight(),
1531 right
: $win
.innerWidth()
1537 borders
: this.getBorders( el
),
1539 top
: $el
.scrollTop(),
1540 left
: $el
.scrollLeft()
1543 right
: $el
.innerWidth() - el
.clientWidth
,
1544 bottom
: $el
.innerHeight() - el
.clientHeight
1546 rect
: el
.getBoundingClientRect()
1552 * Get scrollable object parent
1554 * documentElement can't be used to get or set the scrollTop
1555 * property on Blink. Changing and testing its value lets us
1556 * use 'body' or 'documentElement' based on what is working.
1558 * https://code.google.com/p/chromium/issues/detail?id=303131
1561 * @param {HTMLElement} el Element to find scrollable parent for
1562 * @return {HTMLElement} Scrollable parent
1564 OO
.ui
.Element
.static.getRootScrollableElement = function ( el
) {
1565 var scrollTop
, body
;
1567 if ( OO
.ui
.scrollableElement
=== undefined ) {
1568 body
= el
.ownerDocument
.body
;
1569 scrollTop
= body
.scrollTop
;
1572 if ( body
.scrollTop
=== 1 ) {
1573 body
.scrollTop
= scrollTop
;
1574 OO
.ui
.scrollableElement
= 'body';
1576 OO
.ui
.scrollableElement
= 'documentElement';
1580 return el
.ownerDocument
[ OO
.ui
.scrollableElement
];
1584 * Get closest scrollable container.
1586 * Traverses up until either a scrollable element or the root is reached, in which case the window
1590 * @param {HTMLElement} el Element to find scrollable container for
1591 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1592 * @return {HTMLElement} Closest scrollable container
1594 OO
.ui
.Element
.static.getClosestScrollableContainer = function ( el
, dimension
) {
1596 // props = [ 'overflow' ] doesn't work due to https://bugzilla.mozilla.org/show_bug.cgi?id=889091
1597 props
= [ 'overflow-x', 'overflow-y' ],
1598 $parent
= $( el
).parent();
1600 if ( dimension
=== 'x' || dimension
=== 'y' ) {
1601 props
= [ 'overflow-' + dimension
];
1604 while ( $parent
.length
) {
1605 if ( $parent
[ 0 ] === this.getRootScrollableElement( el
) ) {
1606 return $parent
[ 0 ];
1610 val
= $parent
.css( props
[ i
] );
1611 if ( val
=== 'auto' || val
=== 'scroll' ) {
1612 return $parent
[ 0 ];
1615 $parent
= $parent
.parent();
1617 return this.getDocument( el
).body
;
1621 * Scroll element into view.
1624 * @param {HTMLElement} el Element to scroll into view
1625 * @param {Object} [config] Configuration options
1626 * @param {string} [config.duration] jQuery animation duration value
1627 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1628 * to scroll in both directions
1629 * @param {Function} [config.complete] Function to call when scrolling completes
1631 OO
.ui
.Element
.static.scrollIntoView = function ( el
, config
) {
1632 var rel
, anim
, callback
, sc
, $sc
, eld
, scd
, $win
;
1634 // Configuration initialization
1635 config
= config
|| {};
1638 callback
= typeof config
.complete
=== 'function' && config
.complete
;
1639 sc
= this.getClosestScrollableContainer( el
, config
.direction
);
1641 eld
= this.getDimensions( el
);
1642 scd
= this.getDimensions( sc
);
1643 $win
= $( this.getWindow( el
) );
1645 // Compute the distances between the edges of el and the edges of the scroll viewport
1646 if ( $sc
.is( 'html, body' ) ) {
1647 // If the scrollable container is the root, this is easy
1650 bottom
: $win
.innerHeight() - eld
.rect
.bottom
,
1651 left
: eld
.rect
.left
,
1652 right
: $win
.innerWidth() - eld
.rect
.right
1655 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1657 top
: eld
.rect
.top
- ( scd
.rect
.top
+ scd
.borders
.top
),
1658 bottom
: scd
.rect
.bottom
- scd
.borders
.bottom
- scd
.scrollbar
.bottom
- eld
.rect
.bottom
,
1659 left
: eld
.rect
.left
- ( scd
.rect
.left
+ scd
.borders
.left
),
1660 right
: scd
.rect
.right
- scd
.borders
.right
- scd
.scrollbar
.right
- eld
.rect
.right
1664 if ( !config
.direction
|| config
.direction
=== 'y' ) {
1665 if ( rel
.top
< 0 ) {
1666 anim
.scrollTop
= scd
.scroll
.top
+ rel
.top
;
1667 } else if ( rel
.top
> 0 && rel
.bottom
< 0 ) {
1668 anim
.scrollTop
= scd
.scroll
.top
+ Math
.min( rel
.top
, -rel
.bottom
);
1671 if ( !config
.direction
|| config
.direction
=== 'x' ) {
1672 if ( rel
.left
< 0 ) {
1673 anim
.scrollLeft
= scd
.scroll
.left
+ rel
.left
;
1674 } else if ( rel
.left
> 0 && rel
.right
< 0 ) {
1675 anim
.scrollLeft
= scd
.scroll
.left
+ Math
.min( rel
.left
, -rel
.right
);
1678 if ( !$.isEmptyObject( anim
) ) {
1679 $sc
.stop( true ).animate( anim
, config
.duration
|| 'fast' );
1681 $sc
.queue( function ( next
) {
1694 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1695 * and reserve space for them, because it probably doesn't.
1697 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1698 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1699 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1700 * and then reattach (or show) them back.
1703 * @param {HTMLElement} el Element to reconsider the scrollbars on
1705 OO
.ui
.Element
.static.reconsiderScrollbars = function ( el
) {
1706 var i
, len
, scrollLeft
, scrollTop
, nodes
= [];
1707 // Save scroll position
1708 scrollLeft
= el
.scrollLeft
;
1709 scrollTop
= el
.scrollTop
;
1710 // Detach all children
1711 while ( el
.firstChild
) {
1712 nodes
.push( el
.firstChild
);
1713 el
.removeChild( el
.firstChild
);
1716 void el
.offsetHeight
;
1717 // Reattach all children
1718 for ( i
= 0, len
= nodes
.length
; i
< len
; i
++ ) {
1719 el
.appendChild( nodes
[ i
] );
1721 // Restore scroll position (no-op if scrollbars disappeared)
1722 el
.scrollLeft
= scrollLeft
;
1723 el
.scrollTop
= scrollTop
;
1729 * Toggle visibility of an element.
1731 * @param {boolean} [show] Make element visible, omit to toggle visibility
1735 OO
.ui
.Element
.prototype.toggle = function ( show
) {
1736 show
= show
=== undefined ? !this.visible
: !!show
;
1738 if ( show
!== this.isVisible() ) {
1739 this.visible
= show
;
1740 this.$element
.toggleClass( 'oo-ui-element-hidden', !this.visible
);
1741 this.emit( 'toggle', show
);
1748 * Check if element is visible.
1750 * @return {boolean} element is visible
1752 OO
.ui
.Element
.prototype.isVisible = function () {
1753 return this.visible
;
1759 * @return {Mixed} Element data
1761 OO
.ui
.Element
.prototype.getData = function () {
1768 * @param {Mixed} Element data
1771 OO
.ui
.Element
.prototype.setData = function ( data
) {
1777 * Check if element supports one or more methods.
1779 * @param {string|string[]} methods Method or list of methods to check
1780 * @return {boolean} All methods are supported
1782 OO
.ui
.Element
.prototype.supports = function ( methods
) {
1786 methods
= Array
.isArray( methods
) ? methods
: [ methods
];
1787 for ( i
= 0, len
= methods
.length
; i
< len
; i
++ ) {
1788 if ( $.isFunction( this[ methods
[ i
] ] ) ) {
1793 return methods
.length
=== support
;
1797 * Update the theme-provided classes.
1799 * @localdoc This is called in element mixins and widget classes any time state changes.
1800 * Updating is debounced, minimizing overhead of changing multiple attributes and
1801 * guaranteeing that theme updates do not occur within an element's constructor
1803 OO
.ui
.Element
.prototype.updateThemeClasses = function () {
1804 this.debouncedUpdateThemeClassesHandler();
1809 * @localdoc This method is called directly from the QUnit tests instead of #updateThemeClasses, to
1810 * make them synchronous.
1812 OO
.ui
.Element
.prototype.debouncedUpdateThemeClasses = function () {
1813 OO
.ui
.theme
.updateElementClasses( this );
1817 * Get the HTML tag name.
1819 * Override this method to base the result on instance information.
1821 * @return {string} HTML tag name
1823 OO
.ui
.Element
.prototype.getTagName = function () {
1824 return this.constructor.static.tagName
;
1828 * Check if the element is attached to the DOM
1829 * @return {boolean} The element is attached to the DOM
1831 OO
.ui
.Element
.prototype.isElementAttached = function () {
1832 return $.contains( this.getElementDocument(), this.$element
[ 0 ] );
1836 * Get the DOM document.
1838 * @return {HTMLDocument} Document object
1840 OO
.ui
.Element
.prototype.getElementDocument = function () {
1841 // Don't cache this in other ways either because subclasses could can change this.$element
1842 return OO
.ui
.Element
.static.getDocument( this.$element
);
1846 * Get the DOM window.
1848 * @return {Window} Window object
1850 OO
.ui
.Element
.prototype.getElementWindow = function () {
1851 return OO
.ui
.Element
.static.getWindow( this.$element
);
1855 * Get closest scrollable container.
1857 OO
.ui
.Element
.prototype.getClosestScrollableElementContainer = function () {
1858 return OO
.ui
.Element
.static.getClosestScrollableContainer( this.$element
[ 0 ] );
1862 * Get group element is in.
1864 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1866 OO
.ui
.Element
.prototype.getElementGroup = function () {
1867 return this.elementGroup
;
1871 * Set group element is in.
1873 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1876 OO
.ui
.Element
.prototype.setElementGroup = function ( group
) {
1877 this.elementGroup
= group
;
1882 * Scroll element into view.
1884 * @param {Object} [config] Configuration options
1886 OO
.ui
.Element
.prototype.scrollElementIntoView = function ( config
) {
1887 return OO
.ui
.Element
.static.scrollIntoView( this.$element
[ 0 ], config
);
1891 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of a HTML DOM node
1892 * (and its children) that represent an Element of the same type and configuration as the current
1893 * one, generated by the PHP implementation.
1895 * This method is called just before `node` is detached from the DOM. The return value of this
1896 * function will be passed to #restorePreInfuseState after this widget's #$element is inserted into
1897 * DOM to replace `node`.
1900 * @param {HTMLElement} node
1903 OO
.ui
.Element
.prototype.gatherPreInfuseState = function () {
1908 * Restore the pre-infusion dynamic state for this widget.
1910 * This method is called after #$element has been inserted into DOM. The parameter is the return
1911 * value of #gatherPreInfuseState.
1914 * @param {Object} state
1916 OO
.ui
.Element
.prototype.restorePreInfuseState = function () {
1920 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1921 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1922 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1923 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1924 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1928 * @extends OO.ui.Element
1929 * @mixins OO.EventEmitter
1932 * @param {Object} [config] Configuration options
1934 OO
.ui
.Layout
= function OoUiLayout( config
) {
1935 // Configuration initialization
1936 config
= config
|| {};
1938 // Parent constructor
1939 OO
.ui
.Layout
.parent
.call( this, config
);
1941 // Mixin constructors
1942 OO
.EventEmitter
.call( this );
1945 this.$element
.addClass( 'oo-ui-layout' );
1950 OO
.inheritClass( OO
.ui
.Layout
, OO
.ui
.Element
);
1951 OO
.mixinClass( OO
.ui
.Layout
, OO
.EventEmitter
);
1954 * Widgets are compositions of one or more OOjs UI elements that users can both view
1955 * and interact with. All widgets can be configured and modified via a standard API,
1956 * and their state can change dynamically according to a model.
1960 * @extends OO.ui.Element
1961 * @mixins OO.EventEmitter
1964 * @param {Object} [config] Configuration options
1965 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1966 * appearance reflects this state.
1968 OO
.ui
.Widget
= function OoUiWidget( config
) {
1969 // Initialize config
1970 config
= $.extend( { disabled
: false }, config
);
1972 // Parent constructor
1973 OO
.ui
.Widget
.parent
.call( this, config
);
1975 // Mixin constructors
1976 OO
.EventEmitter
.call( this );
1979 this.disabled
= null;
1980 this.wasDisabled
= null;
1983 this.$element
.addClass( 'oo-ui-widget' );
1984 this.setDisabled( !!config
.disabled
);
1989 OO
.inheritClass( OO
.ui
.Widget
, OO
.ui
.Element
);
1990 OO
.mixinClass( OO
.ui
.Widget
, OO
.EventEmitter
);
1992 /* Static Properties */
1995 * Whether this widget will behave reasonably when wrapped in a HTML `<label>`. If this is true,
1996 * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click
2001 * @property {boolean}
2003 OO
.ui
.Widget
.static.supportsSimpleLabel
= false;
2010 * A 'disable' event is emitted when the disabled state of the widget changes
2011 * (i.e. on disable **and** enable).
2013 * @param {boolean} disabled Widget is disabled
2019 * A 'toggle' event is emitted when the visibility of the widget changes.
2021 * @param {boolean} visible Widget is visible
2027 * Check if the widget is disabled.
2029 * @return {boolean} Widget is disabled
2031 OO
.ui
.Widget
.prototype.isDisabled = function () {
2032 return this.disabled
;
2036 * Set the 'disabled' state of the widget.
2038 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
2040 * @param {boolean} disabled Disable widget
2043 OO
.ui
.Widget
.prototype.setDisabled = function ( disabled
) {
2046 this.disabled
= !!disabled
;
2047 isDisabled
= this.isDisabled();
2048 if ( isDisabled
!== this.wasDisabled
) {
2049 this.$element
.toggleClass( 'oo-ui-widget-disabled', isDisabled
);
2050 this.$element
.toggleClass( 'oo-ui-widget-enabled', !isDisabled
);
2051 this.$element
.attr( 'aria-disabled', isDisabled
.toString() );
2052 this.emit( 'disable', isDisabled
);
2053 this.updateThemeClasses();
2055 this.wasDisabled
= isDisabled
;
2061 * Update the disabled state, in case of changes in parent widget.
2065 OO
.ui
.Widget
.prototype.updateDisabled = function () {
2066 this.setDisabled( this.disabled
);
2071 * A window is a container for elements that are in a child frame. They are used with
2072 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
2073 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
2074 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
2075 * the window manager will choose a sensible fallback.
2077 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
2078 * different processes are executed:
2080 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
2081 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
2084 * - {@link #getSetupProcess} method is called and its result executed
2085 * - {@link #getReadyProcess} method is called and its result executed
2087 * **opened**: The window is now open
2089 * **closing**: The closing stage begins when the window manager's
2090 * {@link OO.ui.WindowManager#closeWindow closeWindow}
2091 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
2093 * - {@link #getHoldProcess} method is called and its result executed
2094 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
2096 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
2097 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
2098 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
2099 * processing can complete. Always assume window processes are executed asynchronously.
2101 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2103 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
2107 * @extends OO.ui.Element
2108 * @mixins OO.EventEmitter
2111 * @param {Object} [config] Configuration options
2112 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
2113 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
2115 OO
.ui
.Window
= function OoUiWindow( config
) {
2116 // Configuration initialization
2117 config
= config
|| {};
2119 // Parent constructor
2120 OO
.ui
.Window
.parent
.call( this, config
);
2122 // Mixin constructors
2123 OO
.EventEmitter
.call( this );
2126 this.manager
= null;
2127 this.size
= config
.size
|| this.constructor.static.size
;
2128 this.$frame
= $( '<div>' );
2129 this.$overlay
= $( '<div>' );
2130 this.$content
= $( '<div>' );
2132 this.$focusTrapBefore
= $( '<div>' ).prop( 'tabIndex', 0 );
2133 this.$focusTrapAfter
= $( '<div>' ).prop( 'tabIndex', 0 );
2134 this.$focusTraps
= this.$focusTrapBefore
.add( this.$focusTrapAfter
);
2137 this.$overlay
.addClass( 'oo-ui-window-overlay' );
2139 .addClass( 'oo-ui-window-content' )
2140 .attr( 'tabindex', 0 );
2142 .addClass( 'oo-ui-window-frame' )
2143 .append( this.$focusTrapBefore
, this.$content
, this.$focusTrapAfter
);
2146 .addClass( 'oo-ui-window' )
2147 .append( this.$frame
, this.$overlay
);
2149 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
2150 // that reference properties not initialized at that time of parent class construction
2151 // TODO: Find a better way to handle post-constructor setup
2152 this.visible
= false;
2153 this.$element
.addClass( 'oo-ui-element-hidden' );
2158 OO
.inheritClass( OO
.ui
.Window
, OO
.ui
.Element
);
2159 OO
.mixinClass( OO
.ui
.Window
, OO
.EventEmitter
);
2161 /* Static Properties */
2164 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
2166 * The static size is used if no #size is configured during construction.
2170 * @property {string}
2172 OO
.ui
.Window
.static.size
= 'medium';
2177 * Handle mouse down events.
2180 * @param {jQuery.Event} e Mouse down event
2182 OO
.ui
.Window
.prototype.onMouseDown = function ( e
) {
2183 // Prevent clicking on the click-block from stealing focus
2184 if ( e
.target
=== this.$element
[ 0 ] ) {
2190 * Check if the window has been initialized.
2192 * Initialization occurs when a window is added to a manager.
2194 * @return {boolean} Window has been initialized
2196 OO
.ui
.Window
.prototype.isInitialized = function () {
2197 return !!this.manager
;
2201 * Check if the window is visible.
2203 * @return {boolean} Window is visible
2205 OO
.ui
.Window
.prototype.isVisible = function () {
2206 return this.visible
;
2210 * Check if the window is opening.
2212 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
2215 * @return {boolean} Window is opening
2217 OO
.ui
.Window
.prototype.isOpening = function () {
2218 return this.manager
.isOpening( this );
2222 * Check if the window is closing.
2224 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
2226 * @return {boolean} Window is closing
2228 OO
.ui
.Window
.prototype.isClosing = function () {
2229 return this.manager
.isClosing( this );
2233 * Check if the window is opened.
2235 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
2237 * @return {boolean} Window is opened
2239 OO
.ui
.Window
.prototype.isOpened = function () {
2240 return this.manager
.isOpened( this );
2244 * Get the window manager.
2246 * All windows must be attached to a window manager, which is used to open
2247 * and close the window and control its presentation.
2249 * @return {OO.ui.WindowManager} Manager of window
2251 OO
.ui
.Window
.prototype.getManager = function () {
2252 return this.manager
;
2256 * Get the symbolic name of the window size (e.g., `small` or `medium`).
2258 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
2260 OO
.ui
.Window
.prototype.getSize = function () {
2261 var viewport
= OO
.ui
.Element
.static.getDimensions( this.getElementWindow() ),
2262 sizes
= this.manager
.constructor.static.sizes
,
2265 if ( !sizes
[ size
] ) {
2266 size
= this.manager
.constructor.static.defaultSize
;
2268 if ( size
!== 'full' && viewport
.rect
.right
- viewport
.rect
.left
< sizes
[ size
].width
) {
2276 * Get the size properties associated with the current window size
2278 * @return {Object} Size properties
2280 OO
.ui
.Window
.prototype.getSizeProperties = function () {
2281 return this.manager
.constructor.static.sizes
[ this.getSize() ];
2285 * Disable transitions on window's frame for the duration of the callback function, then enable them
2289 * @param {Function} callback Function to call while transitions are disabled
2291 OO
.ui
.Window
.prototype.withoutSizeTransitions = function ( callback
) {
2292 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2293 // Disable transitions first, otherwise we'll get values from when the window was animating.
2295 styleObj
= this.$frame
[ 0 ].style
;
2296 oldTransition
= styleObj
.transition
|| styleObj
.OTransition
|| styleObj
.MsTransition
||
2297 styleObj
.MozTransition
|| styleObj
.WebkitTransition
;
2298 styleObj
.transition
= styleObj
.OTransition
= styleObj
.MsTransition
=
2299 styleObj
.MozTransition
= styleObj
.WebkitTransition
= 'none';
2301 // Force reflow to make sure the style changes done inside callback really are not transitioned
2302 this.$frame
.height();
2303 styleObj
.transition
= styleObj
.OTransition
= styleObj
.MsTransition
=
2304 styleObj
.MozTransition
= styleObj
.WebkitTransition
= oldTransition
;
2308 * Get the height of the full window contents (i.e., the window head, body and foot together).
2310 * What consistitutes the head, body, and foot varies depending on the window type.
2311 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
2312 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
2313 * and special actions in the head, and dialog content in the body.
2315 * To get just the height of the dialog body, use the #getBodyHeight method.
2317 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
2319 OO
.ui
.Window
.prototype.getContentHeight = function () {
2322 bodyStyleObj
= this.$body
[ 0 ].style
,
2323 frameStyleObj
= this.$frame
[ 0 ].style
;
2325 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
2326 // Disable transitions first, otherwise we'll get values from when the window was animating.
2327 this.withoutSizeTransitions( function () {
2328 var oldHeight
= frameStyleObj
.height
,
2329 oldPosition
= bodyStyleObj
.position
;
2330 frameStyleObj
.height
= '1px';
2331 // Force body to resize to new width
2332 bodyStyleObj
.position
= 'relative';
2333 bodyHeight
= win
.getBodyHeight();
2334 frameStyleObj
.height
= oldHeight
;
2335 bodyStyleObj
.position
= oldPosition
;
2339 // Add buffer for border
2340 ( this.$frame
.outerHeight() - this.$frame
.innerHeight() ) +
2341 // Use combined heights of children
2342 ( this.$head
.outerHeight( true ) + bodyHeight
+ this.$foot
.outerHeight( true ) )
2347 * Get the height of the window body.
2349 * To get the height of the full window contents (the window body, head, and foot together),
2350 * use #getContentHeight.
2352 * When this function is called, the window will temporarily have been resized
2353 * to height=1px, so .scrollHeight measurements can be taken accurately.
2355 * @return {number} Height of the window body in pixels
2357 OO
.ui
.Window
.prototype.getBodyHeight = function () {
2358 return this.$body
[ 0 ].scrollHeight
;
2362 * Get the directionality of the frame (right-to-left or left-to-right).
2364 * @return {string} Directionality: `'ltr'` or `'rtl'`
2366 OO
.ui
.Window
.prototype.getDir = function () {
2367 return OO
.ui
.Element
.static.getDir( this.$content
) || 'ltr';
2371 * Get the 'setup' process.
2373 * The setup process is used to set up a window for use in a particular context,
2374 * based on the `data` argument. This method is called during the opening phase of the window’s
2377 * Override this method to add additional steps to the ‘setup’ process the parent method provides
2378 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2381 * To add window content that persists between openings, you may wish to use the #initialize method
2385 * @param {Object} [data] Window opening data
2386 * @return {OO.ui.Process} Setup process
2388 OO
.ui
.Window
.prototype.getSetupProcess = function () {
2389 return new OO
.ui
.Process();
2393 * Get the ‘ready’ process.
2395 * The ready process is used to ready a window for use in a particular
2396 * context, based on the `data` argument. This method is called during the opening phase of
2397 * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
2399 * Override this method to add additional steps to the ‘ready’ process the parent method
2400 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
2401 * methods of OO.ui.Process.
2404 * @param {Object} [data] Window opening data
2405 * @return {OO.ui.Process} Ready process
2407 OO
.ui
.Window
.prototype.getReadyProcess = function () {
2408 return new OO
.ui
.Process();
2412 * Get the 'hold' process.
2414 * The hold proccess is used to keep a window from being used in a particular context,
2415 * based on the `data` argument. This method is called during the closing phase of the window’s
2418 * Override this method to add additional steps to the 'hold' process the parent method provides
2419 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2423 * @param {Object} [data] Window closing data
2424 * @return {OO.ui.Process} Hold process
2426 OO
.ui
.Window
.prototype.getHoldProcess = function () {
2427 return new OO
.ui
.Process();
2431 * Get the ‘teardown’ process.
2433 * The teardown process is used to teardown a window after use. During teardown,
2434 * user interactions within the window are conveyed and the window is closed, based on the `data`
2435 * argument. This method is called during the closing phase of the window’s lifecycle.
2437 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
2438 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2442 * @param {Object} [data] Window closing data
2443 * @return {OO.ui.Process} Teardown process
2445 OO
.ui
.Window
.prototype.getTeardownProcess = function () {
2446 return new OO
.ui
.Process();
2450 * Set the window manager.
2452 * This will cause the window to initialize. Calling it more than once will cause an error.
2454 * @param {OO.ui.WindowManager} manager Manager for this window
2455 * @throws {Error} An error is thrown if the method is called more than once
2458 OO
.ui
.Window
.prototype.setManager = function ( manager
) {
2459 if ( this.manager
) {
2460 throw new Error( 'Cannot set window manager, window already has a manager' );
2463 this.manager
= manager
;
2470 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2472 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2476 OO
.ui
.Window
.prototype.setSize = function ( size
) {
2483 * Update the window size.
2485 * @throws {Error} An error is thrown if the window is not attached to a window manager
2488 OO
.ui
.Window
.prototype.updateSize = function () {
2489 if ( !this.manager
) {
2490 throw new Error( 'Cannot update window size, must be attached to a manager' );
2493 this.manager
.updateWindowSize( this );
2499 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2500 * when the window is opening. In general, setDimensions should not be called directly.
2502 * To set the size of the window, use the #setSize method.
2504 * @param {Object} dim CSS dimension properties
2505 * @param {string|number} [dim.width] Width
2506 * @param {string|number} [dim.minWidth] Minimum width
2507 * @param {string|number} [dim.maxWidth] Maximum width
2508 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2509 * @param {string|number} [dim.minWidth] Minimum height
2510 * @param {string|number} [dim.maxWidth] Maximum height
2513 OO
.ui
.Window
.prototype.setDimensions = function ( dim
) {
2516 styleObj
= this.$frame
[ 0 ].style
;
2518 // Calculate the height we need to set using the correct width
2519 if ( dim
.height
=== undefined ) {
2520 this.withoutSizeTransitions( function () {
2521 var oldWidth
= styleObj
.width
;
2522 win
.$frame
.css( 'width', dim
.width
|| '' );
2523 height
= win
.getContentHeight();
2524 styleObj
.width
= oldWidth
;
2527 height
= dim
.height
;
2531 width
: dim
.width
|| '',
2532 minWidth
: dim
.minWidth
|| '',
2533 maxWidth
: dim
.maxWidth
|| '',
2534 height
: height
|| '',
2535 minHeight
: dim
.minHeight
|| '',
2536 maxHeight
: dim
.maxHeight
|| ''
2543 * Initialize window contents.
2545 * Before the window is opened for the first time, #initialize is called so that content that
2546 * persists between openings can be added to the window.
2548 * To set up a window with new content each time the window opens, use #getSetupProcess.
2550 * @throws {Error} An error is thrown if the window is not attached to a window manager
2553 OO
.ui
.Window
.prototype.initialize = function () {
2554 if ( !this.manager
) {
2555 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2559 this.$head
= $( '<div>' );
2560 this.$body
= $( '<div>' );
2561 this.$foot
= $( '<div>' );
2562 this.$document
= $( this.getElementDocument() );
2565 this.$element
.on( 'mousedown', this.onMouseDown
.bind( this ) );
2568 this.$head
.addClass( 'oo-ui-window-head' );
2569 this.$body
.addClass( 'oo-ui-window-body' );
2570 this.$foot
.addClass( 'oo-ui-window-foot' );
2571 this.$content
.append( this.$head
, this.$body
, this.$foot
);
2577 * Called when someone tries to focus the hidden element at the end of the dialog.
2578 * Sends focus back to the start of the dialog.
2580 * @param {jQuery.Event} event Focus event
2582 OO
.ui
.Window
.prototype.onFocusTrapFocused = function ( event
) {
2583 if ( this.$focusTrapBefore
.is( event
.target
) ) {
2584 OO
.ui
.findFocusable( this.$content
, true ).focus();
2586 // this.$content is the part of the focus cycle, and is the first focusable element
2587 this.$content
.focus();
2594 * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
2595 * method, which returns a promise resolved when the window is done opening.
2597 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2599 * @param {Object} [data] Window opening data
2600 * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
2601 * if the window fails to open. When the promise is resolved successfully, the first argument of the
2602 * value is a new promise, which is resolved when the window begins closing.
2603 * @throws {Error} An error is thrown if the window is not attached to a window manager
2605 OO
.ui
.Window
.prototype.open = function ( data
) {
2606 if ( !this.manager
) {
2607 throw new Error( 'Cannot open window, must be attached to a manager' );
2610 return this.manager
.openWindow( this, data
);
2616 * This method is a wrapper around a call to the window
2617 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
2618 * which returns a closing promise resolved when the window is done closing.
2620 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2621 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2622 * the window closes.
2624 * @param {Object} [data] Window closing data
2625 * @return {jQuery.Promise} Promise resolved when window is closed
2626 * @throws {Error} An error is thrown if the window is not attached to a window manager
2628 OO
.ui
.Window
.prototype.close = function ( data
) {
2629 if ( !this.manager
) {
2630 throw new Error( 'Cannot close window, must be attached to a manager' );
2633 return this.manager
.closeWindow( this, data
);
2639 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2642 * @param {Object} [data] Window opening data
2643 * @return {jQuery.Promise} Promise resolved when window is setup
2645 OO
.ui
.Window
.prototype.setup = function ( data
) {
2647 deferred
= $.Deferred();
2649 this.toggle( true );
2651 this.focusTrapHandler
= OO
.ui
.bind( this.onFocusTrapFocused
, this );
2652 this.$focusTraps
.on( 'focus', this.focusTrapHandler
);
2654 this.getSetupProcess( data
).execute().done( function () {
2655 // Force redraw by asking the browser to measure the elements' widths
2656 win
.$element
.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2657 win
.$content
.addClass( 'oo-ui-window-content-setup' ).width();
2661 return deferred
.promise();
2667 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2670 * @param {Object} [data] Window opening data
2671 * @return {jQuery.Promise} Promise resolved when window is ready
2673 OO
.ui
.Window
.prototype.ready = function ( data
) {
2675 deferred
= $.Deferred();
2677 this.$content
.focus();
2678 this.getReadyProcess( data
).execute().done( function () {
2679 // Force redraw by asking the browser to measure the elements' widths
2680 win
.$element
.addClass( 'oo-ui-window-ready' ).width();
2681 win
.$content
.addClass( 'oo-ui-window-content-ready' ).width();
2685 return deferred
.promise();
2691 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2694 * @param {Object} [data] Window closing data
2695 * @return {jQuery.Promise} Promise resolved when window is held
2697 OO
.ui
.Window
.prototype.hold = function ( data
) {
2699 deferred
= $.Deferred();
2701 this.getHoldProcess( data
).execute().done( function () {
2702 // Get the focused element within the window's content
2703 var $focus
= win
.$content
.find( OO
.ui
.Element
.static.getDocument( win
.$content
).activeElement
);
2705 // Blur the focused element
2706 if ( $focus
.length
) {
2710 // Force redraw by asking the browser to measure the elements' widths
2711 win
.$element
.removeClass( 'oo-ui-window-ready' ).width();
2712 win
.$content
.removeClass( 'oo-ui-window-content-ready' ).width();
2716 return deferred
.promise();
2722 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2725 * @param {Object} [data] Window closing data
2726 * @return {jQuery.Promise} Promise resolved when window is torn down
2728 OO
.ui
.Window
.prototype.teardown = function ( data
) {
2731 return this.getTeardownProcess( data
).execute()
2732 .done( function () {
2733 // Force redraw by asking the browser to measure the elements' widths
2734 win
.$element
.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2735 win
.$content
.removeClass( 'oo-ui-window-content-setup' ).width();
2736 win
.$focusTraps
.off( 'focus', win
.focusTrapHandler
);
2737 win
.toggle( false );
2742 * The Dialog class serves as the base class for the other types of dialogs.
2743 * Unless extended to include controls, the rendered dialog box is a simple window
2744 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2745 * which opens, closes, and controls the presentation of the window. See the
2746 * [OOjs UI documentation on MediaWiki] [1] for more information.
2749 * // A simple dialog window.
2750 * function MyDialog( config ) {
2751 * MyDialog.parent.call( this, config );
2753 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2754 * MyDialog.prototype.initialize = function () {
2755 * MyDialog.parent.prototype.initialize.call( this );
2756 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2757 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2758 * this.$body.append( this.content.$element );
2760 * MyDialog.prototype.getBodyHeight = function () {
2761 * return this.content.$element.outerHeight( true );
2763 * var myDialog = new MyDialog( {
2766 * // Create and append a window manager, which opens and closes the window.
2767 * var windowManager = new OO.ui.WindowManager();
2768 * $( 'body' ).append( windowManager.$element );
2769 * windowManager.addWindows( [ myDialog ] );
2770 * // Open the window!
2771 * windowManager.openWindow( myDialog );
2773 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2777 * @extends OO.ui.Window
2778 * @mixins OO.ui.mixin.PendingElement
2781 * @param {Object} [config] Configuration options
2783 OO
.ui
.Dialog
= function OoUiDialog( config
) {
2784 // Parent constructor
2785 OO
.ui
.Dialog
.parent
.call( this, config
);
2787 // Mixin constructors
2788 OO
.ui
.mixin
.PendingElement
.call( this );
2791 this.actions
= new OO
.ui
.ActionSet();
2792 this.attachedActions
= [];
2793 this.currentAction
= null;
2794 this.onDialogKeyDownHandler
= this.onDialogKeyDown
.bind( this );
2797 this.actions
.connect( this, {
2798 click
: 'onActionClick',
2799 resize
: 'onActionResize',
2800 change
: 'onActionsChange'
2805 .addClass( 'oo-ui-dialog' )
2806 .attr( 'role', 'dialog' );
2811 OO
.inheritClass( OO
.ui
.Dialog
, OO
.ui
.Window
);
2812 OO
.mixinClass( OO
.ui
.Dialog
, OO
.ui
.mixin
.PendingElement
);
2814 /* Static Properties */
2817 * Symbolic name of dialog.
2819 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2820 * Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
2822 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2827 * @property {string}
2829 OO
.ui
.Dialog
.static.name
= '';
2834 * The title can be specified as a plaintext string, a {@link OO.ui.mixin.LabelElement Label} node, or a function
2835 * that will produce a Label node or string. The title can also be specified with data passed to the
2836 * constructor (see #getSetupProcess). In this case, the static value will be overriden.
2841 * @property {jQuery|string|Function}
2843 OO
.ui
.Dialog
.static.title
= '';
2846 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2848 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2849 * value will be overriden.
2851 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
2855 * @property {Object[]}
2857 OO
.ui
.Dialog
.static.actions
= [];
2860 * Close the dialog when the 'Esc' key is pressed.
2865 * @property {boolean}
2867 OO
.ui
.Dialog
.static.escapable
= true;
2872 * Handle frame document key down events.
2875 * @param {jQuery.Event} e Key down event
2877 OO
.ui
.Dialog
.prototype.onDialogKeyDown = function ( e
) {
2878 if ( e
.which
=== OO
.ui
.Keys
.ESCAPE
) {
2881 e
.stopPropagation();
2886 * Handle action resized events.
2889 * @param {OO.ui.ActionWidget} action Action that was resized
2891 OO
.ui
.Dialog
.prototype.onActionResize = function () {
2892 // Override in subclass
2896 * Handle action click events.
2899 * @param {OO.ui.ActionWidget} action Action that was clicked
2901 OO
.ui
.Dialog
.prototype.onActionClick = function ( action
) {
2902 if ( !this.isPending() ) {
2903 this.executeAction( action
.getAction() );
2908 * Handle actions change event.
2912 OO
.ui
.Dialog
.prototype.onActionsChange = function () {
2913 this.detachActions();
2914 if ( !this.isClosing() ) {
2915 this.attachActions();
2920 * Get the set of actions used by the dialog.
2922 * @return {OO.ui.ActionSet}
2924 OO
.ui
.Dialog
.prototype.getActions = function () {
2925 return this.actions
;
2929 * Get a process for taking action.
2931 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
2932 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
2933 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
2936 * @param {string} [action] Symbolic name of action
2937 * @return {OO.ui.Process} Action process
2939 OO
.ui
.Dialog
.prototype.getActionProcess = function ( action
) {
2940 return new OO
.ui
.Process()
2941 .next( function () {
2943 // An empty action always closes the dialog without data, which should always be
2944 // safe and make no changes
2953 * @param {Object} [data] Dialog opening data
2954 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
2955 * the {@link #static-title static title}
2956 * @param {Object[]} [data.actions] List of configuration options for each
2957 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
2959 OO
.ui
.Dialog
.prototype.getSetupProcess = function ( data
) {
2963 return OO
.ui
.Dialog
.parent
.prototype.getSetupProcess
.call( this, data
)
2964 .next( function () {
2965 var config
= this.constructor.static,
2966 actions
= data
.actions
!== undefined ? data
.actions
: config
.actions
;
2968 this.title
.setLabel(
2969 data
.title
!== undefined ? data
.title
: this.constructor.static.title
2971 this.actions
.add( this.getActionWidgets( actions
) );
2973 if ( this.constructor.static.escapable
) {
2974 this.$element
.on( 'keydown', this.onDialogKeyDownHandler
);
2982 OO
.ui
.Dialog
.prototype.getTeardownProcess = function ( data
) {
2984 return OO
.ui
.Dialog
.parent
.prototype.getTeardownProcess
.call( this, data
)
2985 .first( function () {
2986 if ( this.constructor.static.escapable
) {
2987 this.$element
.off( 'keydown', this.onDialogKeyDownHandler
);
2990 this.actions
.clear();
2991 this.currentAction
= null;
2998 OO
.ui
.Dialog
.prototype.initialize = function () {
3002 OO
.ui
.Dialog
.parent
.prototype.initialize
.call( this );
3004 titleId
= OO
.ui
.generateElementId();
3007 this.title
= new OO
.ui
.LabelWidget( {
3012 this.$content
.addClass( 'oo-ui-dialog-content' );
3013 this.$element
.attr( 'aria-labelledby', titleId
);
3014 this.setPendingElement( this.$head
);
3018 * Get action widgets from a list of configs
3020 * @param {Object[]} actions Action widget configs
3021 * @return {OO.ui.ActionWidget[]} Action widgets
3023 OO
.ui
.Dialog
.prototype.getActionWidgets = function ( actions
) {
3024 var i
, len
, widgets
= [];
3025 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
3027 new OO
.ui
.ActionWidget( actions
[ i
] )
3034 * Attach action actions.
3038 OO
.ui
.Dialog
.prototype.attachActions = function () {
3039 // Remember the list of potentially attached actions
3040 this.attachedActions
= this.actions
.get();
3044 * Detach action actions.
3049 OO
.ui
.Dialog
.prototype.detachActions = function () {
3052 // Detach all actions that may have been previously attached
3053 for ( i
= 0, len
= this.attachedActions
.length
; i
< len
; i
++ ) {
3054 this.attachedActions
[ i
].$element
.detach();
3056 this.attachedActions
= [];
3060 * Execute an action.
3062 * @param {string} action Symbolic name of action to execute
3063 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
3065 OO
.ui
.Dialog
.prototype.executeAction = function ( action
) {
3067 this.currentAction
= action
;
3068 return this.getActionProcess( action
).execute()
3069 .always( this.popPending
.bind( this ) );
3073 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
3074 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
3075 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
3076 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
3077 * pertinent data and reused.
3079 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
3080 * `opened`, and `closing`, which represent the primary stages of the cycle:
3082 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
3083 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
3085 * - an `opening` event is emitted with an `opening` promise
3086 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
3087 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
3088 * window and its result executed
3089 * - a `setup` progress notification is emitted from the `opening` promise
3090 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
3091 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
3092 * window and its result executed
3093 * - a `ready` progress notification is emitted from the `opening` promise
3094 * - the `opening` promise is resolved with an `opened` promise
3096 * **Opened**: the window is now open.
3098 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
3099 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
3100 * to close the window.
3102 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
3103 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
3104 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
3105 * window and its result executed
3106 * - a `hold` progress notification is emitted from the `closing` promise
3107 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
3108 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
3109 * window and its result executed
3110 * - a `teardown` progress notification is emitted from the `closing` promise
3111 * - the `closing` promise is resolved. The window is now closed
3113 * See the [OOjs UI documentation on MediaWiki][1] for more information.
3115 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3118 * @extends OO.ui.Element
3119 * @mixins OO.EventEmitter
3122 * @param {Object} [config] Configuration options
3123 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
3124 * Note that window classes that are instantiated with a factory must have
3125 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
3126 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
3128 OO
.ui
.WindowManager
= function OoUiWindowManager( config
) {
3129 // Configuration initialization
3130 config
= config
|| {};
3132 // Parent constructor
3133 OO
.ui
.WindowManager
.parent
.call( this, config
);
3135 // Mixin constructors
3136 OO
.EventEmitter
.call( this );
3139 this.factory
= config
.factory
;
3140 this.modal
= config
.modal
=== undefined || !!config
.modal
;
3142 this.opening
= null;
3144 this.closing
= null;
3145 this.preparingToOpen
= null;
3146 this.preparingToClose
= null;
3147 this.currentWindow
= null;
3148 this.globalEvents
= false;
3149 this.$ariaHidden
= null;
3150 this.onWindowResizeTimeout
= null;
3151 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
3152 this.afterWindowResizeHandler
= this.afterWindowResize
.bind( this );
3156 .addClass( 'oo-ui-windowManager' )
3157 .toggleClass( 'oo-ui-windowManager-modal', this.modal
);
3162 OO
.inheritClass( OO
.ui
.WindowManager
, OO
.ui
.Element
);
3163 OO
.mixinClass( OO
.ui
.WindowManager
, OO
.EventEmitter
);
3168 * An 'opening' event is emitted when the window begins to be opened.
3171 * @param {OO.ui.Window} win Window that's being opened
3172 * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
3173 * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
3174 * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
3175 * @param {Object} data Window opening data
3179 * A 'closing' event is emitted when the window begins to be closed.
3182 * @param {OO.ui.Window} win Window that's being closed
3183 * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
3184 * is closed successfully. The promise emits `hold` and `teardown` notifications when those
3185 * processes are complete. When the `closing` promise is resolved, the first argument of its value
3186 * is the closing data.
3187 * @param {Object} data Window closing data
3191 * A 'resize' event is emitted when a window is resized.
3194 * @param {OO.ui.Window} win Window that was resized
3197 /* Static Properties */
3200 * Map of the symbolic name of each window size and its CSS properties.
3204 * @property {Object}
3206 OO
.ui
.WindowManager
.static.sizes
= {
3220 // These can be non-numeric because they are never used in calculations
3227 * Symbolic name of the default window size.
3229 * The default size is used if the window's requested size is not recognized.
3233 * @property {string}
3235 OO
.ui
.WindowManager
.static.defaultSize
= 'medium';
3240 * Handle window resize events.
3243 * @param {jQuery.Event} e Window resize event
3245 OO
.ui
.WindowManager
.prototype.onWindowResize = function () {
3246 clearTimeout( this.onWindowResizeTimeout
);
3247 this.onWindowResizeTimeout
= setTimeout( this.afterWindowResizeHandler
, 200 );
3251 * Handle window resize events.
3254 * @param {jQuery.Event} e Window resize event
3256 OO
.ui
.WindowManager
.prototype.afterWindowResize = function () {
3257 if ( this.currentWindow
) {
3258 this.updateWindowSize( this.currentWindow
);
3263 * Check if window is opening.
3265 * @return {boolean} Window is opening
3267 OO
.ui
.WindowManager
.prototype.isOpening = function ( win
) {
3268 return win
=== this.currentWindow
&& !!this.opening
&& this.opening
.state() === 'pending';
3272 * Check if window is closing.
3274 * @return {boolean} Window is closing
3276 OO
.ui
.WindowManager
.prototype.isClosing = function ( win
) {
3277 return win
=== this.currentWindow
&& !!this.closing
&& this.closing
.state() === 'pending';
3281 * Check if window is opened.
3283 * @return {boolean} Window is opened
3285 OO
.ui
.WindowManager
.prototype.isOpened = function ( win
) {
3286 return win
=== this.currentWindow
&& !!this.opened
&& this.opened
.state() === 'pending';
3290 * Check if a window is being managed.
3292 * @param {OO.ui.Window} win Window to check
3293 * @return {boolean} Window is being managed
3295 OO
.ui
.WindowManager
.prototype.hasWindow = function ( win
) {
3298 for ( name
in this.windows
) {
3299 if ( this.windows
[ name
] === win
) {
3308 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
3310 * @param {OO.ui.Window} win Window being opened
3311 * @param {Object} [data] Window opening data
3312 * @return {number} Milliseconds to wait
3314 OO
.ui
.WindowManager
.prototype.getSetupDelay = function () {
3319 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
3321 * @param {OO.ui.Window} win Window being opened
3322 * @param {Object} [data] Window opening data
3323 * @return {number} Milliseconds to wait
3325 OO
.ui
.WindowManager
.prototype.getReadyDelay = function () {
3330 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
3332 * @param {OO.ui.Window} win Window being closed
3333 * @param {Object} [data] Window closing data
3334 * @return {number} Milliseconds to wait
3336 OO
.ui
.WindowManager
.prototype.getHoldDelay = function () {
3341 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
3342 * executing the ‘teardown’ process.
3344 * @param {OO.ui.Window} win Window being closed
3345 * @param {Object} [data] Window closing data
3346 * @return {number} Milliseconds to wait
3348 OO
.ui
.WindowManager
.prototype.getTeardownDelay = function () {
3349 return this.modal
? 250 : 0;
3353 * Get a window by its symbolic name.
3355 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
3356 * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
3357 * for more information about using factories.
3358 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3360 * @param {string} name Symbolic name of the window
3361 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
3362 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
3363 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
3365 OO
.ui
.WindowManager
.prototype.getWindow = function ( name
) {
3366 var deferred
= $.Deferred(),
3367 win
= this.windows
[ name
];
3369 if ( !( win
instanceof OO
.ui
.Window
) ) {
3370 if ( this.factory
) {
3371 if ( !this.factory
.lookup( name
) ) {
3372 deferred
.reject( new OO
.ui
.Error(
3373 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
3376 win
= this.factory
.create( name
);
3377 this.addWindows( [ win
] );
3378 deferred
.resolve( win
);
3381 deferred
.reject( new OO
.ui
.Error(
3382 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
3386 deferred
.resolve( win
);
3389 return deferred
.promise();
3393 * Get current window.
3395 * @return {OO.ui.Window|null} Currently opening/opened/closing window
3397 OO
.ui
.WindowManager
.prototype.getCurrentWindow = function () {
3398 return this.currentWindow
;
3404 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
3405 * @param {Object} [data] Window opening data
3406 * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
3407 * See {@link #event-opening 'opening' event} for more information about `opening` promises.
3410 OO
.ui
.WindowManager
.prototype.openWindow = function ( win
, data
) {
3412 opening
= $.Deferred();
3414 // Argument handling
3415 if ( typeof win
=== 'string' ) {
3416 return this.getWindow( win
).then( function ( win
) {
3417 return manager
.openWindow( win
, data
);
3422 if ( !this.hasWindow( win
) ) {
3423 opening
.reject( new OO
.ui
.Error(
3424 'Cannot open window: window is not attached to manager'
3426 } else if ( this.preparingToOpen
|| this.opening
|| this.opened
) {
3427 opening
.reject( new OO
.ui
.Error(
3428 'Cannot open window: another window is opening or open'
3433 if ( opening
.state() !== 'rejected' ) {
3434 // If a window is currently closing, wait for it to complete
3435 this.preparingToOpen
= $.when( this.closing
);
3436 // Ensure handlers get called after preparingToOpen is set
3437 this.preparingToOpen
.done( function () {
3438 if ( manager
.modal
) {
3439 manager
.toggleGlobalEvents( true );
3440 manager
.toggleAriaIsolation( true );
3442 manager
.currentWindow
= win
;
3443 manager
.opening
= opening
;
3444 manager
.preparingToOpen
= null;
3445 manager
.emit( 'opening', win
, opening
, data
);
3446 setTimeout( function () {
3447 win
.setup( data
).then( function () {
3448 manager
.updateWindowSize( win
);
3449 manager
.opening
.notify( { state
: 'setup' } );
3450 setTimeout( function () {
3451 win
.ready( data
).then( function () {
3452 manager
.opening
.notify( { state
: 'ready' } );
3453 manager
.opening
= null;
3454 manager
.opened
= $.Deferred();
3455 opening
.resolve( manager
.opened
.promise(), data
);
3457 }, manager
.getReadyDelay() );
3459 }, manager
.getSetupDelay() );
3463 return opening
.promise();
3469 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3470 * @param {Object} [data] Window closing data
3471 * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
3472 * See {@link #event-closing 'closing' event} for more information about closing promises.
3473 * @throws {Error} An error is thrown if the window is not managed by the window manager.
3476 OO
.ui
.WindowManager
.prototype.closeWindow = function ( win
, data
) {
3478 closing
= $.Deferred(),
3481 // Argument handling
3482 if ( typeof win
=== 'string' ) {
3483 win
= this.windows
[ win
];
3484 } else if ( !this.hasWindow( win
) ) {
3490 closing
.reject( new OO
.ui
.Error(
3491 'Cannot close window: window is not attached to manager'
3493 } else if ( win
!== this.currentWindow
) {
3494 closing
.reject( new OO
.ui
.Error(
3495 'Cannot close window: window already closed with different data'
3497 } else if ( this.preparingToClose
|| this.closing
) {
3498 closing
.reject( new OO
.ui
.Error(
3499 'Cannot close window: window already closing with different data'
3504 if ( closing
.state() !== 'rejected' ) {
3505 // If the window is currently opening, close it when it's done
3506 this.preparingToClose
= $.when( this.opening
);
3507 // Ensure handlers get called after preparingToClose is set
3508 this.preparingToClose
.done( function () {
3509 manager
.closing
= closing
;
3510 manager
.preparingToClose
= null;
3511 manager
.emit( 'closing', win
, closing
, data
);
3512 opened
= manager
.opened
;
3513 manager
.opened
= null;
3514 opened
.resolve( closing
.promise(), data
);
3515 setTimeout( function () {
3516 win
.hold( data
).then( function () {
3517 closing
.notify( { state
: 'hold' } );
3518 setTimeout( function () {
3519 win
.teardown( data
).then( function () {
3520 closing
.notify( { state
: 'teardown' } );
3521 if ( manager
.modal
) {
3522 manager
.toggleGlobalEvents( false );
3523 manager
.toggleAriaIsolation( false );
3525 manager
.closing
= null;
3526 manager
.currentWindow
= null;
3527 closing
.resolve( data
);
3529 }, manager
.getTeardownDelay() );
3531 }, manager
.getHoldDelay() );
3535 return closing
.promise();
3539 * Add windows to the window manager.
3541 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
3542 * See the [OOjs ui documentation on MediaWiki] [2] for examples.
3543 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3545 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
3546 * by reference, symbolic name, or explicitly defined symbolic names.
3547 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
3548 * explicit nor a statically configured symbolic name.
3550 OO
.ui
.WindowManager
.prototype.addWindows = function ( windows
) {
3551 var i
, len
, win
, name
, list
;
3553 if ( Array
.isArray( windows
) ) {
3554 // Convert to map of windows by looking up symbolic names from static configuration
3556 for ( i
= 0, len
= windows
.length
; i
< len
; i
++ ) {
3557 name
= windows
[ i
].constructor.static.name
;
3558 if ( typeof name
!== 'string' ) {
3559 throw new Error( 'Cannot add window' );
3561 list
[ name
] = windows
[ i
];
3563 } else if ( OO
.isPlainObject( windows
) ) {
3568 for ( name
in list
) {
3570 this.windows
[ name
] = win
.toggle( false );
3571 this.$element
.append( win
.$element
);
3572 win
.setManager( this );
3577 * Remove the specified windows from the windows manager.
3579 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
3580 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
3581 * longer listens to events, use the #destroy method.
3583 * @param {string[]} names Symbolic names of windows to remove
3584 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3585 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
3587 OO
.ui
.WindowManager
.prototype.removeWindows = function ( names
) {
3588 var i
, len
, win
, name
, cleanupWindow
,
3591 cleanup = function ( name
, win
) {
3592 delete manager
.windows
[ name
];
3593 win
.$element
.detach();
3596 for ( i
= 0, len
= names
.length
; i
< len
; i
++ ) {
3598 win
= this.windows
[ name
];
3600 throw new Error( 'Cannot remove window' );
3602 cleanupWindow
= cleanup
.bind( null, name
, win
);
3603 promises
.push( this.closeWindow( name
).then( cleanupWindow
, cleanupWindow
) );
3606 return $.when
.apply( $, promises
);
3610 * Remove all windows from the window manager.
3612 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
3613 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
3614 * To remove just a subset of windows, use the #removeWindows method.
3616 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3618 OO
.ui
.WindowManager
.prototype.clearWindows = function () {
3619 return this.removeWindows( Object
.keys( this.windows
) );
3623 * Set dialog size. In general, this method should not be called directly.
3625 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3629 OO
.ui
.WindowManager
.prototype.updateWindowSize = function ( win
) {
3632 // Bypass for non-current, and thus invisible, windows
3633 if ( win
!== this.currentWindow
) {
3637 isFullscreen
= win
.getSize() === 'full';
3639 this.$element
.toggleClass( 'oo-ui-windowManager-fullscreen', isFullscreen
);
3640 this.$element
.toggleClass( 'oo-ui-windowManager-floating', !isFullscreen
);
3641 win
.setDimensions( win
.getSizeProperties() );
3643 this.emit( 'resize', win
);
3649 * Bind or unbind global events for scrolling.
3652 * @param {boolean} [on] Bind global events
3655 OO
.ui
.WindowManager
.prototype.toggleGlobalEvents = function ( on
) {
3656 var scrollWidth
, bodyMargin
,
3657 $body
= $( this.getElementDocument().body
),
3658 // We could have multiple window managers open so only modify
3659 // the body css at the bottom of the stack
3660 stackDepth
= $body
.data( 'windowManagerGlobalEvents' ) || 0 ;
3662 on
= on
=== undefined ? !!this.globalEvents
: !!on
;
3665 if ( !this.globalEvents
) {
3666 $( this.getElementWindow() ).on( {
3667 // Start listening for top-level window dimension changes
3668 'orientationchange resize': this.onWindowResizeHandler
3670 if ( stackDepth
=== 0 ) {
3671 scrollWidth
= window
.innerWidth
- document
.documentElement
.clientWidth
;
3672 bodyMargin
= parseFloat( $body
.css( 'margin-right' ) ) || 0;
3675 'margin-right': bodyMargin
+ scrollWidth
3679 this.globalEvents
= true;
3681 } else if ( this.globalEvents
) {
3682 $( this.getElementWindow() ).off( {
3683 // Stop listening for top-level window dimension changes
3684 'orientationchange resize': this.onWindowResizeHandler
3687 if ( stackDepth
=== 0 ) {
3693 this.globalEvents
= false;
3695 $body
.data( 'windowManagerGlobalEvents', stackDepth
);
3701 * Toggle screen reader visibility of content other than the window manager.
3704 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3707 OO
.ui
.WindowManager
.prototype.toggleAriaIsolation = function ( isolate
) {
3708 isolate
= isolate
=== undefined ? !this.$ariaHidden
: !!isolate
;
3711 if ( !this.$ariaHidden
) {
3712 // Hide everything other than the window manager from screen readers
3713 this.$ariaHidden
= $( 'body' )
3715 .not( this.$element
.parentsUntil( 'body' ).last() )
3716 .attr( 'aria-hidden', '' );
3718 } else if ( this.$ariaHidden
) {
3719 // Restore screen reader visibility
3720 this.$ariaHidden
.removeAttr( 'aria-hidden' );
3721 this.$ariaHidden
= null;
3728 * Destroy the window manager.
3730 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
3731 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
3734 OO
.ui
.WindowManager
.prototype.destroy = function () {
3735 this.toggleGlobalEvents( false );
3736 this.toggleAriaIsolation( false );
3737 this.clearWindows();
3738 this.$element
.remove();
3742 * Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong
3743 * in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the
3744 * appearance and functionality of the error interface.
3746 * The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error
3747 * is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget
3748 * that initiated the failed process will be disabled.
3750 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the
3753 * For an example of error interfaces, please see the [OOjs UI documentation on MediaWiki][1].
3755 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Processes_and_errors
3760 * @param {string|jQuery} message Description of error
3761 * @param {Object} [config] Configuration options
3762 * @cfg {boolean} [recoverable=true] Error is recoverable.
3763 * By default, errors are recoverable, and users can try the process again.
3764 * @cfg {boolean} [warning=false] Error is a warning.
3765 * If the error is a warning, the error interface will include a
3766 * 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning
3767 * is not triggered a second time if the user chooses to continue.
3769 OO
.ui
.Error
= function OoUiError( message
, config
) {
3770 // Allow passing positional parameters inside the config object
3771 if ( OO
.isPlainObject( message
) && config
=== undefined ) {
3773 message
= config
.message
;
3776 // Configuration initialization
3777 config
= config
|| {};
3780 this.message
= message
instanceof jQuery
? message
: String( message
);
3781 this.recoverable
= config
.recoverable
=== undefined || !!config
.recoverable
;
3782 this.warning
= !!config
.warning
;
3787 OO
.initClass( OO
.ui
.Error
);
3792 * Check if the error is recoverable.
3794 * If the error is recoverable, users are able to try the process again.
3796 * @return {boolean} Error is recoverable
3798 OO
.ui
.Error
.prototype.isRecoverable = function () {
3799 return this.recoverable
;
3803 * Check if the error is a warning.
3805 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
3807 * @return {boolean} Error is warning
3809 OO
.ui
.Error
.prototype.isWarning = function () {
3810 return this.warning
;
3814 * Get error message as DOM nodes.
3816 * @return {jQuery} Error message in DOM nodes
3818 OO
.ui
.Error
.prototype.getMessage = function () {
3819 return this.message
instanceof jQuery
?
3820 this.message
.clone() :
3821 $( '<div>' ).text( this.message
).contents();
3825 * Get the error message text.
3827 * @return {string} Error message
3829 OO
.ui
.Error
.prototype.getMessageText = function () {
3830 return this.message
instanceof jQuery
? this.message
.text() : this.message
;
3834 * Wraps an HTML snippet for use with configuration values which default
3835 * to strings. This bypasses the default html-escaping done to string
3841 * @param {string} [content] HTML content
3843 OO
.ui
.HtmlSnippet
= function OoUiHtmlSnippet( content
) {
3845 this.content
= content
;
3850 OO
.initClass( OO
.ui
.HtmlSnippet
);
3857 * @return {string} Unchanged HTML snippet.
3859 OO
.ui
.HtmlSnippet
.prototype.toString = function () {
3860 return this.content
;
3864 * A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
3867 * - **number**: the process will wait for the specified number of milliseconds before proceeding.
3868 * - **promise**: the process will continue to the next step when the promise is successfully resolved
3869 * or stop if the promise is rejected.
3870 * - **function**: the process will execute the function. The process will stop if the function returns
3871 * either a boolean `false` or a promise that is rejected; if the function returns a number, the process
3872 * will wait for that number of milliseconds before proceeding.
3874 * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
3875 * configured, users can dismiss the error and try the process again, or not. If a process is stopped,
3876 * its remaining steps will not be performed.
3881 * @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
3882 * that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
3883 * @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
3884 * a number or promise.
3885 * @return {Object} Step object, with `callback` and `context` properties
3887 OO
.ui
.Process = function ( step
, context
) {
3892 if ( step
!== undefined ) {
3893 this.next( step
, context
);
3899 OO
.initClass( OO
.ui
.Process
);
3904 * Start the process.
3906 * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
3907 * If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
3908 * and any remaining steps are not performed.
3910 OO
.ui
.Process
.prototype.execute = function () {
3911 var i
, len
, promise
;
3914 * Continue execution.
3917 * @param {Array} step A function and the context it should be called in
3918 * @return {Function} Function that continues the process
3920 function proceed( step
) {
3921 return function () {
3922 // Execute step in the correct context
3924 result
= step
.callback
.call( step
.context
);
3926 if ( result
=== false ) {
3927 // Use rejected promise for boolean false results
3928 return $.Deferred().reject( [] ).promise();
3930 if ( typeof result
=== 'number' ) {
3932 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3934 // Use a delayed promise for numbers, expecting them to be in milliseconds
3935 deferred
= $.Deferred();
3936 setTimeout( deferred
.resolve
, result
);
3937 return deferred
.promise();
3939 if ( result
instanceof OO
.ui
.Error
) {
3940 // Use rejected promise for error
3941 return $.Deferred().reject( [ result
] ).promise();
3943 if ( Array
.isArray( result
) && result
.length
&& result
[ 0 ] instanceof OO
.ui
.Error
) {
3944 // Use rejected promise for list of errors
3945 return $.Deferred().reject( result
).promise();
3947 // Duck-type the object to see if it can produce a promise
3948 if ( result
&& $.isFunction( result
.promise
) ) {
3949 // Use a promise generated from the result
3950 return result
.promise();
3952 // Use resolved promise for other results
3953 return $.Deferred().resolve().promise();
3957 if ( this.steps
.length
) {
3958 // Generate a chain reaction of promises
3959 promise
= proceed( this.steps
[ 0 ] )();
3960 for ( i
= 1, len
= this.steps
.length
; i
< len
; i
++ ) {
3961 promise
= promise
.then( proceed( this.steps
[ i
] ) );
3964 promise
= $.Deferred().resolve().promise();
3971 * Create a process step.
3974 * @param {number|jQuery.Promise|Function} step
3976 * - Number of milliseconds to wait before proceeding
3977 * - Promise that must be resolved before proceeding
3978 * - Function to execute
3979 * - If the function returns a boolean false the process will stop
3980 * - If the function returns a promise, the process will continue to the next
3981 * step when the promise is resolved or stop if the promise is rejected
3982 * - If the function returns a number, the process will wait for that number of
3983 * milliseconds before proceeding
3984 * @param {Object} [context=null] Execution context of the function. The context is
3985 * ignored if the step is a number or promise.
3986 * @return {Object} Step object, with `callback` and `context` properties
3988 OO
.ui
.Process
.prototype.createStep = function ( step
, context
) {
3989 if ( typeof step
=== 'number' || $.isFunction( step
.promise
) ) {
3991 callback: function () {
3997 if ( $.isFunction( step
) ) {
4003 throw new Error( 'Cannot create process step: number, promise or function expected' );
4007 * Add step to the beginning of the process.
4009 * @inheritdoc #createStep
4010 * @return {OO.ui.Process} this
4013 OO
.ui
.Process
.prototype.first = function ( step
, context
) {
4014 this.steps
.unshift( this.createStep( step
, context
) );
4019 * Add step to the end of the process.
4021 * @inheritdoc #createStep
4022 * @return {OO.ui.Process} this
4025 OO
.ui
.Process
.prototype.next = function ( step
, context
) {
4026 this.steps
.push( this.createStep( step
, context
) );
4031 * A ToolFactory creates tools on demand. All tools ({@link OO.ui.Tool Tools}, {@link OO.ui.PopupTool PopupTools},
4032 * and {@link OO.ui.ToolGroupTool ToolGroupTools}) must be registered with a tool factory. Tools are
4033 * registered by their symbolic name. See {@link OO.ui.Toolbar toolbars} for an example.
4035 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4037 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4040 * @extends OO.Factory
4043 OO
.ui
.ToolFactory
= function OoUiToolFactory() {
4044 // Parent constructor
4045 OO
.ui
.ToolFactory
.parent
.call( this );
4050 OO
.inheritClass( OO
.ui
.ToolFactory
, OO
.Factory
);
4055 * Get tools from the factory
4057 * @param {Array} include Included tools
4058 * @param {Array} exclude Excluded tools
4059 * @param {Array} promote Promoted tools
4060 * @param {Array} demote Demoted tools
4061 * @return {string[]} List of tools
4063 OO
.ui
.ToolFactory
.prototype.getTools = function ( include
, exclude
, promote
, demote
) {
4064 var i
, len
, included
, promoted
, demoted
,
4068 // Collect included and not excluded tools
4069 included
= OO
.simpleArrayDifference( this.extract( include
), this.extract( exclude
) );
4072 promoted
= this.extract( promote
, used
);
4073 demoted
= this.extract( demote
, used
);
4076 for ( i
= 0, len
= included
.length
; i
< len
; i
++ ) {
4077 if ( !used
[ included
[ i
] ] ) {
4078 auto
.push( included
[ i
] );
4082 return promoted
.concat( auto
).concat( demoted
);
4086 * Get a flat list of names from a list of names or groups.
4088 * Tools can be specified in the following ways:
4090 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
4091 * - All tools in a group: `{ group: 'group-name' }`
4092 * - All tools: `'*'`
4095 * @param {Array|string} collection List of tools
4096 * @param {Object} [used] Object with names that should be skipped as properties; extracted
4097 * names will be added as properties
4098 * @return {string[]} List of extracted names
4100 OO
.ui
.ToolFactory
.prototype.extract = function ( collection
, used
) {
4101 var i
, len
, item
, name
, tool
,
4104 if ( collection
=== '*' ) {
4105 for ( name
in this.registry
) {
4106 tool
= this.registry
[ name
];
4108 // Only add tools by group name when auto-add is enabled
4109 tool
.static.autoAddToCatchall
&&
4110 // Exclude already used tools
4111 ( !used
|| !used
[ name
] )
4115 used
[ name
] = true;
4119 } else if ( Array
.isArray( collection
) ) {
4120 for ( i
= 0, len
= collection
.length
; i
< len
; i
++ ) {
4121 item
= collection
[ i
];
4122 // Allow plain strings as shorthand for named tools
4123 if ( typeof item
=== 'string' ) {
4124 item
= { name
: item
};
4126 if ( OO
.isPlainObject( item
) ) {
4128 for ( name
in this.registry
) {
4129 tool
= this.registry
[ name
];
4131 // Include tools with matching group
4132 tool
.static.group
=== item
.group
&&
4133 // Only add tools by group name when auto-add is enabled
4134 tool
.static.autoAddToGroup
&&
4135 // Exclude already used tools
4136 ( !used
|| !used
[ name
] )
4140 used
[ name
] = true;
4144 // Include tools with matching name and exclude already used tools
4145 } else if ( item
.name
&& ( !used
|| !used
[ item
.name
] ) ) {
4146 names
.push( item
.name
);
4148 used
[ item
.name
] = true;
4158 * ToolGroupFactories create {@link OO.ui.ToolGroup toolgroups} on demand. The toolgroup classes must
4159 * specify a symbolic name and be registered with the factory. The following classes are registered by
4162 * - {@link OO.ui.BarToolGroup BarToolGroups} (‘bar’)
4163 * - {@link OO.ui.MenuToolGroup MenuToolGroups} (‘menu’)
4164 * - {@link OO.ui.ListToolGroup ListToolGroups} (‘list’)
4166 * See {@link OO.ui.Toolbar toolbars} for an example.
4168 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
4170 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
4172 * @extends OO.Factory
4175 OO
.ui
.ToolGroupFactory
= function OoUiToolGroupFactory() {
4176 var i
, l
, defaultClasses
;
4177 // Parent constructor
4178 OO
.Factory
.call( this );
4180 defaultClasses
= this.constructor.static.getDefaultClasses();
4182 // Register default toolgroups
4183 for ( i
= 0, l
= defaultClasses
.length
; i
< l
; i
++ ) {
4184 this.register( defaultClasses
[ i
] );
4190 OO
.inheritClass( OO
.ui
.ToolGroupFactory
, OO
.Factory
);
4192 /* Static Methods */
4195 * Get a default set of classes to be registered on construction.
4197 * @return {Function[]} Default classes
4199 OO
.ui
.ToolGroupFactory
.static.getDefaultClasses = function () {
4202 OO
.ui
.ListToolGroup
,
4214 * @param {Object} [config] Configuration options
4216 OO
.ui
.Theme
= function OoUiTheme( config
) {
4217 // Configuration initialization
4218 config
= config
|| {};
4223 OO
.initClass( OO
.ui
.Theme
);
4228 * Get a list of classes to be applied to a widget.
4230 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
4231 * otherwise state transitions will not work properly.
4233 * @param {OO.ui.Element} element Element for which to get classes
4234 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4236 OO
.ui
.Theme
.prototype.getElementClasses = function ( /* element */ ) {
4237 return { on
: [], off
: [] };
4241 * Update CSS classes provided by the theme.
4243 * For elements with theme logic hooks, this should be called any time there's a state change.
4245 * @param {OO.ui.Element} element Element for which to update classes
4246 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
4248 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
4249 var $elements
= $( [] ),
4250 classes
= this.getElementClasses( element
);
4252 if ( element
.$icon
) {
4253 $elements
= $elements
.add( element
.$icon
);
4255 if ( element
.$indicator
) {
4256 $elements
= $elements
.add( element
.$indicator
);
4260 .removeClass( classes
.off
.join( ' ' ) )
4261 .addClass( classes
.on
.join( ' ' ) );
4265 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
4266 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
4267 * order in which users will navigate through the focusable elements via the "tab" key.
4270 * // TabIndexedElement is mixed into the ButtonWidget class
4271 * // to provide a tabIndex property.
4272 * var button1 = new OO.ui.ButtonWidget( {
4276 * var button2 = new OO.ui.ButtonWidget( {
4280 * var button3 = new OO.ui.ButtonWidget( {
4284 * var button4 = new OO.ui.ButtonWidget( {
4288 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
4294 * @param {Object} [config] Configuration options
4295 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
4296 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
4297 * functionality will be applied to it instead.
4298 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
4299 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
4300 * to remove the element from the tab-navigation flow.
4302 OO
.ui
.mixin
.TabIndexedElement
= function OoUiMixinTabIndexedElement( config
) {
4303 // Configuration initialization
4304 config
= $.extend( { tabIndex
: 0 }, config
);
4307 this.$tabIndexed
= null;
4308 this.tabIndex
= null;
4311 this.connect( this, { disable
: 'onTabIndexedElementDisable' } );
4314 this.setTabIndex( config
.tabIndex
);
4315 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
4320 OO
.initClass( OO
.ui
.mixin
.TabIndexedElement
);
4325 * Set the element that should use the tabindex functionality.
4327 * This method is used to retarget a tabindex mixin so that its functionality applies
4328 * to the specified element. If an element is currently using the functionality, the mixin’s
4329 * effect on that element is removed before the new element is set up.
4331 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
4334 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
4335 var tabIndex
= this.tabIndex
;
4336 // Remove attributes from old $tabIndexed
4337 this.setTabIndex( null );
4338 // Force update of new $tabIndexed
4339 this.$tabIndexed
= $tabIndexed
;
4340 this.tabIndex
= tabIndex
;
4341 return this.updateTabIndex();
4345 * Set the value of the tabindex.
4347 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
4350 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
4351 tabIndex
= typeof tabIndex
=== 'number' ? tabIndex
: null;
4353 if ( this.tabIndex
!== tabIndex
) {
4354 this.tabIndex
= tabIndex
;
4355 this.updateTabIndex();
4362 * Update the `tabindex` attribute, in case of changes to tab index or
4368 OO
.ui
.mixin
.TabIndexedElement
.prototype.updateTabIndex = function () {
4369 if ( this.$tabIndexed
) {
4370 if ( this.tabIndex
!== null ) {
4371 // Do not index over disabled elements
4372 this.$tabIndexed
.attr( {
4373 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
4374 // Support: ChromeVox and NVDA
4375 // These do not seem to inherit aria-disabled from parent elements
4376 'aria-disabled': this.isDisabled().toString()
4379 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
4386 * Handle disable events.
4389 * @param {boolean} disabled Element is disabled
4391 OO
.ui
.mixin
.TabIndexedElement
.prototype.onTabIndexedElementDisable = function () {
4392 this.updateTabIndex();
4396 * Get the value of the tabindex.
4398 * @return {number|null} Tabindex value
4400 OO
.ui
.mixin
.TabIndexedElement
.prototype.getTabIndex = function () {
4401 return this.tabIndex
;
4405 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
4406 * interface element that can be configured with access keys for accessibility.
4407 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
4409 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
4414 * @param {Object} [config] Configuration options
4415 * @cfg {jQuery} [$button] The button element created by the class.
4416 * If this configuration is omitted, the button element will use a generated `<a>`.
4417 * @cfg {boolean} [framed=true] Render the button with a frame
4419 OO
.ui
.mixin
.ButtonElement
= function OoUiMixinButtonElement( config
) {
4420 // Configuration initialization
4421 config
= config
|| {};
4424 this.$button
= null;
4426 this.active
= false;
4427 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
4428 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
4429 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
4430 this.onKeyUpHandler
= this.onKeyUp
.bind( this );
4431 this.onClickHandler
= this.onClick
.bind( this );
4432 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
4435 this.$element
.addClass( 'oo-ui-buttonElement' );
4436 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
4437 this.setButtonElement( config
.$button
|| $( '<a>' ) );
4442 OO
.initClass( OO
.ui
.mixin
.ButtonElement
);
4444 /* Static Properties */
4447 * Cancel mouse down events.
4449 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
4450 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
4451 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
4456 * @property {boolean}
4458 OO
.ui
.mixin
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
4463 * A 'click' event is emitted when the button element is clicked.
4471 * Set the button element.
4473 * This method is used to retarget a button mixin so that its functionality applies to
4474 * the specified button element instead of the one created by the class. If a button element
4475 * is already set, the method will remove the mixin’s effect on that element.
4477 * @param {jQuery} $button Element to use as button
4479 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
4480 if ( this.$button
) {
4482 .removeClass( 'oo-ui-buttonElement-button' )
4483 .removeAttr( 'role accesskey' )
4485 mousedown
: this.onMouseDownHandler
,
4486 keydown
: this.onKeyDownHandler
,
4487 click
: this.onClickHandler
,
4488 keypress
: this.onKeyPressHandler
4492 this.$button
= $button
4493 .addClass( 'oo-ui-buttonElement-button' )
4494 .attr( { role
: 'button' } )
4496 mousedown
: this.onMouseDownHandler
,
4497 keydown
: this.onKeyDownHandler
,
4498 click
: this.onClickHandler
,
4499 keypress
: this.onKeyPressHandler
4504 * Handles mouse down events.
4507 * @param {jQuery.Event} e Mouse down event
4509 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown = function ( e
) {
4510 if ( this.isDisabled() || e
.which
!== 1 ) {
4513 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
4514 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4515 // reliably remove the pressed class
4516 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler
);
4517 // Prevent change of focus unless specifically configured otherwise
4518 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
4524 * Handles mouse up events.
4527 * @param {jQuery.Event} e Mouse up event
4529 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp = function ( e
) {
4530 if ( this.isDisabled() || e
.which
!== 1 ) {
4533 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
4534 // Stop listening for mouseup, since we only needed this once
4535 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onMouseUpHandler
);
4539 * Handles mouse click events.
4542 * @param {jQuery.Event} e Mouse click event
4545 OO
.ui
.mixin
.ButtonElement
.prototype.onClick = function ( e
) {
4546 if ( !this.isDisabled() && e
.which
=== 1 ) {
4547 if ( this.emit( 'click' ) ) {
4554 * Handles key down events.
4557 * @param {jQuery.Event} e Key down event
4559 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyDown = function ( e
) {
4560 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
4563 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
4564 // Run the keyup handler no matter where the key is when the button is let go, so we can
4565 // reliably remove the pressed class
4566 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler
);
4570 * Handles key up events.
4573 * @param {jQuery.Event} e Key up event
4575 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyUp = function ( e
) {
4576 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
4579 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
4580 // Stop listening for keyup, since we only needed this once
4581 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onKeyUpHandler
);
4585 * Handles key press events.
4588 * @param {jQuery.Event} e Key press event
4591 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyPress = function ( e
) {
4592 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
4593 if ( this.emit( 'click' ) ) {
4600 * Check if button has a frame.
4602 * @return {boolean} Button is framed
4604 OO
.ui
.mixin
.ButtonElement
.prototype.isFramed = function () {
4609 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
4611 * @param {boolean} [framed] Make button framed, omit to toggle
4614 OO
.ui
.mixin
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
4615 framed
= framed
=== undefined ? !this.framed
: !!framed
;
4616 if ( framed
!== this.framed
) {
4617 this.framed
= framed
;
4619 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
4620 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
4621 this.updateThemeClasses();
4628 * Set the button to its 'active' state.
4630 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
4631 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
4632 * for other button types.
4634 * @param {boolean} [value] Make button active
4637 OO
.ui
.mixin
.ButtonElement
.prototype.setActive = function ( value
) {
4638 this.$element
.toggleClass( 'oo-ui-buttonElement-active', !!value
);
4643 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4644 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4645 * items from the group is done through the interface the class provides.
4646 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4648 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4654 * @param {Object} [config] Configuration options
4655 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4656 * is omitted, the group element will use a generated `<div>`.
4658 OO
.ui
.mixin
.GroupElement
= function OoUiMixinGroupElement( config
) {
4659 // Configuration initialization
4660 config
= config
|| {};
4665 this.aggregateItemEvents
= {};
4668 this.setGroupElement( config
.$group
|| $( '<div>' ) );
4674 * Set the group element.
4676 * If an element is already set, items will be moved to the new element.
4678 * @param {jQuery} $group Element to use as group
4680 OO
.ui
.mixin
.GroupElement
.prototype.setGroupElement = function ( $group
) {
4683 this.$group
= $group
;
4684 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4685 this.$group
.append( this.items
[ i
].$element
);
4690 * Check if a group contains no items.
4692 * @return {boolean} Group is empty
4694 OO
.ui
.mixin
.GroupElement
.prototype.isEmpty = function () {
4695 return !this.items
.length
;
4699 * Get all items in the group.
4701 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4702 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4705 * @return {OO.ui.Element[]} An array of items.
4707 OO
.ui
.mixin
.GroupElement
.prototype.getItems = function () {
4708 return this.items
.slice( 0 );
4712 * Get an item by its data.
4714 * Only the first item with matching data will be returned. To return all matching items,
4715 * use the #getItemsFromData method.
4717 * @param {Object} data Item data to search for
4718 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4720 OO
.ui
.mixin
.GroupElement
.prototype.getItemFromData = function ( data
) {
4722 hash
= OO
.getHash( data
);
4724 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4725 item
= this.items
[ i
];
4726 if ( hash
=== OO
.getHash( item
.getData() ) ) {
4735 * Get items by their data.
4737 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4739 * @param {Object} data Item data to search for
4740 * @return {OO.ui.Element[]} Items with equivalent data
4742 OO
.ui
.mixin
.GroupElement
.prototype.getItemsFromData = function ( data
) {
4744 hash
= OO
.getHash( data
),
4747 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4748 item
= this.items
[ i
];
4749 if ( hash
=== OO
.getHash( item
.getData() ) ) {
4758 * Aggregate the events emitted by the group.
4760 * When events are aggregated, the group will listen to all contained items for the event,
4761 * and then emit the event under a new name. The new event will contain an additional leading
4762 * parameter containing the item that emitted the original event. Other arguments emitted from
4763 * the original event are passed through.
4765 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
4766 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
4767 * A `null` value will remove aggregated events.
4769 * @throws {Error} An error is thrown if aggregation already exists.
4771 OO
.ui
.mixin
.GroupElement
.prototype.aggregate = function ( events
) {
4772 var i
, len
, item
, add
, remove
, itemEvent
, groupEvent
;
4774 for ( itemEvent
in events
) {
4775 groupEvent
= events
[ itemEvent
];
4777 // Remove existing aggregated event
4778 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4779 // Don't allow duplicate aggregations
4781 throw new Error( 'Duplicate item event aggregation for ' + itemEvent
);
4783 // Remove event aggregation from existing items
4784 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4785 item
= this.items
[ i
];
4786 if ( item
.connect
&& item
.disconnect
) {
4788 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4789 item
.disconnect( this, remove
);
4792 // Prevent future items from aggregating event
4793 delete this.aggregateItemEvents
[ itemEvent
];
4796 // Add new aggregate event
4798 // Make future items aggregate event
4799 this.aggregateItemEvents
[ itemEvent
] = groupEvent
;
4800 // Add event aggregation to existing items
4801 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4802 item
= this.items
[ i
];
4803 if ( item
.connect
&& item
.disconnect
) {
4805 add
[ itemEvent
] = [ 'emit', groupEvent
, item
];
4806 item
.connect( this, add
);
4814 * Add items to the group.
4816 * Items will be added to the end of the group array unless the optional `index` parameter specifies
4817 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
4819 * @param {OO.ui.Element[]} items An array of items to add to the group
4820 * @param {number} [index] Index of the insertion point
4823 OO
.ui
.mixin
.GroupElement
.prototype.addItems = function ( items
, index
) {
4824 var i
, len
, item
, event
, events
, currentIndex
,
4827 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
4830 // Check if item exists then remove it first, effectively "moving" it
4831 currentIndex
= this.items
.indexOf( item
);
4832 if ( currentIndex
>= 0 ) {
4833 this.removeItems( [ item
] );
4834 // Adjust index to compensate for removal
4835 if ( currentIndex
< index
) {
4840 if ( item
.connect
&& item
.disconnect
&& !$.isEmptyObject( this.aggregateItemEvents
) ) {
4842 for ( event
in this.aggregateItemEvents
) {
4843 events
[ event
] = [ 'emit', this.aggregateItemEvents
[ event
], item
];
4845 item
.connect( this, events
);
4847 item
.setElementGroup( this );
4848 itemElements
.push( item
.$element
.get( 0 ) );
4851 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
4852 this.$group
.append( itemElements
);
4853 this.items
.push
.apply( this.items
, items
);
4854 } else if ( index
=== 0 ) {
4855 this.$group
.prepend( itemElements
);
4856 this.items
.unshift
.apply( this.items
, items
);
4858 this.items
[ index
].$element
.before( itemElements
);
4859 this.items
.splice
.apply( this.items
, [ index
, 0 ].concat( items
) );
4866 * Remove the specified items from a group.
4868 * Removed items are detached (not removed) from the DOM so that they may be reused.
4869 * To remove all items from a group, you may wish to use the #clearItems method instead.
4871 * @param {OO.ui.Element[]} items An array of items to remove
4874 OO
.ui
.mixin
.GroupElement
.prototype.removeItems = function ( items
) {
4875 var i
, len
, item
, index
, remove
, itemEvent
;
4877 // Remove specific items
4878 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
4880 index
= this.items
.indexOf( item
);
4881 if ( index
!== -1 ) {
4883 item
.connect
&& item
.disconnect
&&
4884 !$.isEmptyObject( this.aggregateItemEvents
)
4887 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4888 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4890 item
.disconnect( this, remove
);
4892 item
.setElementGroup( null );
4893 this.items
.splice( index
, 1 );
4894 item
.$element
.detach();
4902 * Clear all items from the group.
4904 * Cleared items are detached from the DOM, not removed, so that they may be reused.
4905 * To remove only a subset of items from a group, use the #removeItems method.
4909 OO
.ui
.mixin
.GroupElement
.prototype.clearItems = function () {
4910 var i
, len
, item
, remove
, itemEvent
;
4913 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4914 item
= this.items
[ i
];
4916 item
.connect
&& item
.disconnect
&&
4917 !$.isEmptyObject( this.aggregateItemEvents
)
4920 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
4921 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
4923 item
.disconnect( this, remove
);
4925 item
.setElementGroup( null );
4926 item
.$element
.detach();
4934 * DraggableElement is a mixin class used to create elements that can be clicked
4935 * and dragged by a mouse to a new position within a group. This class must be used
4936 * in conjunction with OO.ui.mixin.DraggableGroupElement, which provides a container for
4937 * the draggable elements.
4944 OO
.ui
.mixin
.DraggableElement
= function OoUiMixinDraggableElement() {
4948 // Initialize and events
4950 .attr( 'draggable', true )
4951 .addClass( 'oo-ui-draggableElement' )
4953 dragstart
: this.onDragStart
.bind( this ),
4954 dragover
: this.onDragOver
.bind( this ),
4955 dragend
: this.onDragEnd
.bind( this ),
4956 drop
: this.onDrop
.bind( this )
4960 OO
.initClass( OO
.ui
.mixin
.DraggableElement
);
4967 * A dragstart event is emitted when the user clicks and begins dragging an item.
4968 * @param {OO.ui.mixin.DraggableElement} item The item the user has clicked and is dragging with the mouse.
4973 * A dragend event is emitted when the user drags an item and releases the mouse,
4974 * thus terminating the drag operation.
4979 * A drop event is emitted when the user drags an item and then releases the mouse button
4980 * over a valid target.
4983 /* Static Properties */
4986 * @inheritdoc OO.ui.mixin.ButtonElement
4988 OO
.ui
.mixin
.DraggableElement
.static.cancelButtonMouseDownEvents
= false;
4993 * Respond to dragstart event.
4996 * @param {jQuery.Event} event jQuery event
4999 OO
.ui
.mixin
.DraggableElement
.prototype.onDragStart = function ( e
) {
5000 var dataTransfer
= e
.originalEvent
.dataTransfer
;
5001 // Define drop effect
5002 dataTransfer
.dropEffect
= 'none';
5003 dataTransfer
.effectAllowed
= 'move';
5005 // We must set up a dataTransfer data property or Firefox seems to
5006 // ignore the fact the element is draggable.
5008 dataTransfer
.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
5010 // The above is only for Firefox. Move on if it fails.
5012 // Add dragging class
5013 this.$element
.addClass( 'oo-ui-draggableElement-dragging' );
5015 this.emit( 'dragstart', this );
5020 * Respond to dragend event.
5025 OO
.ui
.mixin
.DraggableElement
.prototype.onDragEnd = function () {
5026 this.$element
.removeClass( 'oo-ui-draggableElement-dragging' );
5027 this.emit( 'dragend' );
5031 * Handle drop event.
5034 * @param {jQuery.Event} event jQuery event
5037 OO
.ui
.mixin
.DraggableElement
.prototype.onDrop = function ( e
) {
5039 this.emit( 'drop', e
);
5043 * In order for drag/drop to work, the dragover event must
5044 * return false and stop propogation.
5048 OO
.ui
.mixin
.DraggableElement
.prototype.onDragOver = function ( e
) {
5054 * Store it in the DOM so we can access from the widget drag event
5057 * @param {number} Item index
5059 OO
.ui
.mixin
.DraggableElement
.prototype.setIndex = function ( index
) {
5060 if ( this.index
!== index
) {
5062 this.$element
.data( 'index', index
);
5070 * @return {number} Item index
5072 OO
.ui
.mixin
.DraggableElement
.prototype.getIndex = function () {
5077 * DraggableGroupElement is a mixin class used to create a group element to
5078 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
5079 * The class is used with OO.ui.mixin.DraggableElement.
5083 * @mixins OO.ui.mixin.GroupElement
5086 * @param {Object} [config] Configuration options
5087 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
5088 * should match the layout of the items. Items displayed in a single row
5089 * or in several rows should use horizontal orientation. The vertical orientation should only be
5090 * used when the items are displayed in a single column. Defaults to 'vertical'
5092 OO
.ui
.mixin
.DraggableGroupElement
= function OoUiMixinDraggableGroupElement( config
) {
5093 // Configuration initialization
5094 config
= config
|| {};
5096 // Parent constructor
5097 OO
.ui
.mixin
.GroupElement
.call( this, config
);
5100 this.orientation
= config
.orientation
|| 'vertical';
5101 this.dragItem
= null;
5102 this.itemDragOver
= null;
5104 this.sideInsertion
= '';
5108 dragstart
: 'itemDragStart',
5109 dragend
: 'itemDragEnd',
5112 this.connect( this, {
5113 itemDragStart
: 'onItemDragStart',
5114 itemDrop
: 'onItemDrop',
5115 itemDragEnd
: 'onItemDragEnd'
5118 dragover
: this.onDragOver
.bind( this ),
5119 dragleave
: this.onDragLeave
.bind( this )
5123 if ( Array
.isArray( config
.items
) ) {
5124 this.addItems( config
.items
);
5126 this.$placeholder
= $( '<div>' )
5127 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
5129 .addClass( 'oo-ui-draggableGroupElement' )
5130 .append( this.$status
)
5131 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation
=== 'horizontal' )
5132 .prepend( this.$placeholder
);
5136 OO
.mixinClass( OO
.ui
.mixin
.DraggableGroupElement
, OO
.ui
.mixin
.GroupElement
);
5141 * A 'reorder' event is emitted when the order of items in the group changes.
5144 * @param {OO.ui.mixin.DraggableElement} item Reordered item
5145 * @param {number} [newIndex] New index for the item
5151 * Respond to item drag start event
5154 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5156 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDragStart = function ( item
) {
5159 // Map the index of each object
5160 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5161 this.items
[ i
].setIndex( i
);
5164 if ( this.orientation
=== 'horizontal' ) {
5165 // Set the height of the indicator
5166 this.$placeholder
.css( {
5167 height
: item
.$element
.outerHeight(),
5171 // Set the width of the indicator
5172 this.$placeholder
.css( {
5174 width
: item
.$element
.outerWidth()
5177 this.setDragItem( item
);
5181 * Respond to item drag end event
5185 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDragEnd = function () {
5186 this.unsetDragItem();
5191 * Handle drop event and switch the order of the items accordingly
5194 * @param {OO.ui.mixin.DraggableElement} item Dropped item
5197 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDrop = function ( item
) {
5198 var toIndex
= item
.getIndex();
5199 // Check if the dropped item is from the current group
5200 // TODO: Figure out a way to configure a list of legally droppable
5201 // elements even if they are not yet in the list
5202 if ( this.getDragItem() ) {
5203 // If the insertion point is 'after', the insertion index
5204 // is shifted to the right (or to the left in RTL, hence 'after')
5205 if ( this.sideInsertion
=== 'after' ) {
5208 // Emit change event
5209 this.emit( 'reorder', this.getDragItem(), toIndex
);
5211 this.unsetDragItem();
5212 // Return false to prevent propogation
5217 * Handle dragleave event.
5221 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onDragLeave = function () {
5222 // This means the item was dragged outside the widget
5225 .addClass( 'oo-ui-element-hidden' );
5229 * Respond to dragover event
5232 * @param {jQuery.Event} event Event details
5234 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onDragOver = function ( e
) {
5235 var dragOverObj
, $optionWidget
, itemOffset
, itemMidpoint
, itemBoundingRect
,
5236 itemSize
, cssOutput
, dragPosition
, itemIndex
, itemPosition
,
5237 clientX
= e
.originalEvent
.clientX
,
5238 clientY
= e
.originalEvent
.clientY
;
5240 // Get the OptionWidget item we are dragging over
5241 dragOverObj
= this.getElementDocument().elementFromPoint( clientX
, clientY
);
5242 $optionWidget
= $( dragOverObj
).closest( '.oo-ui-draggableElement' );
5243 if ( $optionWidget
[ 0 ] ) {
5244 itemOffset
= $optionWidget
.offset();
5245 itemBoundingRect
= $optionWidget
[ 0 ].getBoundingClientRect();
5246 itemPosition
= $optionWidget
.position();
5247 itemIndex
= $optionWidget
.data( 'index' );
5252 this.isDragging() &&
5253 itemIndex
!== this.getDragItem().getIndex()
5255 if ( this.orientation
=== 'horizontal' ) {
5256 // Calculate where the mouse is relative to the item width
5257 itemSize
= itemBoundingRect
.width
;
5258 itemMidpoint
= itemBoundingRect
.left
+ itemSize
/ 2;
5259 dragPosition
= clientX
;
5260 // Which side of the item we hover over will dictate
5261 // where the placeholder will appear, on the left or
5264 left
: dragPosition
< itemMidpoint
? itemPosition
.left
: itemPosition
.left
+ itemSize
,
5265 top
: itemPosition
.top
5268 // Calculate where the mouse is relative to the item height
5269 itemSize
= itemBoundingRect
.height
;
5270 itemMidpoint
= itemBoundingRect
.top
+ itemSize
/ 2;
5271 dragPosition
= clientY
;
5272 // Which side of the item we hover over will dictate
5273 // where the placeholder will appear, on the top or
5276 top
: dragPosition
< itemMidpoint
? itemPosition
.top
: itemPosition
.top
+ itemSize
,
5277 left
: itemPosition
.left
5280 // Store whether we are before or after an item to rearrange
5281 // For horizontal layout, we need to account for RTL, as this is flipped
5282 if ( this.orientation
=== 'horizontal' && this.$element
.css( 'direction' ) === 'rtl' ) {
5283 this.sideInsertion
= dragPosition
< itemMidpoint
? 'after' : 'before';
5285 this.sideInsertion
= dragPosition
< itemMidpoint
? 'before' : 'after';
5287 // Add drop indicator between objects
5290 .removeClass( 'oo-ui-element-hidden' );
5292 // This means the item was dragged outside the widget
5295 .addClass( 'oo-ui-element-hidden' );
5302 * Set a dragged item
5304 * @param {OO.ui.mixin.DraggableElement} item Dragged item
5306 OO
.ui
.mixin
.DraggableGroupElement
.prototype.setDragItem = function ( item
) {
5307 this.dragItem
= item
;
5311 * Unset the current dragged item
5313 OO
.ui
.mixin
.DraggableGroupElement
.prototype.unsetDragItem = function () {
5314 this.dragItem
= null;
5315 this.itemDragOver
= null;
5316 this.$placeholder
.addClass( 'oo-ui-element-hidden' );
5317 this.sideInsertion
= '';
5321 * Get the item that is currently being dragged.
5323 * @return {OO.ui.mixin.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
5325 OO
.ui
.mixin
.DraggableGroupElement
.prototype.getDragItem = function () {
5326 return this.dragItem
;
5330 * Check if an item in the group is currently being dragged.
5332 * @return {Boolean} Item is being dragged
5334 OO
.ui
.mixin
.DraggableGroupElement
.prototype.isDragging = function () {
5335 return this.getDragItem() !== null;
5339 * IconElement is often mixed into other classes to generate an icon.
5340 * Icons are graphics, about the size of normal text. They are used to aid the user
5341 * in locating a control or to convey information in a space-efficient way. See the
5342 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
5343 * included in the library.
5345 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5351 * @param {Object} [config] Configuration options
5352 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
5353 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
5354 * the icon element be set to an existing icon instead of the one generated by this class, set a
5355 * value using a jQuery selection. For example:
5357 * // Use a <div> tag instead of a <span>
5359 * // Use an existing icon element instead of the one generated by the class
5360 * $icon: this.$element
5361 * // Use an icon element from a child widget
5362 * $icon: this.childwidget.$element
5363 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
5364 * symbolic names. A map is used for i18n purposes and contains a `default` icon
5365 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
5366 * by the user's language.
5368 * Example of an i18n map:
5370 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5371 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
5372 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5373 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
5374 * text. The icon title is displayed when users move the mouse over the icon.
5376 OO
.ui
.mixin
.IconElement
= function OoUiMixinIconElement( config
) {
5377 // Configuration initialization
5378 config
= config
|| {};
5383 this.iconTitle
= null;
5386 this.setIcon( config
.icon
|| this.constructor.static.icon
);
5387 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
5388 this.setIconElement( config
.$icon
|| $( '<span>' ) );
5393 OO
.initClass( OO
.ui
.mixin
.IconElement
);
5395 /* Static Properties */
5398 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
5399 * for i18n purposes and contains a `default` icon name and additional names keyed by
5400 * language code. The `default` name is used when no icon is keyed by the user's language.
5402 * Example of an i18n map:
5404 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5406 * Note: the static property will be overridden if the #icon configuration is used.
5410 * @property {Object|string}
5412 OO
.ui
.mixin
.IconElement
.static.icon
= null;
5415 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
5416 * function that returns title text, or `null` for no title.
5418 * The static property will be overridden if the #iconTitle configuration is used.
5422 * @property {string|Function|null}
5424 OO
.ui
.mixin
.IconElement
.static.iconTitle
= null;
5429 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
5430 * applies to the specified icon element instead of the one created by the class. If an icon
5431 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
5432 * and mixin methods will no longer affect the element.
5434 * @param {jQuery} $icon Element to use as icon
5436 OO
.ui
.mixin
.IconElement
.prototype.setIconElement = function ( $icon
) {
5439 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
5440 .removeAttr( 'title' );
5444 .addClass( 'oo-ui-iconElement-icon' )
5445 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
5446 if ( this.iconTitle
!== null ) {
5447 this.$icon
.attr( 'title', this.iconTitle
);
5450 this.updateThemeClasses();
5454 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
5455 * The icon parameter can also be set to a map of icon names. See the #icon config setting
5458 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
5459 * by language code, or `null` to remove the icon.
5462 OO
.ui
.mixin
.IconElement
.prototype.setIcon = function ( icon
) {
5463 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
5464 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
5466 if ( this.icon
!== icon
) {
5468 if ( this.icon
!== null ) {
5469 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
5471 if ( icon
!== null ) {
5472 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
5478 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
5479 this.updateThemeClasses();
5485 * Set the icon title. Use `null` to remove the title.
5487 * @param {string|Function|null} iconTitle A text string used as the icon title,
5488 * a function that returns title text, or `null` for no title.
5491 OO
.ui
.mixin
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
5492 iconTitle
= typeof iconTitle
=== 'function' ||
5493 ( typeof iconTitle
=== 'string' && iconTitle
.length
) ?
5494 OO
.ui
.resolveMsg( iconTitle
) : null;
5496 if ( this.iconTitle
!== iconTitle
) {
5497 this.iconTitle
= iconTitle
;
5499 if ( this.iconTitle
!== null ) {
5500 this.$icon
.attr( 'title', iconTitle
);
5502 this.$icon
.removeAttr( 'title' );
5511 * Get the symbolic name of the icon.
5513 * @return {string} Icon name
5515 OO
.ui
.mixin
.IconElement
.prototype.getIcon = function () {
5520 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5522 * @return {string} Icon title text
5524 OO
.ui
.mixin
.IconElement
.prototype.getIconTitle = function () {
5525 return this.iconTitle
;
5529 * IndicatorElement is often mixed into other classes to generate an indicator.
5530 * Indicators are small graphics that are generally used in two ways:
5532 * - To draw attention to the status of an item. For example, an indicator might be
5533 * used to show that an item in a list has errors that need to be resolved.
5534 * - To clarify the function of a control that acts in an exceptional way (a button
5535 * that opens a menu instead of performing an action directly, for example).
5537 * For a list of indicators included in the library, please see the
5538 * [OOjs UI documentation on MediaWiki] [1].
5540 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5546 * @param {Object} [config] Configuration options
5547 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5548 * configuration is omitted, the indicator element will use a generated `<span>`.
5549 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5550 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5552 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5553 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5554 * or a function that returns title text. The indicator title is displayed when users move
5555 * the mouse over the indicator.
5557 OO
.ui
.mixin
.IndicatorElement
= function OoUiMixinIndicatorElement( config
) {
5558 // Configuration initialization
5559 config
= config
|| {};
5562 this.$indicator
= null;
5563 this.indicator
= null;
5564 this.indicatorTitle
= null;
5567 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
5568 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
5569 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
5574 OO
.initClass( OO
.ui
.mixin
.IndicatorElement
);
5576 /* Static Properties */
5579 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5580 * The static property will be overridden if the #indicator configuration is used.
5584 * @property {string|null}
5586 OO
.ui
.mixin
.IndicatorElement
.static.indicator
= null;
5589 * A text string used as the indicator title, a function that returns title text, or `null`
5590 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5594 * @property {string|Function|null}
5596 OO
.ui
.mixin
.IndicatorElement
.static.indicatorTitle
= null;
5601 * Set the indicator element.
5603 * If an element is already set, it will be cleaned up before setting up the new element.
5605 * @param {jQuery} $indicator Element to use as indicator
5607 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
5608 if ( this.$indicator
) {
5610 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
5611 .removeAttr( 'title' );
5614 this.$indicator
= $indicator
5615 .addClass( 'oo-ui-indicatorElement-indicator' )
5616 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
5617 if ( this.indicatorTitle
!== null ) {
5618 this.$indicator
.attr( 'title', this.indicatorTitle
);
5621 this.updateThemeClasses();
5625 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5627 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5630 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
5631 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
5633 if ( this.indicator
!== indicator
) {
5634 if ( this.$indicator
) {
5635 if ( this.indicator
!== null ) {
5636 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
5638 if ( indicator
!== null ) {
5639 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
5642 this.indicator
= indicator
;
5645 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
5646 this.updateThemeClasses();
5652 * Set the indicator title.
5654 * The title is displayed when a user moves the mouse over the indicator.
5656 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5657 * `null` for no indicator title
5660 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorTitle = function ( indicatorTitle
) {
5661 indicatorTitle
= typeof indicatorTitle
=== 'function' ||
5662 ( typeof indicatorTitle
=== 'string' && indicatorTitle
.length
) ?
5663 OO
.ui
.resolveMsg( indicatorTitle
) : null;
5665 if ( this.indicatorTitle
!== indicatorTitle
) {
5666 this.indicatorTitle
= indicatorTitle
;
5667 if ( this.$indicator
) {
5668 if ( this.indicatorTitle
!== null ) {
5669 this.$indicator
.attr( 'title', indicatorTitle
);
5671 this.$indicator
.removeAttr( 'title' );
5680 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5682 * @return {string} Symbolic name of indicator
5684 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicator = function () {
5685 return this.indicator
;
5689 * Get the indicator title.
5691 * The title is displayed when a user moves the mouse over the indicator.
5693 * @return {string} Indicator title text
5695 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicatorTitle = function () {
5696 return this.indicatorTitle
;
5700 * LabelElement is often mixed into other classes to generate a label, which
5701 * helps identify the function of an interface element.
5702 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5704 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5710 * @param {Object} [config] Configuration options
5711 * @cfg {jQuery} [$label] The label element created by the class. If this
5712 * configuration is omitted, the label element will use a generated `<span>`.
5713 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
5714 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
5715 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
5716 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5717 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5718 * The label will be truncated to fit if necessary.
5720 OO
.ui
.mixin
.LabelElement
= function OoUiMixinLabelElement( config
) {
5721 // Configuration initialization
5722 config
= config
|| {};
5727 this.autoFitLabel
= config
.autoFitLabel
=== undefined || !!config
.autoFitLabel
;
5730 this.setLabel( config
.label
|| this.constructor.static.label
);
5731 this.setLabelElement( config
.$label
|| $( '<span>' ) );
5736 OO
.initClass( OO
.ui
.mixin
.LabelElement
);
5741 * @event labelChange
5742 * @param {string} value
5745 /* Static Properties */
5748 * The label text. The label can be specified as a plaintext string, a function that will
5749 * produce a string in the future, or `null` for no label. The static value will
5750 * be overridden if a label is specified with the #label config option.
5754 * @property {string|Function|null}
5756 OO
.ui
.mixin
.LabelElement
.static.label
= null;
5761 * Set the label element.
5763 * If an element is already set, it will be cleaned up before setting up the new element.
5765 * @param {jQuery} $label Element to use as label
5767 OO
.ui
.mixin
.LabelElement
.prototype.setLabelElement = function ( $label
) {
5768 if ( this.$label
) {
5769 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
5772 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
5773 this.setLabelContent( this.label
);
5779 * An empty string will result in the label being hidden. A string containing only whitespace will
5780 * be converted to a single ` `.
5782 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
5783 * text; or null for no label
5786 OO
.ui
.mixin
.LabelElement
.prototype.setLabel = function ( label
) {
5787 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
5788 label
= ( ( typeof label
=== 'string' && label
.length
) || label
instanceof jQuery
|| label
instanceof OO
.ui
.HtmlSnippet
) ? label
: null;
5790 this.$element
.toggleClass( 'oo-ui-labelElement', !!label
);
5792 if ( this.label
!== label
) {
5793 if ( this.$label
) {
5794 this.setLabelContent( label
);
5797 this.emit( 'labelChange' );
5806 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
5807 * text; or null for no label
5809 OO
.ui
.mixin
.LabelElement
.prototype.getLabel = function () {
5818 OO
.ui
.mixin
.LabelElement
.prototype.fitLabel = function () {
5819 if ( this.$label
&& this.$label
.autoEllipsis
&& this.autoFitLabel
) {
5820 this.$label
.autoEllipsis( { hasSpan
: false, tooltip
: true } );
5827 * Set the content of the label.
5829 * Do not call this method until after the label element has been set by #setLabelElement.
5832 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5833 * text; or null for no label
5835 OO
.ui
.mixin
.LabelElement
.prototype.setLabelContent = function ( label
) {
5836 if ( typeof label
=== 'string' ) {
5837 if ( label
.match( /^\s*$/ ) ) {
5838 // Convert whitespace only string to a single non-breaking space
5839 this.$label
.html( ' ' );
5841 this.$label
.text( label
);
5843 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
5844 this.$label
.html( label
.toString() );
5845 } else if ( label
instanceof jQuery
) {
5846 this.$label
.empty().append( label
);
5848 this.$label
.empty();
5853 * LookupElement is a mixin that creates a {@link OO.ui.FloatingMenuSelectWidget menu} of suggested values for
5854 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
5855 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
5856 * from the lookup menu, that value becomes the value of the input field.
5858 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
5859 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
5860 * re-enable lookups.
5862 * See the [OOjs UI demos][1] for an example.
5864 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
5870 * @param {Object} [config] Configuration options
5871 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
5872 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
5873 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
5874 * By default, the lookup menu is not generated and displayed until the user begins to type.
5876 OO
.ui
.mixin
.LookupElement
= function OoUiMixinLookupElement( config
) {
5877 // Configuration initialization
5878 config
= config
|| {};
5881 this.$overlay
= config
.$overlay
|| this.$element
;
5882 this.lookupMenu
= new OO
.ui
.FloatingMenuSelectWidget( {
5885 $container
: config
.$container
|| this.$element
5888 this.allowSuggestionsWhenEmpty
= config
.allowSuggestionsWhenEmpty
|| false;
5890 this.lookupCache
= {};
5891 this.lookupQuery
= null;
5892 this.lookupRequest
= null;
5893 this.lookupsDisabled
= false;
5894 this.lookupInputFocused
= false;
5898 focus
: this.onLookupInputFocus
.bind( this ),
5899 blur
: this.onLookupInputBlur
.bind( this ),
5900 mousedown
: this.onLookupInputMouseDown
.bind( this )
5902 this.connect( this, { change
: 'onLookupInputChange' } );
5903 this.lookupMenu
.connect( this, {
5904 toggle
: 'onLookupMenuToggle',
5905 choose
: 'onLookupMenuItemChoose'
5909 this.$element
.addClass( 'oo-ui-lookupElement' );
5910 this.lookupMenu
.$element
.addClass( 'oo-ui-lookupElement-menu' );
5911 this.$overlay
.append( this.lookupMenu
.$element
);
5917 * Handle input focus event.
5920 * @param {jQuery.Event} e Input focus event
5922 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputFocus = function () {
5923 this.lookupInputFocused
= true;
5924 this.populateLookupMenu();
5928 * Handle input blur event.
5931 * @param {jQuery.Event} e Input blur event
5933 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputBlur = function () {
5934 this.closeLookupMenu();
5935 this.lookupInputFocused
= false;
5939 * Handle input mouse down event.
5942 * @param {jQuery.Event} e Input mouse down event
5944 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputMouseDown = function () {
5945 // Only open the menu if the input was already focused.
5946 // This way we allow the user to open the menu again after closing it with Esc
5947 // by clicking in the input. Opening (and populating) the menu when initially
5948 // clicking into the input is handled by the focus handler.
5949 if ( this.lookupInputFocused
&& !this.lookupMenu
.isVisible() ) {
5950 this.populateLookupMenu();
5955 * Handle input change event.
5958 * @param {string} value New input value
5960 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputChange = function () {
5961 if ( this.lookupInputFocused
) {
5962 this.populateLookupMenu();
5967 * Handle the lookup menu being shown/hidden.
5970 * @param {boolean} visible Whether the lookup menu is now visible.
5972 OO
.ui
.mixin
.LookupElement
.prototype.onLookupMenuToggle = function ( visible
) {
5974 // When the menu is hidden, abort any active request and clear the menu.
5975 // This has to be done here in addition to closeLookupMenu(), because
5976 // MenuSelectWidget will close itself when the user presses Esc.
5977 this.abortLookupRequest();
5978 this.lookupMenu
.clearItems();
5983 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
5986 * @param {OO.ui.MenuOptionWidget} item Selected item
5988 OO
.ui
.mixin
.LookupElement
.prototype.onLookupMenuItemChoose = function ( item
) {
5989 this.setValue( item
.getData() );
5996 * @return {OO.ui.FloatingMenuSelectWidget}
5998 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenu = function () {
5999 return this.lookupMenu
;
6003 * Disable or re-enable lookups.
6005 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
6007 * @param {boolean} disabled Disable lookups
6009 OO
.ui
.mixin
.LookupElement
.prototype.setLookupsDisabled = function ( disabled
) {
6010 this.lookupsDisabled
= !!disabled
;
6014 * Open the menu. If there are no entries in the menu, this does nothing.
6019 OO
.ui
.mixin
.LookupElement
.prototype.openLookupMenu = function () {
6020 if ( !this.lookupMenu
.isEmpty() ) {
6021 this.lookupMenu
.toggle( true );
6027 * Close the menu, empty it, and abort any pending request.
6032 OO
.ui
.mixin
.LookupElement
.prototype.closeLookupMenu = function () {
6033 this.lookupMenu
.toggle( false );
6034 this.abortLookupRequest();
6035 this.lookupMenu
.clearItems();
6040 * Request menu items based on the input's current value, and when they arrive,
6041 * populate the menu with these items and show the menu.
6043 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
6048 OO
.ui
.mixin
.LookupElement
.prototype.populateLookupMenu = function () {
6050 value
= this.getValue();
6052 if ( this.lookupsDisabled
|| this.isReadOnly() ) {
6056 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
6057 if ( !this.allowSuggestionsWhenEmpty
&& value
=== '' ) {
6058 this.closeLookupMenu();
6059 // Skip population if there is already a request pending for the current value
6060 } else if ( value
!== this.lookupQuery
) {
6061 this.getLookupMenuItems()
6062 .done( function ( items
) {
6063 widget
.lookupMenu
.clearItems();
6064 if ( items
.length
) {
6068 widget
.initializeLookupMenuSelection();
6070 widget
.lookupMenu
.toggle( false );
6073 .fail( function () {
6074 widget
.lookupMenu
.clearItems();
6082 * Highlight the first selectable item in the menu.
6087 OO
.ui
.mixin
.LookupElement
.prototype.initializeLookupMenuSelection = function () {
6088 if ( !this.lookupMenu
.getSelectedItem() ) {
6089 this.lookupMenu
.highlightItem( this.lookupMenu
.getFirstSelectableItem() );
6094 * Get lookup menu items for the current query.
6097 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
6098 * the done event. If the request was aborted to make way for a subsequent request, this promise
6099 * will not be rejected: it will remain pending forever.
6101 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenuItems = function () {
6103 value
= this.getValue(),
6104 deferred
= $.Deferred(),
6107 this.abortLookupRequest();
6108 if ( Object
.prototype.hasOwnProperty
.call( this.lookupCache
, value
) ) {
6109 deferred
.resolve( this.getLookupMenuOptionsFromData( this.lookupCache
[ value
] ) );
6112 this.lookupQuery
= value
;
6113 ourRequest
= this.lookupRequest
= this.getLookupRequest();
6115 .always( function () {
6116 // We need to pop pending even if this is an old request, otherwise
6117 // the widget will remain pending forever.
6118 // TODO: this assumes that an aborted request will fail or succeed soon after
6119 // being aborted, or at least eventually. It would be nice if we could popPending()
6120 // at abort time, but only if we knew that we hadn't already called popPending()
6121 // for that request.
6122 widget
.popPending();
6124 .done( function ( response
) {
6125 // If this is an old request (and aborting it somehow caused it to still succeed),
6126 // ignore its success completely
6127 if ( ourRequest
=== widget
.lookupRequest
) {
6128 widget
.lookupQuery
= null;
6129 widget
.lookupRequest
= null;
6130 widget
.lookupCache
[ value
] = widget
.getLookupCacheDataFromResponse( response
);
6131 deferred
.resolve( widget
.getLookupMenuOptionsFromData( widget
.lookupCache
[ value
] ) );
6134 .fail( function () {
6135 // If this is an old request (or a request failing because it's being aborted),
6136 // ignore its failure completely
6137 if ( ourRequest
=== widget
.lookupRequest
) {
6138 widget
.lookupQuery
= null;
6139 widget
.lookupRequest
= null;
6144 return deferred
.promise();
6148 * Abort the currently pending lookup request, if any.
6152 OO
.ui
.mixin
.LookupElement
.prototype.abortLookupRequest = function () {
6153 var oldRequest
= this.lookupRequest
;
6155 // First unset this.lookupRequest to the fail handler will notice
6156 // that the request is no longer current
6157 this.lookupRequest
= null;
6158 this.lookupQuery
= null;
6164 * Get a new request object of the current lookup query value.
6168 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
6170 OO
.ui
.mixin
.LookupElement
.prototype.getLookupRequest = function () {
6171 // Stub, implemented in subclass
6176 * Pre-process data returned by the request from #getLookupRequest.
6178 * The return value of this function will be cached, and any further queries for the given value
6179 * will use the cache rather than doing API requests.
6183 * @param {Mixed} response Response from server
6184 * @return {Mixed} Cached result data
6186 OO
.ui
.mixin
.LookupElement
.prototype.getLookupCacheDataFromResponse = function () {
6187 // Stub, implemented in subclass
6192 * Get a list of menu option widgets from the (possibly cached) data returned by
6193 * #getLookupCacheDataFromResponse.
6197 * @param {Mixed} data Cached result data, usually an array
6198 * @return {OO.ui.MenuOptionWidget[]} Menu items
6200 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenuOptionsFromData = function () {
6201 // Stub, implemented in subclass
6206 * Set the read-only state of the widget.
6208 * This will also disable/enable the lookups functionality.
6210 * @param {boolean} readOnly Make input read-only
6213 OO
.ui
.mixin
.LookupElement
.prototype.setReadOnly = function ( readOnly
) {
6215 // Note: Calling #setReadOnly this way assumes this is mixed into an OO.ui.TextInputWidget
6216 OO
.ui
.TextInputWidget
.prototype.setReadOnly
.call( this, readOnly
);
6218 // During construction, #setReadOnly is called before the OO.ui.mixin.LookupElement constructor
6219 if ( this.isReadOnly() && this.lookupMenu
) {
6220 this.closeLookupMenu();
6227 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
6228 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
6229 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
6230 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
6236 * @param {Object} [config] Configuration options
6237 * @cfg {Object} [popup] Configuration to pass to popup
6238 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
6240 OO
.ui
.mixin
.PopupElement
= function OoUiMixinPopupElement( config
) {
6241 // Configuration initialization
6242 config
= config
|| {};
6245 this.popup
= new OO
.ui
.PopupWidget( $.extend(
6246 { autoClose
: true },
6248 { $autoCloseIgnore
: this.$element
}
6257 * @return {OO.ui.PopupWidget} Popup widget
6259 OO
.ui
.mixin
.PopupElement
.prototype.getPopup = function () {
6264 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
6265 * additional functionality to an element created by another class. The class provides
6266 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
6267 * which are used to customize the look and feel of a widget to better describe its
6268 * importance and functionality.
6270 * The library currently contains the following styling flags for general use:
6272 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
6273 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
6274 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
6276 * The flags affect the appearance of the buttons:
6279 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
6280 * var button1 = new OO.ui.ButtonWidget( {
6281 * label: 'Constructive',
6282 * flags: 'constructive'
6284 * var button2 = new OO.ui.ButtonWidget( {
6285 * label: 'Destructive',
6286 * flags: 'destructive'
6288 * var button3 = new OO.ui.ButtonWidget( {
6289 * label: 'Progressive',
6290 * flags: 'progressive'
6292 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
6294 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
6295 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
6297 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6303 * @param {Object} [config] Configuration options
6304 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
6305 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
6306 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
6307 * @cfg {jQuery} [$flagged] The flagged element. By default,
6308 * the flagged functionality is applied to the element created by the class ($element).
6309 * If a different element is specified, the flagged functionality will be applied to it instead.
6311 OO
.ui
.mixin
.FlaggedElement
= function OoUiMixinFlaggedElement( config
) {
6312 // Configuration initialization
6313 config
= config
|| {};
6317 this.$flagged
= null;
6320 this.setFlags( config
.flags
);
6321 this.setFlaggedElement( config
.$flagged
|| this.$element
);
6328 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
6329 * parameter contains the name of each modified flag and indicates whether it was
6332 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
6333 * that the flag was added, `false` that the flag was removed.
6339 * Set the flagged element.
6341 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
6342 * If an element is already set, the method will remove the mixin’s effect on that element.
6344 * @param {jQuery} $flagged Element that should be flagged
6346 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
6347 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
6348 return 'oo-ui-flaggedElement-' + flag
;
6351 if ( this.$flagged
) {
6352 this.$flagged
.removeClass( classNames
);
6355 this.$flagged
= $flagged
.addClass( classNames
);
6359 * Check if the specified flag is set.
6361 * @param {string} flag Name of flag
6362 * @return {boolean} The flag is set
6364 OO
.ui
.mixin
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
6365 // This may be called before the constructor, thus before this.flags is set
6366 return this.flags
&& ( flag
in this.flags
);
6370 * Get the names of all flags set.
6372 * @return {string[]} Flag names
6374 OO
.ui
.mixin
.FlaggedElement
.prototype.getFlags = function () {
6375 // This may be called before the constructor, thus before this.flags is set
6376 return Object
.keys( this.flags
|| {} );
6385 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags = function () {
6386 var flag
, className
,
6389 classPrefix
= 'oo-ui-flaggedElement-';
6391 for ( flag
in this.flags
) {
6392 className
= classPrefix
+ flag
;
6393 changes
[ flag
] = false;
6394 delete this.flags
[ flag
];
6395 remove
.push( className
);
6398 if ( this.$flagged
) {
6399 this.$flagged
.removeClass( remove
.join( ' ' ) );
6402 this.updateThemeClasses();
6403 this.emit( 'flag', changes
);
6409 * Add one or more flags.
6411 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
6412 * or an object keyed by flag name with a boolean value that indicates whether the flag should
6413 * be added (`true`) or removed (`false`).
6417 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags = function ( flags
) {
6418 var i
, len
, flag
, className
,
6422 classPrefix
= 'oo-ui-flaggedElement-';
6424 if ( typeof flags
=== 'string' ) {
6425 className
= classPrefix
+ flags
;
6427 if ( !this.flags
[ flags
] ) {
6428 this.flags
[ flags
] = true;
6429 add
.push( className
);
6431 } else if ( Array
.isArray( flags
) ) {
6432 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
6434 className
= classPrefix
+ flag
;
6436 if ( !this.flags
[ flag
] ) {
6437 changes
[ flag
] = true;
6438 this.flags
[ flag
] = true;
6439 add
.push( className
);
6442 } else if ( OO
.isPlainObject( flags
) ) {
6443 for ( flag
in flags
) {
6444 className
= classPrefix
+ flag
;
6445 if ( flags
[ flag
] ) {
6447 if ( !this.flags
[ flag
] ) {
6448 changes
[ flag
] = true;
6449 this.flags
[ flag
] = true;
6450 add
.push( className
);
6454 if ( this.flags
[ flag
] ) {
6455 changes
[ flag
] = false;
6456 delete this.flags
[ flag
];
6457 remove
.push( className
);
6463 if ( this.$flagged
) {
6465 .addClass( add
.join( ' ' ) )
6466 .removeClass( remove
.join( ' ' ) );
6469 this.updateThemeClasses();
6470 this.emit( 'flag', changes
);
6476 * TitledElement is mixed into other classes to provide a `title` attribute.
6477 * Titles are rendered by the browser and are made visible when the user moves
6478 * the mouse over the element. Titles are not visible on touch devices.
6481 * // TitledElement provides a 'title' attribute to the
6482 * // ButtonWidget class
6483 * var button = new OO.ui.ButtonWidget( {
6484 * label: 'Button with Title',
6485 * title: 'I am a button'
6487 * $( 'body' ).append( button.$element );
6493 * @param {Object} [config] Configuration options
6494 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
6495 * If this config is omitted, the title functionality is applied to $element, the
6496 * element created by the class.
6497 * @cfg {string|Function} [title] The title text or a function that returns text. If
6498 * this config is omitted, the value of the {@link #static-title static title} property is used.
6500 OO
.ui
.mixin
.TitledElement
= function OoUiMixinTitledElement( config
) {
6501 // Configuration initialization
6502 config
= config
|| {};
6505 this.$titled
= null;
6509 this.setTitle( config
.title
|| this.constructor.static.title
);
6510 this.setTitledElement( config
.$titled
|| this.$element
);
6515 OO
.initClass( OO
.ui
.mixin
.TitledElement
);
6517 /* Static Properties */
6520 * The title text, a function that returns text, or `null` for no title. The value of the static property
6521 * is overridden if the #title config option is used.
6525 * @property {string|Function|null}
6527 OO
.ui
.mixin
.TitledElement
.static.title
= null;
6532 * Set the titled element.
6534 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6535 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6537 * @param {jQuery} $titled Element that should use the 'titled' functionality
6539 OO
.ui
.mixin
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
6540 if ( this.$titled
) {
6541 this.$titled
.removeAttr( 'title' );
6544 this.$titled
= $titled
;
6546 this.$titled
.attr( 'title', this.title
);
6553 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6556 OO
.ui
.mixin
.TitledElement
.prototype.setTitle = function ( title
) {
6557 title
= typeof title
=== 'string' ? OO
.ui
.resolveMsg( title
) : null;
6559 if ( this.title
!== title
) {
6560 if ( this.$titled
) {
6561 if ( title
!== null ) {
6562 this.$titled
.attr( 'title', title
);
6564 this.$titled
.removeAttr( 'title' );
6576 * @return {string} Title string
6578 OO
.ui
.mixin
.TitledElement
.prototype.getTitle = function () {
6583 * Element that can be automatically clipped to visible boundaries.
6585 * Whenever the element's natural height changes, you have to call
6586 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
6587 * clipping correctly.
6589 * The dimensions of #$clippableContainer will be compared to the boundaries of the
6590 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
6591 * then #$clippable will be given a fixed reduced height and/or width and will be made
6592 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
6593 * but you can build a static footer by setting #$clippableContainer to an element that contains
6594 * #$clippable and the footer.
6600 * @param {Object} [config] Configuration options
6601 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
6602 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
6603 * omit to use #$clippable
6605 OO
.ui
.mixin
.ClippableElement
= function OoUiMixinClippableElement( config
) {
6606 // Configuration initialization
6607 config
= config
|| {};
6610 this.$clippable
= null;
6611 this.$clippableContainer
= null;
6612 this.clipping
= false;
6613 this.clippedHorizontally
= false;
6614 this.clippedVertically
= false;
6615 this.$clippableScrollableContainer
= null;
6616 this.$clippableScroller
= null;
6617 this.$clippableWindow
= null;
6618 this.idealWidth
= null;
6619 this.idealHeight
= null;
6620 this.onClippableScrollHandler
= this.clip
.bind( this );
6621 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
6624 if ( config
.$clippableContainer
) {
6625 this.setClippableContainer( config
.$clippableContainer
);
6627 this.setClippableElement( config
.$clippable
|| this.$element
);
6633 * Set clippable element.
6635 * If an element is already set, it will be cleaned up before setting up the new element.
6637 * @param {jQuery} $clippable Element to make clippable
6639 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
6640 if ( this.$clippable
) {
6641 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
6642 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
6643 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6646 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
6651 * Set clippable container.
6653 * This is the container that will be measured when deciding whether to clip. When clipping,
6654 * #$clippable will be resized in order to keep the clippable container fully visible.
6656 * If the clippable container is unset, #$clippable will be used.
6658 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
6660 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableContainer = function ( $clippableContainer
) {
6661 this.$clippableContainer
= $clippableContainer
;
6662 if ( this.$clippable
) {
6670 * Do not turn clipping on until after the element is attached to the DOM and visible.
6672 * @param {boolean} [clipping] Enable clipping, omit to toggle
6675 OO
.ui
.mixin
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
6676 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
6678 if ( this.clipping
!== clipping
) {
6679 this.clipping
= clipping
;
6681 this.$clippableScrollableContainer
= $( this.getClosestScrollableElementContainer() );
6682 // If the clippable container is the root, we have to listen to scroll events and check
6683 // jQuery.scrollTop on the window because of browser inconsistencies
6684 this.$clippableScroller
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
6685 $( OO
.ui
.Element
.static.getWindow( this.$clippableScrollableContainer
) ) :
6686 this.$clippableScrollableContainer
;
6687 this.$clippableScroller
.on( 'scroll', this.onClippableScrollHandler
);
6688 this.$clippableWindow
= $( this.getElementWindow() )
6689 .on( 'resize', this.onClippableWindowResizeHandler
);
6690 // Initial clip after visible
6693 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
6694 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6696 this.$clippableScrollableContainer
= null;
6697 this.$clippableScroller
.off( 'scroll', this.onClippableScrollHandler
);
6698 this.$clippableScroller
= null;
6699 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
6700 this.$clippableWindow
= null;
6708 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6710 * @return {boolean} Element will be clipped to the visible area
6712 OO
.ui
.mixin
.ClippableElement
.prototype.isClipping = function () {
6713 return this.clipping
;
6717 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6719 * @return {boolean} Part of the element is being clipped
6721 OO
.ui
.mixin
.ClippableElement
.prototype.isClipped = function () {
6722 return this.clippedHorizontally
|| this.clippedVertically
;
6726 * Check if the right of the element is being clipped by the nearest scrollable container.
6728 * @return {boolean} Part of the element is being clipped
6730 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedHorizontally = function () {
6731 return this.clippedHorizontally
;
6735 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6737 * @return {boolean} Part of the element is being clipped
6739 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedVertically = function () {
6740 return this.clippedVertically
;
6744 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6746 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6747 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6749 OO
.ui
.mixin
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
6750 this.idealWidth
= width
;
6751 this.idealHeight
= height
;
6753 if ( !this.clipping
) {
6754 // Update dimensions
6755 this.$clippable
.css( { width
: width
, height
: height
} );
6757 // While clipping, idealWidth and idealHeight are not considered
6761 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6762 * the element's natural height changes.
6764 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6765 * overlapped by, the visible area of the nearest scrollable container.
6769 OO
.ui
.mixin
.ClippableElement
.prototype.clip = function () {
6770 var $container
, extraHeight
, extraWidth
, ccOffset
,
6771 $scrollableContainer
, scOffset
, scHeight
, scWidth
,
6772 ccWidth
, scrollerIsWindow
, scrollTop
, scrollLeft
,
6773 desiredWidth
, desiredHeight
, allotedWidth
, allotedHeight
,
6774 naturalWidth
, naturalHeight
, clipWidth
, clipHeight
,
6775 buffer
= 7; // Chosen by fair dice roll
6777 if ( !this.clipping
) {
6778 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
6782 $container
= this.$clippableContainer
|| this.$clippable
;
6783 extraHeight
= $container
.outerHeight() - this.$clippable
.outerHeight();
6784 extraWidth
= $container
.outerWidth() - this.$clippable
.outerWidth();
6785 ccOffset
= $container
.offset();
6786 $scrollableContainer
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
6787 this.$clippableWindow
: this.$clippableScrollableContainer
;
6788 scOffset
= $scrollableContainer
.offset() || { top
: 0, left
: 0 };
6789 scHeight
= $scrollableContainer
.innerHeight() - buffer
;
6790 scWidth
= $scrollableContainer
.innerWidth() - buffer
;
6791 ccWidth
= $container
.outerWidth() + buffer
;
6792 scrollerIsWindow
= this.$clippableScroller
[ 0 ] === this.$clippableWindow
[ 0 ];
6793 scrollTop
= scrollerIsWindow
? this.$clippableScroller
.scrollTop() : 0;
6794 scrollLeft
= scrollerIsWindow
? this.$clippableScroller
.scrollLeft() : 0;
6795 desiredWidth
= ccOffset
.left
< 0 ?
6796 ccWidth
+ ccOffset
.left
:
6797 ( scOffset
.left
+ scrollLeft
+ scWidth
) - ccOffset
.left
;
6798 desiredHeight
= ( scOffset
.top
+ scrollTop
+ scHeight
) - ccOffset
.top
;
6799 allotedWidth
= desiredWidth
- extraWidth
;
6800 allotedHeight
= desiredHeight
- extraHeight
;
6801 naturalWidth
= this.$clippable
.prop( 'scrollWidth' );
6802 naturalHeight
= this.$clippable
.prop( 'scrollHeight' );
6803 clipWidth
= allotedWidth
< naturalWidth
;
6804 clipHeight
= allotedHeight
< naturalHeight
;
6807 this.$clippable
.css( { overflowX
: 'scroll', width
: Math
.max( 0, allotedWidth
) } );
6809 this.$clippable
.css( { width
: this.idealWidth
? this.idealWidth
- extraWidth
: '', overflowX
: '' } );
6812 this.$clippable
.css( { overflowY
: 'scroll', height
: Math
.max( 0, allotedHeight
) } );
6814 this.$clippable
.css( { height
: this.idealHeight
? this.idealHeight
- extraHeight
: '', overflowY
: '' } );
6817 // If we stopped clipping in at least one of the dimensions
6818 if ( ( this.clippedHorizontally
&& !clipWidth
) || ( this.clippedVertically
&& !clipHeight
) ) {
6819 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
6822 this.clippedHorizontally
= clipWidth
;
6823 this.clippedVertically
= clipHeight
;
6829 * Element that will stick under a specified container, even when it is inserted elsewhere in the
6830 * document (for example, in a OO.ui.Window's $overlay).
6832 * The elements's position is automatically calculated and maintained when window is resized or the
6833 * page is scrolled. If you reposition the container manually, you have to call #position to make
6834 * sure the element is still placed correctly.
6836 * As positioning is only possible when both the element and the container are attached to the DOM
6837 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
6838 * the #toggle method to display a floating popup, for example.
6844 * @param {Object} [config] Configuration options
6845 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
6846 * @cfg {jQuery} [$floatableContainer] Node to position below
6848 OO
.ui
.mixin
.FloatableElement
= function OoUiMixinFloatableElement( config
) {
6849 // Configuration initialization
6850 config
= config
|| {};
6853 this.$floatable
= null;
6854 this.$floatableContainer
= null;
6855 this.$floatableWindow
= null;
6856 this.$floatableClosestScrollable
= null;
6857 this.onFloatableScrollHandler
= this.position
.bind( this );
6858 this.onFloatableWindowResizeHandler
= this.position
.bind( this );
6861 this.setFloatableContainer( config
.$floatableContainer
);
6862 this.setFloatableElement( config
.$floatable
|| this.$element
);
6868 * Set floatable element.
6870 * If an element is already set, it will be cleaned up before setting up the new element.
6872 * @param {jQuery} $floatable Element to make floatable
6874 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableElement = function ( $floatable
) {
6875 if ( this.$floatable
) {
6876 this.$floatable
.removeClass( 'oo-ui-floatableElement-floatable' );
6877 this.$floatable
.css( { left
: '', top
: '' } );
6880 this.$floatable
= $floatable
.addClass( 'oo-ui-floatableElement-floatable' );
6885 * Set floatable container.
6887 * The element will be always positioned under the specified container.
6889 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
6891 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableContainer = function ( $floatableContainer
) {
6892 this.$floatableContainer
= $floatableContainer
;
6893 if ( this.$floatable
) {
6899 * Toggle positioning.
6901 * Do not turn positioning on until after the element is attached to the DOM and visible.
6903 * @param {boolean} [positioning] Enable positioning, omit to toggle
6906 OO
.ui
.mixin
.FloatableElement
.prototype.togglePositioning = function ( positioning
) {
6907 var closestScrollableOfContainer
, closestScrollableOfFloatable
;
6909 positioning
= positioning
=== undefined ? !this.positioning
: !!positioning
;
6911 if ( this.positioning
!== positioning
) {
6912 this.positioning
= positioning
;
6914 closestScrollableOfContainer
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatableContainer
[ 0 ] );
6915 closestScrollableOfFloatable
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatable
[ 0 ] );
6916 if ( closestScrollableOfContainer
!== closestScrollableOfFloatable
) {
6917 // If the scrollable is the root, we have to listen to scroll events
6918 // on the window because of browser inconsistencies (or do we? someone should verify this)
6919 if ( $( closestScrollableOfContainer
).is( 'html, body' ) ) {
6920 closestScrollableOfContainer
= OO
.ui
.Element
.static.getWindow( closestScrollableOfContainer
);
6924 if ( positioning
) {
6925 this.$floatableWindow
= $( this.getElementWindow() );
6926 this.$floatableWindow
.on( 'resize', this.onFloatableWindowResizeHandler
);
6928 if ( closestScrollableOfContainer
!== closestScrollableOfFloatable
) {
6929 this.$floatableClosestScrollable
= $( closestScrollableOfContainer
);
6930 this.$floatableClosestScrollable
.on( 'scroll', this.onFloatableScrollHandler
);
6933 // Initial position after visible
6936 if ( this.$floatableWindow
) {
6937 this.$floatableWindow
.off( 'resize', this.onFloatableWindowResizeHandler
);
6938 this.$floatableWindow
= null;
6941 if ( this.$floatableClosestScrollable
) {
6942 this.$floatableClosestScrollable
.off( 'scroll', this.onFloatableScrollHandler
);
6943 this.$floatableClosestScrollable
= null;
6946 this.$floatable
.css( { left
: '', top
: '' } );
6954 * Position the floatable below its container.
6956 * This should only be done when both of them are attached to the DOM and visible.
6960 OO
.ui
.mixin
.FloatableElement
.prototype.position = function () {
6963 if ( !this.positioning
) {
6967 pos
= OO
.ui
.Element
.static.getRelativePosition( this.$floatableContainer
, this.$floatable
.offsetParent() );
6969 // Position under container
6970 pos
.top
+= this.$floatableContainer
.height();
6971 this.$floatable
.css( pos
);
6973 // We updated the position, so re-evaluate the clipping state.
6974 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
6975 // will not notice the need to update itself.)
6976 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
6977 // it not listen to the right events in the right places?
6986 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
6987 * Accesskeys allow an user to go to a specific element by using
6988 * a shortcut combination of a browser specific keys + the key
6992 * // AccessKeyedElement provides an 'accesskey' attribute to the
6993 * // ButtonWidget class
6994 * var button = new OO.ui.ButtonWidget( {
6995 * label: 'Button with Accesskey',
6998 * $( 'body' ).append( button.$element );
7004 * @param {Object} [config] Configuration options
7005 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
7006 * If this config is omitted, the accesskey functionality is applied to $element, the
7007 * element created by the class.
7008 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
7009 * this config is omitted, no accesskey will be added.
7011 OO
.ui
.mixin
.AccessKeyedElement
= function OoUiMixinAccessKeyedElement( config
) {
7012 // Configuration initialization
7013 config
= config
|| {};
7016 this.$accessKeyed
= null;
7017 this.accessKey
= null;
7020 this.setAccessKey( config
.accessKey
|| null );
7021 this.setAccessKeyedElement( config
.$accessKeyed
|| this.$element
);
7026 OO
.initClass( OO
.ui
.mixin
.AccessKeyedElement
);
7028 /* Static Properties */
7031 * The access key, a function that returns a key, or `null` for no accesskey.
7035 * @property {string|Function|null}
7037 OO
.ui
.mixin
.AccessKeyedElement
.static.accessKey
= null;
7042 * Set the accesskeyed element.
7044 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
7045 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
7047 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
7049 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKeyedElement = function ( $accessKeyed
) {
7050 if ( this.$accessKeyed
) {
7051 this.$accessKeyed
.removeAttr( 'accesskey' );
7054 this.$accessKeyed
= $accessKeyed
;
7055 if ( this.accessKey
) {
7056 this.$accessKeyed
.attr( 'accesskey', this.accessKey
);
7063 * @param {string|Function|null} accesskey Key, a function that returns a key, or `null` for no accesskey
7066 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKey = function ( accessKey
) {
7067 accessKey
= typeof accessKey
=== 'string' ? OO
.ui
.resolveMsg( accessKey
) : null;
7069 if ( this.accessKey
!== accessKey
) {
7070 if ( this.$accessKeyed
) {
7071 if ( accessKey
!== null ) {
7072 this.$accessKeyed
.attr( 'accesskey', accessKey
);
7074 this.$accessKeyed
.removeAttr( 'accesskey' );
7077 this.accessKey
= accessKey
;
7086 * @return {string} accessKey string
7088 OO
.ui
.mixin
.AccessKeyedElement
.prototype.getAccessKey = function () {
7089 return this.accessKey
;
7093 * Tools, together with {@link OO.ui.ToolGroup toolgroups}, constitute {@link OO.ui.Toolbar toolbars}.
7094 * Each tool is configured with a static name, title, and icon and is customized with the command to carry
7095 * out when the tool is selected. Tools must also be registered with a {@link OO.ui.ToolFactory tool factory},
7096 * which creates the tools on demand.
7098 * Tools are added to toolgroups ({@link OO.ui.ListToolGroup ListToolGroup},
7099 * {@link OO.ui.BarToolGroup BarToolGroup}, or {@link OO.ui.MenuToolGroup MenuToolGroup}), which determine how
7100 * the tool is displayed in the toolbar. See {@link OO.ui.Toolbar toolbars} for an example.
7102 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
7103 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7107 * @extends OO.ui.Widget
7108 * @mixins OO.ui.mixin.IconElement
7109 * @mixins OO.ui.mixin.FlaggedElement
7110 * @mixins OO.ui.mixin.TabIndexedElement
7113 * @param {OO.ui.ToolGroup} toolGroup
7114 * @param {Object} [config] Configuration options
7115 * @cfg {string|Function} [title] Title text or a function that returns text. If this config is omitted, the value of
7116 * the {@link #static-title static title} property is used.
7118 * The title is used in different ways depending on the type of toolgroup that contains the tool. The
7119 * 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
7120 * part of a {@link OO.ui.ListToolGroup list} or {@link OO.ui.MenuToolGroup menu} toolgroup.
7122 * For bar toolgroups, a description of the accelerator key is appended to the title if an accelerator key
7123 * is associated with an action by the same name as the tool and accelerator functionality has been added to the application.
7124 * To add accelerator key functionality, you must subclass OO.ui.Toolbar and override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method.
7126 OO
.ui
.Tool
= function OoUiTool( toolGroup
, config
) {
7127 // Allow passing positional parameters inside the config object
7128 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
7130 toolGroup
= config
.toolGroup
;
7133 // Configuration initialization
7134 config
= config
|| {};
7136 // Parent constructor
7137 OO
.ui
.Tool
.parent
.call( this, config
);
7140 this.toolGroup
= toolGroup
;
7141 this.toolbar
= this.toolGroup
.getToolbar();
7142 this.active
= false;
7143 this.$title
= $( '<span>' );
7144 this.$accel
= $( '<span>' );
7145 this.$link
= $( '<a>' );
7148 // Mixin constructors
7149 OO
.ui
.mixin
.IconElement
.call( this, config
);
7150 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
7151 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$link
} ) );
7154 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
7157 this.$title
.addClass( 'oo-ui-tool-title' );
7159 .addClass( 'oo-ui-tool-accel' )
7161 // This may need to be changed if the key names are ever localized,
7162 // but for now they are essentially written in English
7167 .addClass( 'oo-ui-tool-link' )
7168 .append( this.$icon
, this.$title
, this.$accel
)
7169 .attr( 'role', 'button' );
7171 .data( 'oo-ui-tool', this )
7173 'oo-ui-tool ' + 'oo-ui-tool-name-' +
7174 this.constructor.static.name
.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
7176 .toggleClass( 'oo-ui-tool-with-label', this.constructor.static.displayBothIconAndLabel
)
7177 .append( this.$link
);
7178 this.setTitle( config
.title
|| this.constructor.static.title
);
7183 OO
.inheritClass( OO
.ui
.Tool
, OO
.ui
.Widget
);
7184 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.IconElement
);
7185 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.FlaggedElement
);
7186 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.TabIndexedElement
);
7188 /* Static Properties */
7194 OO
.ui
.Tool
.static.tagName
= 'span';
7197 * Symbolic name of tool.
7199 * The symbolic name is used internally to register the tool with a {@link OO.ui.ToolFactory ToolFactory}. It can
7200 * also be used when adding tools to toolgroups.
7205 * @property {string}
7207 OO
.ui
.Tool
.static.name
= '';
7210 * Symbolic name of the group.
7212 * The group name is used to associate tools with each other so that they can be selected later by
7213 * a {@link OO.ui.ToolGroup toolgroup}.
7218 * @property {string}
7220 OO
.ui
.Tool
.static.group
= '';
7223 * 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.
7228 * @property {string|Function}
7230 OO
.ui
.Tool
.static.title
= '';
7233 * Display both icon and label when the tool is used in a {@link OO.ui.BarToolGroup bar} toolgroup.
7234 * Normally only the icon is displayed, or only the label if no icon is given.
7238 * @property {boolean}
7240 OO
.ui
.Tool
.static.displayBothIconAndLabel
= false;
7243 * Add tool to catch-all groups automatically.
7245 * A catch-all group, which contains all tools that do not currently belong to a toolgroup,
7246 * can be included in a toolgroup using the wildcard selector, an asterisk (*).
7250 * @property {boolean}
7252 OO
.ui
.Tool
.static.autoAddToCatchall
= true;
7255 * Add tool to named groups automatically.
7257 * By default, tools that are configured with a static ‘group’ property are added
7258 * to that group and will be selected when the symbolic name of the group is specified (e.g., when
7259 * toolgroups include tools by group name).
7262 * @property {boolean}
7265 OO
.ui
.Tool
.static.autoAddToGroup
= true;
7268 * Check if this tool is compatible with given data.
7270 * This is a stub that can be overriden to provide support for filtering tools based on an
7271 * arbitrary piece of information (e.g., where the cursor is in a document). The implementation
7272 * must also call this method so that the compatibility check can be performed.
7276 * @param {Mixed} data Data to check
7277 * @return {boolean} Tool can be used with data
7279 OO
.ui
.Tool
.static.isCompatibleWith = function () {
7286 * Handle the toolbar state being updated.
7288 * This is an abstract method that must be overridden in a concrete subclass.
7293 OO
.ui
.Tool
.prototype.onUpdateState = function () {
7295 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
7300 * Handle the tool being selected.
7302 * This is an abstract method that must be overridden in a concrete subclass.
7307 OO
.ui
.Tool
.prototype.onSelect = function () {
7309 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
7314 * Check if the tool is active.
7316 * Tools become active when their #onSelect or #onUpdateState handlers change them to appear pressed
7317 * with the #setActive method. Additional CSS is applied to the tool to reflect the active state.
7319 * @return {boolean} Tool is active
7321 OO
.ui
.Tool
.prototype.isActive = function () {
7326 * Make the tool appear active or inactive.
7328 * This method should be called within #onSelect or #onUpdateState event handlers to make the tool
7329 * appear pressed or not.
7331 * @param {boolean} state Make tool appear active
7333 OO
.ui
.Tool
.prototype.setActive = function ( state
) {
7334 this.active
= !!state
;
7335 if ( this.active
) {
7336 this.$element
.addClass( 'oo-ui-tool-active' );
7338 this.$element
.removeClass( 'oo-ui-tool-active' );
7343 * Set the tool #title.
7345 * @param {string|Function} title Title text or a function that returns text
7348 OO
.ui
.Tool
.prototype.setTitle = function ( title
) {
7349 this.title
= OO
.ui
.resolveMsg( title
);
7355 * Get the tool #title.
7357 * @return {string} Title text
7359 OO
.ui
.Tool
.prototype.getTitle = function () {
7364 * Get the tool's symbolic name.
7366 * @return {string} Symbolic name of tool
7368 OO
.ui
.Tool
.prototype.getName = function () {
7369 return this.constructor.static.name
;
7375 OO
.ui
.Tool
.prototype.updateTitle = function () {
7376 var titleTooltips
= this.toolGroup
.constructor.static.titleTooltips
,
7377 accelTooltips
= this.toolGroup
.constructor.static.accelTooltips
,
7378 accel
= this.toolbar
.getToolAccelerator( this.constructor.static.name
),
7381 this.$title
.text( this.title
);
7382 this.$accel
.text( accel
);
7384 if ( titleTooltips
&& typeof this.title
=== 'string' && this.title
.length
) {
7385 tooltipParts
.push( this.title
);
7387 if ( accelTooltips
&& typeof accel
=== 'string' && accel
.length
) {
7388 tooltipParts
.push( accel
);
7390 if ( tooltipParts
.length
) {
7391 this.$link
.attr( 'title', tooltipParts
.join( ' ' ) );
7393 this.$link
.removeAttr( 'title' );
7400 * Destroying the tool removes all event handlers and the tool’s DOM elements.
7401 * Call this method whenever you are done using a tool.
7403 OO
.ui
.Tool
.prototype.destroy = function () {
7404 this.toolbar
.disconnect( this );
7405 this.$element
.remove();
7409 * Toolbars are complex interface components that permit users to easily access a variety
7410 * of {@link OO.ui.Tool tools} (e.g., formatting commands) and actions, which are additional commands that are
7411 * part of the toolbar, but not configured as tools.
7413 * Individual tools are customized and then registered with a {@link OO.ui.ToolFactory tool factory}, which creates
7414 * the tools on demand. Each tool has a symbolic name (used when registering the tool), a title (e.g., ‘Insert
7415 * picture’), and an icon.
7417 * Individual tools are organized in {@link OO.ui.ToolGroup toolgroups}, which can be {@link OO.ui.MenuToolGroup menus}
7418 * of tools, {@link OO.ui.ListToolGroup lists} of tools, or a single {@link OO.ui.BarToolGroup bar} of tools.
7419 * The arrangement and order of the toolgroups is customized when the toolbar is set up. Tools can be presented in
7420 * any order, but each can only appear once in the toolbar.
7422 * The following is an example of a basic toolbar.
7425 * // Example of a toolbar
7426 * // Create the toolbar
7427 * var toolFactory = new OO.ui.ToolFactory();
7428 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7429 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7431 * // We will be placing status text in this element when tools are used
7432 * var $area = $( '<p>' ).text( 'Toolbar example' );
7434 * // Define the tools that we're going to place in our toolbar
7436 * // Create a class inheriting from OO.ui.Tool
7437 * function PictureTool() {
7438 * PictureTool.parent.apply( this, arguments );
7440 * OO.inheritClass( PictureTool, OO.ui.Tool );
7441 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7442 * // of 'icon' and 'title' (displayed icon and text).
7443 * PictureTool.static.name = 'picture';
7444 * PictureTool.static.icon = 'picture';
7445 * PictureTool.static.title = 'Insert picture';
7446 * // Defines the action that will happen when this tool is selected (clicked).
7447 * PictureTool.prototype.onSelect = function () {
7448 * $area.text( 'Picture tool clicked!' );
7449 * // Never display this tool as "active" (selected).
7450 * this.setActive( false );
7452 * // Make this tool available in our toolFactory and thus our toolbar
7453 * toolFactory.register( PictureTool );
7455 * // Register two more tools, nothing interesting here
7456 * function SettingsTool() {
7457 * SettingsTool.parent.apply( this, arguments );
7459 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7460 * SettingsTool.static.name = 'settings';
7461 * SettingsTool.static.icon = 'settings';
7462 * SettingsTool.static.title = 'Change settings';
7463 * SettingsTool.prototype.onSelect = function () {
7464 * $area.text( 'Settings tool clicked!' );
7465 * this.setActive( false );
7467 * toolFactory.register( SettingsTool );
7469 * // Register two more tools, nothing interesting here
7470 * function StuffTool() {
7471 * StuffTool.parent.apply( this, arguments );
7473 * OO.inheritClass( StuffTool, OO.ui.Tool );
7474 * StuffTool.static.name = 'stuff';
7475 * StuffTool.static.icon = 'ellipsis';
7476 * StuffTool.static.title = 'More stuff';
7477 * StuffTool.prototype.onSelect = function () {
7478 * $area.text( 'More stuff tool clicked!' );
7479 * this.setActive( false );
7481 * toolFactory.register( StuffTool );
7483 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7484 * // little popup window (a PopupWidget).
7485 * function HelpTool( toolGroup, config ) {
7486 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7491 * this.popup.$body.append( '<p>I am helpful!</p>' );
7493 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7494 * HelpTool.static.name = 'help';
7495 * HelpTool.static.icon = 'help';
7496 * HelpTool.static.title = 'Help';
7497 * toolFactory.register( HelpTool );
7499 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7500 * // used once (but not all defined tools must be used).
7503 * // 'bar' tool groups display tools' icons only, side-by-side.
7505 * include: [ 'picture', 'help' ]
7508 * // 'list' tool groups display both the titles and icons, in a dropdown list.
7510 * indicator: 'down',
7512 * include: [ 'settings', 'stuff' ]
7514 * // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed
7515 * // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here,
7516 * // since it's more complicated to use. (See the next example snippet on this page.)
7519 * // Create some UI around the toolbar and place it in the document
7520 * var frame = new OO.ui.PanelLayout( {
7524 * var contentFrame = new OO.ui.PanelLayout( {
7528 * frame.$element.append(
7530 * contentFrame.$element.append( $area )
7532 * $( 'body' ).append( frame.$element );
7534 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7536 * toolbar.initialize();
7538 * The following example extends the previous one to illustrate 'menu' toolgroups and the usage of
7539 * 'updateState' event.
7542 * // Create the toolbar
7543 * var toolFactory = new OO.ui.ToolFactory();
7544 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7545 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7547 * // We will be placing status text in this element when tools are used
7548 * var $area = $( '<p>' ).text( 'Toolbar example' );
7550 * // Define the tools that we're going to place in our toolbar
7552 * // Create a class inheriting from OO.ui.Tool
7553 * function PictureTool() {
7554 * PictureTool.parent.apply( this, arguments );
7556 * OO.inheritClass( PictureTool, OO.ui.Tool );
7557 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7558 * // of 'icon' and 'title' (displayed icon and text).
7559 * PictureTool.static.name = 'picture';
7560 * PictureTool.static.icon = 'picture';
7561 * PictureTool.static.title = 'Insert picture';
7562 * // Defines the action that will happen when this tool is selected (clicked).
7563 * PictureTool.prototype.onSelect = function () {
7564 * $area.text( 'Picture tool clicked!' );
7565 * // Never display this tool as "active" (selected).
7566 * this.setActive( false );
7568 * // The toolbar can be synchronized with the state of some external stuff, like a text
7569 * // editor's editing area, highlighting the tools (e.g. a 'bold' tool would be shown as active
7570 * // when the text cursor was inside bolded text). Here we simply disable this feature.
7571 * PictureTool.prototype.onUpdateState = function () {
7573 * // Make this tool available in our toolFactory and thus our toolbar
7574 * toolFactory.register( PictureTool );
7576 * // Register two more tools, nothing interesting here
7577 * function SettingsTool() {
7578 * SettingsTool.parent.apply( this, arguments );
7579 * this.reallyActive = false;
7581 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7582 * SettingsTool.static.name = 'settings';
7583 * SettingsTool.static.icon = 'settings';
7584 * SettingsTool.static.title = 'Change settings';
7585 * SettingsTool.prototype.onSelect = function () {
7586 * $area.text( 'Settings tool clicked!' );
7587 * // Toggle the active state on each click
7588 * this.reallyActive = !this.reallyActive;
7589 * this.setActive( this.reallyActive );
7590 * // To update the menu label
7591 * this.toolbar.emit( 'updateState' );
7593 * SettingsTool.prototype.onUpdateState = function () {
7595 * toolFactory.register( SettingsTool );
7597 * // Register two more tools, nothing interesting here
7598 * function StuffTool() {
7599 * StuffTool.parent.apply( this, arguments );
7600 * this.reallyActive = false;
7602 * OO.inheritClass( StuffTool, OO.ui.Tool );
7603 * StuffTool.static.name = 'stuff';
7604 * StuffTool.static.icon = 'ellipsis';
7605 * StuffTool.static.title = 'More stuff';
7606 * StuffTool.prototype.onSelect = function () {
7607 * $area.text( 'More stuff tool clicked!' );
7608 * // Toggle the active state on each click
7609 * this.reallyActive = !this.reallyActive;
7610 * this.setActive( this.reallyActive );
7611 * // To update the menu label
7612 * this.toolbar.emit( 'updateState' );
7614 * StuffTool.prototype.onUpdateState = function () {
7616 * toolFactory.register( StuffTool );
7618 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7619 * // little popup window (a PopupWidget). 'onUpdateState' is also already implemented.
7620 * function HelpTool( toolGroup, config ) {
7621 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7626 * this.popup.$body.append( '<p>I am helpful!</p>' );
7628 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7629 * HelpTool.static.name = 'help';
7630 * HelpTool.static.icon = 'help';
7631 * HelpTool.static.title = 'Help';
7632 * toolFactory.register( HelpTool );
7634 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7635 * // used once (but not all defined tools must be used).
7638 * // 'bar' tool groups display tools' icons only, side-by-side.
7640 * include: [ 'picture', 'help' ]
7643 * // 'menu' tool groups display both the titles and icons, in a dropdown menu.
7644 * // Menu label indicates which items are selected.
7646 * indicator: 'down',
7647 * include: [ 'settings', 'stuff' ]
7651 * // Create some UI around the toolbar and place it in the document
7652 * var frame = new OO.ui.PanelLayout( {
7656 * var contentFrame = new OO.ui.PanelLayout( {
7660 * frame.$element.append(
7662 * contentFrame.$element.append( $area )
7664 * $( 'body' ).append( frame.$element );
7666 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7668 * toolbar.initialize();
7669 * toolbar.emit( 'updateState' );
7672 * @extends OO.ui.Element
7673 * @mixins OO.EventEmitter
7674 * @mixins OO.ui.mixin.GroupElement
7677 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
7678 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating toolgroups
7679 * @param {Object} [config] Configuration options
7680 * @cfg {boolean} [actions] Add an actions section to the toolbar. Actions are commands that are included
7681 * in the toolbar, but are not configured as tools. By default, actions are displayed on the right side of
7683 * @cfg {boolean} [shadow] Add a shadow below the toolbar.
7685 OO
.ui
.Toolbar
= function OoUiToolbar( toolFactory
, toolGroupFactory
, config
) {
7686 // Allow passing positional parameters inside the config object
7687 if ( OO
.isPlainObject( toolFactory
) && config
=== undefined ) {
7688 config
= toolFactory
;
7689 toolFactory
= config
.toolFactory
;
7690 toolGroupFactory
= config
.toolGroupFactory
;
7693 // Configuration initialization
7694 config
= config
|| {};
7696 // Parent constructor
7697 OO
.ui
.Toolbar
.parent
.call( this, config
);
7699 // Mixin constructors
7700 OO
.EventEmitter
.call( this );
7701 OO
.ui
.mixin
.GroupElement
.call( this, config
);
7704 this.toolFactory
= toolFactory
;
7705 this.toolGroupFactory
= toolGroupFactory
;
7708 this.$bar
= $( '<div>' );
7709 this.$actions
= $( '<div>' );
7710 this.initialized
= false;
7711 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
7715 .add( this.$bar
).add( this.$group
).add( this.$actions
)
7716 .on( 'mousedown keydown', this.onPointerDown
.bind( this ) );
7719 this.$group
.addClass( 'oo-ui-toolbar-tools' );
7720 if ( config
.actions
) {
7721 this.$bar
.append( this.$actions
.addClass( 'oo-ui-toolbar-actions' ) );
7724 .addClass( 'oo-ui-toolbar-bar' )
7725 .append( this.$group
, '<div style="clear:both"></div>' );
7726 if ( config
.shadow
) {
7727 this.$bar
.append( '<div class="oo-ui-toolbar-shadow"></div>' );
7729 this.$element
.addClass( 'oo-ui-toolbar' ).append( this.$bar
);
7734 OO
.inheritClass( OO
.ui
.Toolbar
, OO
.ui
.Element
);
7735 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.EventEmitter
);
7736 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.ui
.mixin
.GroupElement
);
7741 * Get the tool factory.
7743 * @return {OO.ui.ToolFactory} Tool factory
7745 OO
.ui
.Toolbar
.prototype.getToolFactory = function () {
7746 return this.toolFactory
;
7750 * Get the toolgroup factory.
7752 * @return {OO.Factory} Toolgroup factory
7754 OO
.ui
.Toolbar
.prototype.getToolGroupFactory = function () {
7755 return this.toolGroupFactory
;
7759 * Handles mouse down events.
7762 * @param {jQuery.Event} e Mouse down event
7764 OO
.ui
.Toolbar
.prototype.onPointerDown = function ( e
) {
7765 var $closestWidgetToEvent
= $( e
.target
).closest( '.oo-ui-widget' ),
7766 $closestWidgetToToolbar
= this.$element
.closest( '.oo-ui-widget' );
7767 if ( !$closestWidgetToEvent
.length
|| $closestWidgetToEvent
[ 0 ] === $closestWidgetToToolbar
[ 0 ] ) {
7773 * Handle window resize event.
7776 * @param {jQuery.Event} e Window resize event
7778 OO
.ui
.Toolbar
.prototype.onWindowResize = function () {
7779 this.$element
.toggleClass(
7780 'oo-ui-toolbar-narrow',
7781 this.$bar
.width() <= this.narrowThreshold
7786 * Sets up handles and preloads required information for the toolbar to work.
7787 * This must be called after it is attached to a visible document and before doing anything else.
7789 OO
.ui
.Toolbar
.prototype.initialize = function () {
7790 if ( !this.initialized
) {
7791 this.initialized
= true;
7792 this.narrowThreshold
= this.$group
.width() + this.$actions
.width();
7793 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler
);
7794 this.onWindowResize();
7799 * Set up the toolbar.
7801 * The toolbar is set up with a list of toolgroup configurations that specify the type of
7802 * toolgroup ({@link OO.ui.BarToolGroup bar}, {@link OO.ui.MenuToolGroup menu}, or {@link OO.ui.ListToolGroup list})
7803 * to add and which tools to include, exclude, promote, or demote within that toolgroup. Please
7804 * see {@link OO.ui.ToolGroup toolgroups} for more information about including tools in toolgroups.
7806 * @param {Object.<string,Array>} groups List of toolgroup configurations
7807 * @param {Array|string} [groups.include] Tools to include in the toolgroup
7808 * @param {Array|string} [groups.exclude] Tools to exclude from the toolgroup
7809 * @param {Array|string} [groups.promote] Tools to promote to the beginning of the toolgroup
7810 * @param {Array|string} [groups.demote] Tools to demote to the end of the toolgroup
7812 OO
.ui
.Toolbar
.prototype.setup = function ( groups
) {
7813 var i
, len
, type
, group
,
7815 defaultType
= 'bar';
7817 // Cleanup previous groups
7820 // Build out new groups
7821 for ( i
= 0, len
= groups
.length
; i
< len
; i
++ ) {
7822 group
= groups
[ i
];
7823 if ( group
.include
=== '*' ) {
7824 // Apply defaults to catch-all groups
7825 if ( group
.type
=== undefined ) {
7826 group
.type
= 'list';
7828 if ( group
.label
=== undefined ) {
7829 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
7832 // Check type has been registered
7833 type
= this.getToolGroupFactory().lookup( group
.type
) ? group
.type
: defaultType
;
7835 this.getToolGroupFactory().create( type
, this, group
)
7838 this.addItems( items
);
7842 * Remove all tools and toolgroups from the toolbar.
7844 OO
.ui
.Toolbar
.prototype.reset = function () {
7849 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
7850 this.items
[ i
].destroy();
7856 * Destroy the toolbar.
7858 * Destroying the toolbar removes all event handlers and DOM elements that constitute the toolbar. Call
7859 * this method whenever you are done using a toolbar.
7861 OO
.ui
.Toolbar
.prototype.destroy = function () {
7862 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler
);
7864 this.$element
.remove();
7868 * Check if the tool is available.
7870 * Available tools are ones that have not yet been added to the toolbar.
7872 * @param {string} name Symbolic name of tool
7873 * @return {boolean} Tool is available
7875 OO
.ui
.Toolbar
.prototype.isToolAvailable = function ( name
) {
7876 return !this.tools
[ name
];
7880 * Prevent tool from being used again.
7882 * @param {OO.ui.Tool} tool Tool to reserve
7884 OO
.ui
.Toolbar
.prototype.reserveTool = function ( tool
) {
7885 this.tools
[ tool
.getName() ] = tool
;
7889 * Allow tool to be used again.
7891 * @param {OO.ui.Tool} tool Tool to release
7893 OO
.ui
.Toolbar
.prototype.releaseTool = function ( tool
) {
7894 delete this.tools
[ tool
.getName() ];
7898 * Get accelerator label for tool.
7900 * The OOjs UI library does not contain an accelerator system, but this is the hook for one. To
7901 * use an accelerator system, subclass the toolbar and override this method, which is meant to return a label
7902 * that describes the accelerator keys for the tool passed (by symbolic name) to the method.
7904 * @param {string} name Symbolic name of tool
7905 * @return {string|undefined} Tool accelerator label if available
7907 OO
.ui
.Toolbar
.prototype.getToolAccelerator = function () {
7912 * ToolGroups are collections of {@link OO.ui.Tool tools} that are used in a {@link OO.ui.Toolbar toolbar}.
7913 * The type of toolgroup ({@link OO.ui.ListToolGroup list}, {@link OO.ui.BarToolGroup bar}, or {@link OO.ui.MenuToolGroup menu})
7914 * to which a tool belongs determines how the tool is arranged and displayed in the toolbar. Toolgroups
7915 * themselves are created on demand with a {@link OO.ui.ToolGroupFactory toolgroup factory}.
7917 * Toolgroups can contain individual tools, groups of tools, or all available tools:
7919 * To include an individual tool (or array of individual tools), specify tools by symbolic name:
7921 * include: [ 'tool-name' ] or [ { name: 'tool-name' }]
7923 * 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.)
7925 * include: [ { group: 'group-name' } ]
7927 * To include all tools that are not yet assigned to a toolgroup, use the catch-all selector, an asterisk (*):
7931 * See {@link OO.ui.Toolbar toolbars} for a full example. For more information about toolbars in general,
7932 * please see the [OOjs UI documentation on MediaWiki][1].
7934 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7938 * @extends OO.ui.Widget
7939 * @mixins OO.ui.mixin.GroupElement
7942 * @param {OO.ui.Toolbar} toolbar
7943 * @param {Object} [config] Configuration options
7944 * @cfg {Array|string} [include=[]] List of tools to include in the toolgroup.
7945 * @cfg {Array|string} [exclude=[]] List of tools to exclude from the toolgroup.
7946 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning of the toolgroup.
7947 * @cfg {Array|string} [demote=[]] List of tools to demote to the end of the toolgroup.
7948 * This setting is particularly useful when tools have been added to the toolgroup
7949 * en masse (e.g., via the catch-all selector).
7951 OO
.ui
.ToolGroup
= function OoUiToolGroup( toolbar
, config
) {
7952 // Allow passing positional parameters inside the config object
7953 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
7955 toolbar
= config
.toolbar
;
7958 // Configuration initialization
7959 config
= config
|| {};
7961 // Parent constructor
7962 OO
.ui
.ToolGroup
.parent
.call( this, config
);
7964 // Mixin constructors
7965 OO
.ui
.mixin
.GroupElement
.call( this, config
);
7968 this.toolbar
= toolbar
;
7970 this.pressed
= null;
7971 this.autoDisabled
= false;
7972 this.include
= config
.include
|| [];
7973 this.exclude
= config
.exclude
|| [];
7974 this.promote
= config
.promote
|| [];
7975 this.demote
= config
.demote
|| [];
7976 this.onCapturedMouseKeyUpHandler
= this.onCapturedMouseKeyUp
.bind( this );
7980 mousedown
: this.onMouseKeyDown
.bind( this ),
7981 mouseup
: this.onMouseKeyUp
.bind( this ),
7982 keydown
: this.onMouseKeyDown
.bind( this ),
7983 keyup
: this.onMouseKeyUp
.bind( this ),
7984 focus
: this.onMouseOverFocus
.bind( this ),
7985 blur
: this.onMouseOutBlur
.bind( this ),
7986 mouseover
: this.onMouseOverFocus
.bind( this ),
7987 mouseout
: this.onMouseOutBlur
.bind( this )
7989 this.toolbar
.getToolFactory().connect( this, { register
: 'onToolFactoryRegister' } );
7990 this.aggregate( { disable
: 'itemDisable' } );
7991 this.connect( this, { itemDisable
: 'updateDisabled' } );
7994 this.$group
.addClass( 'oo-ui-toolGroup-tools' );
7996 .addClass( 'oo-ui-toolGroup' )
7997 .append( this.$group
);
8003 OO
.inheritClass( OO
.ui
.ToolGroup
, OO
.ui
.Widget
);
8004 OO
.mixinClass( OO
.ui
.ToolGroup
, OO
.ui
.mixin
.GroupElement
);
8012 /* Static Properties */
8015 * Show labels in tooltips.
8019 * @property {boolean}
8021 OO
.ui
.ToolGroup
.static.titleTooltips
= false;
8024 * Show acceleration labels in tooltips.
8026 * Note: The OOjs UI library does not include an accelerator system, but does contain
8027 * a hook for one. To use an accelerator system, subclass the {@link OO.ui.Toolbar toolbar} and
8028 * override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method, which is
8029 * meant to return a label that describes the accelerator keys for a given tool (e.g., 'Ctrl + M').
8033 * @property {boolean}
8035 OO
.ui
.ToolGroup
.static.accelTooltips
= false;
8038 * Automatically disable the toolgroup when all tools are disabled
8042 * @property {boolean}
8044 OO
.ui
.ToolGroup
.static.autoDisable
= true;
8051 OO
.ui
.ToolGroup
.prototype.isDisabled = function () {
8052 return this.autoDisabled
|| OO
.ui
.ToolGroup
.parent
.prototype.isDisabled
.apply( this, arguments
);
8058 OO
.ui
.ToolGroup
.prototype.updateDisabled = function () {
8059 var i
, item
, allDisabled
= true;
8061 if ( this.constructor.static.autoDisable
) {
8062 for ( i
= this.items
.length
- 1; i
>= 0; i
-- ) {
8063 item
= this.items
[ i
];
8064 if ( !item
.isDisabled() ) {
8065 allDisabled
= false;
8069 this.autoDisabled
= allDisabled
;
8071 OO
.ui
.ToolGroup
.parent
.prototype.updateDisabled
.apply( this, arguments
);
8075 * Handle mouse down and key down events.
8078 * @param {jQuery.Event} e Mouse down or key down event
8080 OO
.ui
.ToolGroup
.prototype.onMouseKeyDown = function ( e
) {
8082 !this.isDisabled() &&
8083 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
8085 this.pressed
= this.getTargetTool( e
);
8086 if ( this.pressed
) {
8087 this.pressed
.setActive( true );
8088 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler
);
8089 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler
);
8096 * Handle captured mouse up and key up events.
8099 * @param {Event} e Mouse up or key up event
8101 OO
.ui
.ToolGroup
.prototype.onCapturedMouseKeyUp = function ( e
) {
8102 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler
);
8103 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler
);
8104 // onMouseKeyUp may be called a second time, depending on where the mouse is when the button is
8105 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
8106 this.onMouseKeyUp( e
);
8110 * Handle mouse up and key up events.
8113 * @param {jQuery.Event} e Mouse up or key up event
8115 OO
.ui
.ToolGroup
.prototype.onMouseKeyUp = function ( e
) {
8116 var tool
= this.getTargetTool( e
);
8119 !this.isDisabled() && this.pressed
&& this.pressed
=== tool
&&
8120 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
8122 this.pressed
.onSelect();
8123 this.pressed
= null;
8127 this.pressed
= null;
8131 * Handle mouse over and focus events.
8134 * @param {jQuery.Event} e Mouse over or focus event
8136 OO
.ui
.ToolGroup
.prototype.onMouseOverFocus = function ( e
) {
8137 var tool
= this.getTargetTool( e
);
8139 if ( this.pressed
&& this.pressed
=== tool
) {
8140 this.pressed
.setActive( true );
8145 * Handle mouse out and blur events.
8148 * @param {jQuery.Event} e Mouse out or blur event
8150 OO
.ui
.ToolGroup
.prototype.onMouseOutBlur = function ( e
) {
8151 var tool
= this.getTargetTool( e
);
8153 if ( this.pressed
&& this.pressed
=== tool
) {
8154 this.pressed
.setActive( false );
8159 * Get the closest tool to a jQuery.Event.
8161 * Only tool links are considered, which prevents other elements in the tool such as popups from
8162 * triggering tool group interactions.
8165 * @param {jQuery.Event} e
8166 * @return {OO.ui.Tool|null} Tool, `null` if none was found
8168 OO
.ui
.ToolGroup
.prototype.getTargetTool = function ( e
) {
8170 $item
= $( e
.target
).closest( '.oo-ui-tool-link' );
8172 if ( $item
.length
) {
8173 tool
= $item
.parent().data( 'oo-ui-tool' );
8176 return tool
&& !tool
.isDisabled() ? tool
: null;
8180 * Handle tool registry register events.
8182 * If a tool is registered after the group is created, we must repopulate the list to account for:
8184 * - a tool being added that may be included
8185 * - a tool already included being overridden
8188 * @param {string} name Symbolic name of tool
8190 OO
.ui
.ToolGroup
.prototype.onToolFactoryRegister = function () {
8195 * Get the toolbar that contains the toolgroup.
8197 * @return {OO.ui.Toolbar} Toolbar that contains the toolgroup
8199 OO
.ui
.ToolGroup
.prototype.getToolbar = function () {
8200 return this.toolbar
;
8204 * Add and remove tools based on configuration.
8206 OO
.ui
.ToolGroup
.prototype.populate = function () {
8207 var i
, len
, name
, tool
,
8208 toolFactory
= this.toolbar
.getToolFactory(),
8212 list
= this.toolbar
.getToolFactory().getTools(
8213 this.include
, this.exclude
, this.promote
, this.demote
8216 // Build a list of needed tools
8217 for ( i
= 0, len
= list
.length
; i
< len
; i
++ ) {
8221 toolFactory
.lookup( name
) &&
8222 // Tool is available or is already in this group
8223 ( this.toolbar
.isToolAvailable( name
) || this.tools
[ name
] )
8225 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
8226 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
8227 this.toolbar
.tools
[ name
] = true;
8228 tool
= this.tools
[ name
];
8230 // Auto-initialize tools on first use
8231 this.tools
[ name
] = tool
= toolFactory
.create( name
, this );
8234 this.toolbar
.reserveTool( tool
);
8236 names
[ name
] = true;
8239 // Remove tools that are no longer needed
8240 for ( name
in this.tools
) {
8241 if ( !names
[ name
] ) {
8242 this.tools
[ name
].destroy();
8243 this.toolbar
.releaseTool( this.tools
[ name
] );
8244 remove
.push( this.tools
[ name
] );
8245 delete this.tools
[ name
];
8248 if ( remove
.length
) {
8249 this.removeItems( remove
);
8251 // Update emptiness state
8253 this.$element
.removeClass( 'oo-ui-toolGroup-empty' );
8255 this.$element
.addClass( 'oo-ui-toolGroup-empty' );
8257 // Re-add tools (moving existing ones to new locations)
8258 this.addItems( add
);
8259 // Disabled state may depend on items
8260 this.updateDisabled();
8264 * Destroy toolgroup.
8266 OO
.ui
.ToolGroup
.prototype.destroy = function () {
8270 this.toolbar
.getToolFactory().disconnect( this );
8271 for ( name
in this.tools
) {
8272 this.toolbar
.releaseTool( this.tools
[ name
] );
8273 this.tools
[ name
].disconnect( this ).destroy();
8274 delete this.tools
[ name
];
8276 this.$element
.remove();
8280 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
8281 * consists of a header that contains the dialog title, a body with the message, and a footer that
8282 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
8283 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
8285 * There are two basic types of message dialogs, confirmation and alert:
8287 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
8288 * more details about the consequences.
8289 * - **alert**: the dialog title describes which event occurred and the message provides more information
8290 * about why the event occurred.
8292 * The MessageDialog class specifies two actions: ‘accept’, the primary
8293 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
8294 * passing along the selected action.
8296 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
8299 * // Example: Creating and opening a message dialog window.
8300 * var messageDialog = new OO.ui.MessageDialog();
8302 * // Create and append a window manager.
8303 * var windowManager = new OO.ui.WindowManager();
8304 * $( 'body' ).append( windowManager.$element );
8305 * windowManager.addWindows( [ messageDialog ] );
8306 * // Open the window.
8307 * windowManager.openWindow( messageDialog, {
8308 * title: 'Basic message dialog',
8309 * message: 'This is the message'
8312 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
8315 * @extends OO.ui.Dialog
8318 * @param {Object} [config] Configuration options
8320 OO
.ui
.MessageDialog
= function OoUiMessageDialog( config
) {
8321 // Parent constructor
8322 OO
.ui
.MessageDialog
.parent
.call( this, config
);
8325 this.verticalActionLayout
= null;
8328 this.$element
.addClass( 'oo-ui-messageDialog' );
8333 OO
.inheritClass( OO
.ui
.MessageDialog
, OO
.ui
.Dialog
);
8335 /* Static Properties */
8337 OO
.ui
.MessageDialog
.static.name
= 'message';
8339 OO
.ui
.MessageDialog
.static.size
= 'small';
8341 OO
.ui
.MessageDialog
.static.verbose
= false;
8346 * The title of a confirmation dialog describes what a progressive action will do. The
8347 * title of an alert dialog describes which event occurred.
8351 * @property {jQuery|string|Function|null}
8353 OO
.ui
.MessageDialog
.static.title
= null;
8356 * The message displayed in the dialog body.
8358 * A confirmation message describes the consequences of a progressive action. An alert
8359 * message describes why an event occurred.
8363 * @property {jQuery|string|Function|null}
8365 OO
.ui
.MessageDialog
.static.message
= null;
8367 OO
.ui
.MessageDialog
.static.actions
= [
8368 { action
: 'accept', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-accept' ), flags
: 'primary' },
8369 { action
: 'reject', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-reject' ), flags
: 'safe' }
8377 OO
.ui
.MessageDialog
.prototype.setManager = function ( manager
) {
8378 OO
.ui
.MessageDialog
.parent
.prototype.setManager
.call( this, manager
);
8381 this.manager
.connect( this, {
8391 OO
.ui
.MessageDialog
.prototype.onActionResize = function ( action
) {
8393 return OO
.ui
.MessageDialog
.parent
.prototype.onActionResize
.call( this, action
);
8397 * Handle window resized events.
8401 OO
.ui
.MessageDialog
.prototype.onResize = function () {
8403 dialog
.fitActions();
8404 // Wait for CSS transition to finish and do it again :(
8405 setTimeout( function () {
8406 dialog
.fitActions();
8411 * Toggle action layout between vertical and horizontal.
8414 * @param {boolean} [value] Layout actions vertically, omit to toggle
8417 OO
.ui
.MessageDialog
.prototype.toggleVerticalActionLayout = function ( value
) {
8418 value
= value
=== undefined ? !this.verticalActionLayout
: !!value
;
8420 if ( value
!== this.verticalActionLayout
) {
8421 this.verticalActionLayout
= value
;
8423 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value
)
8424 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value
);
8433 OO
.ui
.MessageDialog
.prototype.getActionProcess = function ( action
) {
8435 return new OO
.ui
.Process( function () {
8436 this.close( { action
: action
} );
8439 return OO
.ui
.MessageDialog
.parent
.prototype.getActionProcess
.call( this, action
);
8445 * @param {Object} [data] Dialog opening data
8446 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
8447 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
8448 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
8449 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
8452 OO
.ui
.MessageDialog
.prototype.getSetupProcess = function ( data
) {
8456 return OO
.ui
.MessageDialog
.parent
.prototype.getSetupProcess
.call( this, data
)
8457 .next( function () {
8458 this.title
.setLabel(
8459 data
.title
!== undefined ? data
.title
: this.constructor.static.title
8461 this.message
.setLabel(
8462 data
.message
!== undefined ? data
.message
: this.constructor.static.message
8464 this.message
.$element
.toggleClass(
8465 'oo-ui-messageDialog-message-verbose',
8466 data
.verbose
!== undefined ? data
.verbose
: this.constructor.static.verbose
8474 OO
.ui
.MessageDialog
.prototype.getReadyProcess = function ( data
) {
8478 return OO
.ui
.MessageDialog
.parent
.prototype.getReadyProcess
.call( this, data
)
8479 .next( function () {
8480 // Focus the primary action button
8481 var actions
= this.actions
.get();
8482 actions
= actions
.filter( function ( action
) {
8483 return action
.getFlags().indexOf( 'primary' ) > -1;
8485 if ( actions
.length
> 0 ) {
8486 actions
[ 0 ].$button
.focus();
8494 OO
.ui
.MessageDialog
.prototype.getBodyHeight = function () {
8495 var bodyHeight
, oldOverflow
,
8496 $scrollable
= this.container
.$element
;
8498 oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
8499 $scrollable
[ 0 ].style
.overflow
= 'hidden';
8501 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
8503 bodyHeight
= this.text
.$element
.outerHeight( true );
8504 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
8512 OO
.ui
.MessageDialog
.prototype.setDimensions = function ( dim
) {
8513 var $scrollable
= this.container
.$element
;
8514 OO
.ui
.MessageDialog
.parent
.prototype.setDimensions
.call( this, dim
);
8516 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
8517 // Need to do it after transition completes (250ms), add 50ms just in case.
8518 setTimeout( function () {
8519 var oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
8520 $scrollable
[ 0 ].style
.overflow
= 'hidden';
8522 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
8524 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
8533 OO
.ui
.MessageDialog
.prototype.initialize = function () {
8535 OO
.ui
.MessageDialog
.parent
.prototype.initialize
.call( this );
8538 this.$actions
= $( '<div>' );
8539 this.container
= new OO
.ui
.PanelLayout( {
8540 scrollable
: true, classes
: [ 'oo-ui-messageDialog-container' ]
8542 this.text
= new OO
.ui
.PanelLayout( {
8543 padded
: true, expanded
: false, classes
: [ 'oo-ui-messageDialog-text' ]
8545 this.message
= new OO
.ui
.LabelWidget( {
8546 classes
: [ 'oo-ui-messageDialog-message' ]
8550 this.title
.$element
.addClass( 'oo-ui-messageDialog-title' );
8551 this.$content
.addClass( 'oo-ui-messageDialog-content' );
8552 this.container
.$element
.append( this.text
.$element
);
8553 this.text
.$element
.append( this.title
.$element
, this.message
.$element
);
8554 this.$body
.append( this.container
.$element
);
8555 this.$actions
.addClass( 'oo-ui-messageDialog-actions' );
8556 this.$foot
.append( this.$actions
);
8562 OO
.ui
.MessageDialog
.prototype.attachActions = function () {
8563 var i
, len
, other
, special
, others
;
8566 OO
.ui
.MessageDialog
.parent
.prototype.attachActions
.call( this );
8568 special
= this.actions
.getSpecial();
8569 others
= this.actions
.getOthers();
8571 if ( special
.safe
) {
8572 this.$actions
.append( special
.safe
.$element
);
8573 special
.safe
.toggleFramed( false );
8575 if ( others
.length
) {
8576 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
8577 other
= others
[ i
];
8578 this.$actions
.append( other
.$element
);
8579 other
.toggleFramed( false );
8582 if ( special
.primary
) {
8583 this.$actions
.append( special
.primary
.$element
);
8584 special
.primary
.toggleFramed( false );
8587 if ( !this.isOpening() ) {
8588 // If the dialog is currently opening, this will be called automatically soon.
8589 // This also calls #fitActions.
8595 * Fit action actions into columns or rows.
8597 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
8601 OO
.ui
.MessageDialog
.prototype.fitActions = function () {
8603 previous
= this.verticalActionLayout
,
8604 actions
= this.actions
.get();
8607 this.toggleVerticalActionLayout( false );
8608 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
8609 action
= actions
[ i
];
8610 if ( action
.$element
.innerWidth() < action
.$label
.outerWidth( true ) ) {
8611 this.toggleVerticalActionLayout( true );
8616 // Move the body out of the way of the foot
8617 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
8619 if ( this.verticalActionLayout
!== previous
) {
8620 // We changed the layout, window height might need to be updated.
8626 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
8627 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
8628 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
8629 * relevant. The ProcessDialog class is always extended and customized with the actions and content
8630 * required for each process.
8632 * The process dialog box consists of a header that visually represents the ‘working’ state of long
8633 * processes with an animation. The header contains the dialog title as well as
8634 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
8635 * a ‘primary’ action on the right (e.g., ‘Done’).
8637 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
8638 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
8641 * // Example: Creating and opening a process dialog window.
8642 * function MyProcessDialog( config ) {
8643 * MyProcessDialog.parent.call( this, config );
8645 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
8647 * MyProcessDialog.static.title = 'Process dialog';
8648 * MyProcessDialog.static.actions = [
8649 * { action: 'save', label: 'Done', flags: 'primary' },
8650 * { label: 'Cancel', flags: 'safe' }
8653 * MyProcessDialog.prototype.initialize = function () {
8654 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
8655 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
8656 * 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>' );
8657 * this.$body.append( this.content.$element );
8659 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
8660 * var dialog = this;
8662 * return new OO.ui.Process( function () {
8663 * dialog.close( { action: action } );
8666 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
8669 * var windowManager = new OO.ui.WindowManager();
8670 * $( 'body' ).append( windowManager.$element );
8672 * var dialog = new MyProcessDialog();
8673 * windowManager.addWindows( [ dialog ] );
8674 * windowManager.openWindow( dialog );
8676 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
8680 * @extends OO.ui.Dialog
8683 * @param {Object} [config] Configuration options
8685 OO
.ui
.ProcessDialog
= function OoUiProcessDialog( config
) {
8686 // Parent constructor
8687 OO
.ui
.ProcessDialog
.parent
.call( this, config
);
8690 this.fitOnOpen
= false;
8693 this.$element
.addClass( 'oo-ui-processDialog' );
8698 OO
.inheritClass( OO
.ui
.ProcessDialog
, OO
.ui
.Dialog
);
8703 * Handle dismiss button click events.
8709 OO
.ui
.ProcessDialog
.prototype.onDismissErrorButtonClick = function () {
8714 * Handle retry button click events.
8716 * Hides errors and then tries again.
8720 OO
.ui
.ProcessDialog
.prototype.onRetryButtonClick = function () {
8722 this.executeAction( this.currentAction
);
8728 OO
.ui
.ProcessDialog
.prototype.onActionResize = function ( action
) {
8729 if ( this.actions
.isSpecial( action
) ) {
8732 return OO
.ui
.ProcessDialog
.parent
.prototype.onActionResize
.call( this, action
);
8738 OO
.ui
.ProcessDialog
.prototype.initialize = function () {
8740 OO
.ui
.ProcessDialog
.parent
.prototype.initialize
.call( this );
8743 this.$navigation
= $( '<div>' );
8744 this.$location
= $( '<div>' );
8745 this.$safeActions
= $( '<div>' );
8746 this.$primaryActions
= $( '<div>' );
8747 this.$otherActions
= $( '<div>' );
8748 this.dismissButton
= new OO
.ui
.ButtonWidget( {
8749 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' )
8751 this.retryButton
= new OO
.ui
.ButtonWidget();
8752 this.$errors
= $( '<div>' );
8753 this.$errorsTitle
= $( '<div>' );
8756 this.dismissButton
.connect( this, { click
: 'onDismissErrorButtonClick' } );
8757 this.retryButton
.connect( this, { click
: 'onRetryButtonClick' } );
8760 this.title
.$element
.addClass( 'oo-ui-processDialog-title' );
8762 .append( this.title
.$element
)
8763 .addClass( 'oo-ui-processDialog-location' );
8764 this.$safeActions
.addClass( 'oo-ui-processDialog-actions-safe' );
8765 this.$primaryActions
.addClass( 'oo-ui-processDialog-actions-primary' );
8766 this.$otherActions
.addClass( 'oo-ui-processDialog-actions-other' );
8768 .addClass( 'oo-ui-processDialog-errors-title' )
8769 .text( OO
.ui
.msg( 'ooui-dialog-process-error' ) );
8771 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
8772 .append( this.$errorsTitle
, this.dismissButton
.$element
, this.retryButton
.$element
);
8774 .addClass( 'oo-ui-processDialog-content' )
8775 .append( this.$errors
);
8777 .addClass( 'oo-ui-processDialog-navigation' )
8778 .append( this.$safeActions
, this.$location
, this.$primaryActions
);
8779 this.$head
.append( this.$navigation
);
8780 this.$foot
.append( this.$otherActions
);
8786 OO
.ui
.ProcessDialog
.prototype.getActionWidgets = function ( actions
) {
8787 var i
, len
, widgets
= [];
8788 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
8790 new OO
.ui
.ActionWidget( $.extend( { framed
: true }, actions
[ i
] ) )
8799 OO
.ui
.ProcessDialog
.prototype.attachActions = function () {
8800 var i
, len
, other
, special
, others
;
8803 OO
.ui
.ProcessDialog
.parent
.prototype.attachActions
.call( this );
8805 special
= this.actions
.getSpecial();
8806 others
= this.actions
.getOthers();
8807 if ( special
.primary
) {
8808 this.$primaryActions
.append( special
.primary
.$element
);
8810 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
8811 other
= others
[ i
];
8812 this.$otherActions
.append( other
.$element
);
8814 if ( special
.safe
) {
8815 this.$safeActions
.append( special
.safe
.$element
);
8819 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
8825 OO
.ui
.ProcessDialog
.prototype.executeAction = function ( action
) {
8827 return OO
.ui
.ProcessDialog
.parent
.prototype.executeAction
.call( this, action
)
8828 .fail( function ( errors
) {
8829 process
.showErrors( errors
|| [] );
8836 OO
.ui
.ProcessDialog
.prototype.setDimensions = function () {
8838 OO
.ui
.ProcessDialog
.parent
.prototype.setDimensions
.apply( this, arguments
);
8844 * Fit label between actions.
8849 OO
.ui
.ProcessDialog
.prototype.fitLabel = function () {
8850 var safeWidth
, primaryWidth
, biggerWidth
, labelWidth
, navigationWidth
, leftWidth
, rightWidth
,
8851 size
= this.getSizeProperties();
8853 if ( typeof size
.width
!== 'number' ) {
8854 if ( this.isOpened() ) {
8855 navigationWidth
= this.$head
.width() - 20;
8856 } else if ( this.isOpening() ) {
8857 if ( !this.fitOnOpen
) {
8858 // Size is relative and the dialog isn't open yet, so wait.
8859 this.manager
.opening
.done( this.fitLabel
.bind( this ) );
8860 this.fitOnOpen
= true;
8867 navigationWidth
= size
.width
- 20;
8870 safeWidth
= this.$safeActions
.is( ':visible' ) ? this.$safeActions
.width() : 0;
8871 primaryWidth
= this.$primaryActions
.is( ':visible' ) ? this.$primaryActions
.width() : 0;
8872 biggerWidth
= Math
.max( safeWidth
, primaryWidth
);
8874 labelWidth
= this.title
.$element
.width();
8876 if ( 2 * biggerWidth
+ labelWidth
< navigationWidth
) {
8877 // We have enough space to center the label
8878 leftWidth
= rightWidth
= biggerWidth
;
8880 // Let's hope we at least have enough space not to overlap, because we can't wrap the label…
8881 if ( this.getDir() === 'ltr' ) {
8882 leftWidth
= safeWidth
;
8883 rightWidth
= primaryWidth
;
8885 leftWidth
= primaryWidth
;
8886 rightWidth
= safeWidth
;
8890 this.$location
.css( { paddingLeft
: leftWidth
, paddingRight
: rightWidth
} );
8896 * Handle errors that occurred during accept or reject processes.
8899 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
8901 OO
.ui
.ProcessDialog
.prototype.showErrors = function ( errors
) {
8902 var i
, len
, $item
, actions
,
8908 if ( errors
instanceof OO
.ui
.Error
) {
8909 errors
= [ errors
];
8912 for ( i
= 0, len
= errors
.length
; i
< len
; i
++ ) {
8913 if ( !errors
[ i
].isRecoverable() ) {
8914 recoverable
= false;
8916 if ( errors
[ i
].isWarning() ) {
8919 $item
= $( '<div>' )
8920 .addClass( 'oo-ui-processDialog-error' )
8921 .append( errors
[ i
].getMessage() );
8922 items
.push( $item
[ 0 ] );
8924 this.$errorItems
= $( items
);
8925 if ( recoverable
) {
8926 abilities
[ this.currentAction
] = true;
8927 // Copy the flags from the first matching action
8928 actions
= this.actions
.get( { actions
: this.currentAction
} );
8929 if ( actions
.length
) {
8930 this.retryButton
.clearFlags().setFlags( actions
[ 0 ].getFlags() );
8933 abilities
[ this.currentAction
] = false;
8934 this.actions
.setAbilities( abilities
);
8937 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-continue' ) );
8939 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-retry' ) );
8941 this.retryButton
.toggle( recoverable
);
8942 this.$errorsTitle
.after( this.$errorItems
);
8943 this.$errors
.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
8951 OO
.ui
.ProcessDialog
.prototype.hideErrors = function () {
8952 this.$errors
.addClass( 'oo-ui-element-hidden' );
8953 if ( this.$errorItems
) {
8954 this.$errorItems
.remove();
8955 this.$errorItems
= null;
8962 OO
.ui
.ProcessDialog
.prototype.getTeardownProcess = function ( data
) {
8964 return OO
.ui
.ProcessDialog
.parent
.prototype.getTeardownProcess
.call( this, data
)
8965 .first( function () {
8966 // Make sure to hide errors
8968 this.fitOnOpen
= false;
8973 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
8974 * which is a widget that is specified by reference before any optional configuration settings.
8976 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
8978 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8979 * A left-alignment is used for forms with many fields.
8980 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8981 * A right-alignment is used for long but familiar forms which users tab through,
8982 * verifying the current field with a quick glance at the label.
8983 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8984 * that users fill out from top to bottom.
8985 * - **inline**: The label is placed after the field-widget and aligned to the left.
8986 * An inline-alignment is best used with checkboxes or radio buttons.
8988 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
8989 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
8991 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8993 * @extends OO.ui.Layout
8994 * @mixins OO.ui.mixin.LabelElement
8995 * @mixins OO.ui.mixin.TitledElement
8998 * @param {OO.ui.Widget} fieldWidget Field widget
8999 * @param {Object} [config] Configuration options
9000 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
9001 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
9002 * The array may contain strings or OO.ui.HtmlSnippet instances.
9003 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
9004 * The array may contain strings or OO.ui.HtmlSnippet instances.
9005 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
9006 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
9007 * For important messages, you are advised to use `notices`, as they are always shown.
9009 * @throws {Error} An error is thrown if no widget is specified
9011 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
9012 var hasInputWidget
, div
, i
;
9014 // Allow passing positional parameters inside the config object
9015 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
9016 config
= fieldWidget
;
9017 fieldWidget
= config
.fieldWidget
;
9020 // Make sure we have required constructor arguments
9021 if ( fieldWidget
=== undefined ) {
9022 throw new Error( 'Widget not found' );
9025 hasInputWidget
= fieldWidget
.constructor.static.supportsSimpleLabel
;
9027 // Configuration initialization
9028 config
= $.extend( { align
: 'left' }, config
);
9030 // Parent constructor
9031 OO
.ui
.FieldLayout
.parent
.call( this, config
);
9033 // Mixin constructors
9034 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9035 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
9038 this.fieldWidget
= fieldWidget
;
9039 this.errors
= config
.errors
|| [];
9040 this.notices
= config
.notices
|| [];
9041 this.$field
= $( '<div>' );
9042 this.$messages
= $( '<ul>' );
9043 this.$body
= $( '<' + ( hasInputWidget
? 'label' : 'div' ) + '>' );
9045 if ( config
.help
) {
9046 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
9047 classes
: [ 'oo-ui-fieldLayout-help' ],
9053 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
9054 div
.html( config
.help
.toString() );
9056 div
.text( config
.help
);
9058 this.popupButtonWidget
.getPopup().$body
.append(
9059 div
.addClass( 'oo-ui-fieldLayout-help-content' )
9061 this.$help
= this.popupButtonWidget
.$element
;
9063 this.$help
= $( [] );
9067 if ( hasInputWidget
) {
9068 this.$label
.on( 'click', this.onLabelClick
.bind( this ) );
9070 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
9074 .addClass( 'oo-ui-fieldLayout' )
9075 .append( this.$help
, this.$body
);
9076 if ( this.errors
.length
|| this.notices
.length
) {
9077 this.$element
.append( this.$messages
);
9079 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
9080 this.$messages
.addClass( 'oo-ui-fieldLayout-messages' );
9082 .addClass( 'oo-ui-fieldLayout-field' )
9083 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget
.isDisabled() )
9084 .append( this.fieldWidget
.$element
);
9086 for ( i
= 0; i
< this.notices
.length
; i
++ ) {
9087 this.$messages
.append( this.makeMessage( 'notice', this.notices
[ i
] ) );
9089 for ( i
= 0; i
< this.errors
.length
; i
++ ) {
9090 this.$messages
.append( this.makeMessage( 'error', this.errors
[ i
] ) );
9093 this.setAlignment( config
.align
);
9098 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
9099 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.LabelElement
);
9100 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.TitledElement
);
9105 * Handle field disable events.
9108 * @param {boolean} value Field is disabled
9110 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
9111 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
9115 * Handle label mouse click events.
9118 * @param {jQuery.Event} e Mouse click event
9120 OO
.ui
.FieldLayout
.prototype.onLabelClick = function () {
9121 this.fieldWidget
.simulateLabelClick();
9126 * Get the widget contained by the field.
9128 * @return {OO.ui.Widget} Field widget
9130 OO
.ui
.FieldLayout
.prototype.getField = function () {
9131 return this.fieldWidget
;
9135 * @param {string} kind 'error' or 'notice'
9136 * @param {string|OO.ui.HtmlSnippet} text
9139 OO
.ui
.FieldLayout
.prototype.makeMessage = function ( kind
, text
) {
9140 var $listItem
, $icon
, message
;
9141 $listItem
= $( '<li>' );
9142 if ( kind
=== 'error' ) {
9143 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'warning' ] } ).$element
;
9144 } else if ( kind
=== 'notice' ) {
9145 $icon
= new OO
.ui
.IconWidget( { icon
: 'info' } ).$element
;
9149 message
= new OO
.ui
.LabelWidget( { label
: text
} );
9151 .append( $icon
, message
.$element
)
9152 .addClass( 'oo-ui-fieldLayout-messages-' + kind
);
9157 * Set the field alignment mode.
9160 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
9163 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
9164 if ( value
!== this.align
) {
9165 // Default to 'left'
9166 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
9170 if ( value
=== 'inline' ) {
9171 this.$body
.append( this.$field
, this.$label
);
9173 this.$body
.append( this.$label
, this.$field
);
9175 // Set classes. The following classes can be used here:
9176 // * oo-ui-fieldLayout-align-left
9177 // * oo-ui-fieldLayout-align-right
9178 // * oo-ui-fieldLayout-align-top
9179 // * oo-ui-fieldLayout-align-inline
9181 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
9183 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
9191 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
9192 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
9193 * is required and is specified before any optional configuration settings.
9195 * Labels can be aligned in one of four ways:
9197 * - **left**: The label is placed before the field-widget and aligned with the left margin.
9198 * A left-alignment is used for forms with many fields.
9199 * - **right**: The label is placed before the field-widget and aligned to the right margin.
9200 * A right-alignment is used for long but familiar forms which users tab through,
9201 * verifying the current field with a quick glance at the label.
9202 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
9203 * that users fill out from top to bottom.
9204 * - **inline**: The label is placed after the field-widget and aligned to the left.
9205 * An inline-alignment is best used with checkboxes or radio buttons.
9207 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
9208 * text is specified.
9211 * // Example of an ActionFieldLayout
9212 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
9213 * new OO.ui.TextInputWidget( {
9214 * placeholder: 'Field widget'
9216 * new OO.ui.ButtonWidget( {
9220 * label: 'An ActionFieldLayout. This label is aligned top',
9222 * help: 'This is help text'
9226 * $( 'body' ).append( actionFieldLayout.$element );
9229 * @extends OO.ui.FieldLayout
9232 * @param {OO.ui.Widget} fieldWidget Field widget
9233 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
9235 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
9236 // Allow passing positional parameters inside the config object
9237 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
9238 config
= fieldWidget
;
9239 fieldWidget
= config
.fieldWidget
;
9240 buttonWidget
= config
.buttonWidget
;
9243 // Parent constructor
9244 OO
.ui
.ActionFieldLayout
.parent
.call( this, fieldWidget
, config
);
9247 this.buttonWidget
= buttonWidget
;
9248 this.$button
= $( '<div>' );
9249 this.$input
= $( '<div>' );
9253 .addClass( 'oo-ui-actionFieldLayout' );
9255 .addClass( 'oo-ui-actionFieldLayout-button' )
9256 .append( this.buttonWidget
.$element
);
9258 .addClass( 'oo-ui-actionFieldLayout-input' )
9259 .append( this.fieldWidget
.$element
);
9261 .append( this.$input
, this.$button
);
9266 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
9269 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
9270 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
9271 * configured with a label as well. For more information and examples,
9272 * please see the [OOjs UI documentation on MediaWiki][1].
9275 * // Example of a fieldset layout
9276 * var input1 = new OO.ui.TextInputWidget( {
9277 * placeholder: 'A text input field'
9280 * var input2 = new OO.ui.TextInputWidget( {
9281 * placeholder: 'A text input field'
9284 * var fieldset = new OO.ui.FieldsetLayout( {
9285 * label: 'Example of a fieldset layout'
9288 * fieldset.addItems( [
9289 * new OO.ui.FieldLayout( input1, {
9290 * label: 'Field One'
9292 * new OO.ui.FieldLayout( input2, {
9293 * label: 'Field Two'
9296 * $( 'body' ).append( fieldset.$element );
9298 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9301 * @extends OO.ui.Layout
9302 * @mixins OO.ui.mixin.IconElement
9303 * @mixins OO.ui.mixin.LabelElement
9304 * @mixins OO.ui.mixin.GroupElement
9307 * @param {Object} [config] Configuration options
9308 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
9310 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
9311 // Configuration initialization
9312 config
= config
|| {};
9314 // Parent constructor
9315 OO
.ui
.FieldsetLayout
.parent
.call( this, config
);
9317 // Mixin constructors
9318 OO
.ui
.mixin
.IconElement
.call( this, config
);
9319 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9320 OO
.ui
.mixin
.GroupElement
.call( this, config
);
9322 if ( config
.help
) {
9323 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
9324 classes
: [ 'oo-ui-fieldsetLayout-help' ],
9329 this.popupButtonWidget
.getPopup().$body
.append(
9331 .text( config
.help
)
9332 .addClass( 'oo-ui-fieldsetLayout-help-content' )
9334 this.$help
= this.popupButtonWidget
.$element
;
9336 this.$help
= $( [] );
9341 .addClass( 'oo-ui-fieldsetLayout' )
9342 .prepend( this.$help
, this.$icon
, this.$label
, this.$group
);
9343 if ( Array
.isArray( config
.items
) ) {
9344 this.addItems( config
.items
);
9350 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
9351 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.IconElement
);
9352 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.LabelElement
);
9353 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.GroupElement
);
9356 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
9357 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
9358 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
9359 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9361 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
9362 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
9363 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
9364 * some fancier controls. Some controls have both regular and InputWidget variants, for example
9365 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
9366 * often have simplified APIs to match the capabilities of HTML forms.
9367 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
9369 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
9370 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9373 * // Example of a form layout that wraps a fieldset layout
9374 * var input1 = new OO.ui.TextInputWidget( {
9375 * placeholder: 'Username'
9377 * var input2 = new OO.ui.TextInputWidget( {
9378 * placeholder: 'Password',
9381 * var submit = new OO.ui.ButtonInputWidget( {
9385 * var fieldset = new OO.ui.FieldsetLayout( {
9386 * label: 'A form layout'
9388 * fieldset.addItems( [
9389 * new OO.ui.FieldLayout( input1, {
9390 * label: 'Username',
9393 * new OO.ui.FieldLayout( input2, {
9394 * label: 'Password',
9397 * new OO.ui.FieldLayout( submit )
9399 * var form = new OO.ui.FormLayout( {
9400 * items: [ fieldset ],
9401 * action: '/api/formhandler',
9404 * $( 'body' ).append( form.$element );
9407 * @extends OO.ui.Layout
9408 * @mixins OO.ui.mixin.GroupElement
9411 * @param {Object} [config] Configuration options
9412 * @cfg {string} [method] HTML form `method` attribute
9413 * @cfg {string} [action] HTML form `action` attribute
9414 * @cfg {string} [enctype] HTML form `enctype` attribute
9415 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
9417 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
9418 // Configuration initialization
9419 config
= config
|| {};
9421 // Parent constructor
9422 OO
.ui
.FormLayout
.parent
.call( this, config
);
9424 // Mixin constructors
9425 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
9428 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
9430 // Make sure the action is safe
9431 if ( config
.action
!== undefined && !OO
.ui
.isSafeUrl( config
.action
) ) {
9432 throw new Error( 'Potentially unsafe action provided: ' + config
.action
);
9437 .addClass( 'oo-ui-formLayout' )
9439 method
: config
.method
,
9440 action
: config
.action
,
9441 enctype
: config
.enctype
9443 if ( Array
.isArray( config
.items
) ) {
9444 this.addItems( config
.items
);
9450 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
9451 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.mixin
.GroupElement
);
9456 * A 'submit' event is emitted when the form is submitted.
9461 /* Static Properties */
9463 OO
.ui
.FormLayout
.static.tagName
= 'form';
9468 * Handle form submit events.
9471 * @param {jQuery.Event} e Submit event
9474 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
9475 if ( this.emit( 'submit' ) ) {
9481 * 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)
9482 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
9485 * var menuLayout = new OO.ui.MenuLayout( {
9488 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9489 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9490 * select = new OO.ui.SelectWidget( {
9492 * new OO.ui.OptionWidget( {
9496 * new OO.ui.OptionWidget( {
9500 * new OO.ui.OptionWidget( {
9504 * new OO.ui.OptionWidget( {
9509 * } ).on( 'select', function ( item ) {
9510 * menuLayout.setMenuPosition( item.getData() );
9513 * menuLayout.$menu.append(
9514 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
9516 * menuLayout.$content.append(
9517 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
9519 * $( 'body' ).append( menuLayout.$element );
9521 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
9522 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
9523 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
9526 * .oo-ui-menuLayout-menu {
9530 * .oo-ui-menuLayout-content {
9538 * @extends OO.ui.Layout
9541 * @param {Object} [config] Configuration options
9542 * @cfg {boolean} [showMenu=true] Show menu
9543 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
9545 OO
.ui
.MenuLayout
= function OoUiMenuLayout( config
) {
9546 // Configuration initialization
9547 config
= $.extend( {
9549 menuPosition
: 'before'
9552 // Parent constructor
9553 OO
.ui
.MenuLayout
.parent
.call( this, config
);
9558 * @property {jQuery}
9560 this.$menu
= $( '<div>' );
9564 * @property {jQuery}
9566 this.$content
= $( '<div>' );
9570 .addClass( 'oo-ui-menuLayout-menu' );
9571 this.$content
.addClass( 'oo-ui-menuLayout-content' );
9573 .addClass( 'oo-ui-menuLayout' )
9574 .append( this.$content
, this.$menu
);
9575 this.setMenuPosition( config
.menuPosition
);
9576 this.toggleMenu( config
.showMenu
);
9581 OO
.inheritClass( OO
.ui
.MenuLayout
, OO
.ui
.Layout
);
9588 * @param {boolean} showMenu Show menu, omit to toggle
9591 OO
.ui
.MenuLayout
.prototype.toggleMenu = function ( showMenu
) {
9592 showMenu
= showMenu
=== undefined ? !this.showMenu
: !!showMenu
;
9594 if ( this.showMenu
!== showMenu
) {
9595 this.showMenu
= showMenu
;
9597 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu
)
9598 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu
);
9605 * Check if menu is visible
9607 * @return {boolean} Menu is visible
9609 OO
.ui
.MenuLayout
.prototype.isMenuVisible = function () {
9610 return this.showMenu
;
9614 * Set menu position.
9616 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
9617 * @throws {Error} If position value is not supported
9620 OO
.ui
.MenuLayout
.prototype.setMenuPosition = function ( position
) {
9621 this.$element
.removeClass( 'oo-ui-menuLayout-' + this.menuPosition
);
9622 this.menuPosition
= position
;
9623 this.$element
.addClass( 'oo-ui-menuLayout-' + position
);
9629 * Get menu position.
9631 * @return {string} Menu position
9633 OO
.ui
.MenuLayout
.prototype.getMenuPosition = function () {
9634 return this.menuPosition
;
9638 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
9639 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
9640 * through the pages and select which one to display. By default, only one page is
9641 * displayed at a time and the outline is hidden. When a user navigates to a new page,
9642 * the booklet layout automatically focuses on the first focusable element, unless the
9643 * default setting is changed. Optionally, booklets can be configured to show
9644 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
9647 * // Example of a BookletLayout that contains two PageLayouts.
9649 * function PageOneLayout( name, config ) {
9650 * PageOneLayout.parent.call( this, name, config );
9651 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
9653 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
9654 * PageOneLayout.prototype.setupOutlineItem = function () {
9655 * this.outlineItem.setLabel( 'Page One' );
9658 * function PageTwoLayout( name, config ) {
9659 * PageTwoLayout.parent.call( this, name, config );
9660 * this.$element.append( '<p>Second page</p>' );
9662 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
9663 * PageTwoLayout.prototype.setupOutlineItem = function () {
9664 * this.outlineItem.setLabel( 'Page Two' );
9667 * var page1 = new PageOneLayout( 'one' ),
9668 * page2 = new PageTwoLayout( 'two' );
9670 * var booklet = new OO.ui.BookletLayout( {
9674 * booklet.addPages ( [ page1, page2 ] );
9675 * $( 'body' ).append( booklet.$element );
9678 * @extends OO.ui.MenuLayout
9681 * @param {Object} [config] Configuration options
9682 * @cfg {boolean} [continuous=false] Show all pages, one after another
9683 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
9684 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
9685 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
9687 OO
.ui
.BookletLayout
= function OoUiBookletLayout( config
) {
9688 // Configuration initialization
9689 config
= config
|| {};
9691 // Parent constructor
9692 OO
.ui
.BookletLayout
.parent
.call( this, config
);
9695 this.currentPageName
= null;
9697 this.ignoreFocus
= false;
9698 this.stackLayout
= new OO
.ui
.StackLayout( { continuous
: !!config
.continuous
} );
9699 this.$content
.append( this.stackLayout
.$element
);
9700 this.autoFocus
= config
.autoFocus
=== undefined || !!config
.autoFocus
;
9701 this.outlineVisible
= false;
9702 this.outlined
= !!config
.outlined
;
9703 if ( this.outlined
) {
9704 this.editable
= !!config
.editable
;
9705 this.outlineControlsWidget
= null;
9706 this.outlineSelectWidget
= new OO
.ui
.OutlineSelectWidget();
9707 this.outlinePanel
= new OO
.ui
.PanelLayout( { scrollable
: true } );
9708 this.$menu
.append( this.outlinePanel
.$element
);
9709 this.outlineVisible
= true;
9710 if ( this.editable
) {
9711 this.outlineControlsWidget
= new OO
.ui
.OutlineControlsWidget(
9712 this.outlineSelectWidget
9716 this.toggleMenu( this.outlined
);
9719 this.stackLayout
.connect( this, { set: 'onStackLayoutSet' } );
9720 if ( this.outlined
) {
9721 this.outlineSelectWidget
.connect( this, { select
: 'onOutlineSelectWidgetSelect' } );
9723 if ( this.autoFocus
) {
9724 // Event 'focus' does not bubble, but 'focusin' does
9725 this.stackLayout
.$element
.on( 'focusin', this.onStackLayoutFocus
.bind( this ) );
9729 this.$element
.addClass( 'oo-ui-bookletLayout' );
9730 this.stackLayout
.$element
.addClass( 'oo-ui-bookletLayout-stackLayout' );
9731 if ( this.outlined
) {
9732 this.outlinePanel
.$element
9733 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
9734 .append( this.outlineSelectWidget
.$element
);
9735 if ( this.editable
) {
9736 this.outlinePanel
.$element
9737 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
9738 .append( this.outlineControlsWidget
.$element
);
9745 OO
.inheritClass( OO
.ui
.BookletLayout
, OO
.ui
.MenuLayout
);
9750 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
9752 * @param {OO.ui.PageLayout} page Current page
9756 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
9759 * @param {OO.ui.PageLayout[]} page Added pages
9760 * @param {number} index Index pages were added at
9764 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
9765 * {@link #removePages removed} from the booklet.
9768 * @param {OO.ui.PageLayout[]} pages Removed pages
9774 * Handle stack layout focus.
9777 * @param {jQuery.Event} e Focusin event
9779 OO
.ui
.BookletLayout
.prototype.onStackLayoutFocus = function ( e
) {
9782 // Find the page that an element was focused within
9783 $target
= $( e
.target
).closest( '.oo-ui-pageLayout' );
9784 for ( name
in this.pages
) {
9785 // Check for page match, exclude current page to find only page changes
9786 if ( this.pages
[ name
].$element
[ 0 ] === $target
[ 0 ] && name
!== this.currentPageName
) {
9787 this.setPage( name
);
9794 * Handle stack layout set events.
9797 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
9799 OO
.ui
.BookletLayout
.prototype.onStackLayoutSet = function ( page
) {
9802 page
.scrollElementIntoView( { complete: function () {
9803 if ( layout
.autoFocus
) {
9811 * Focus the first input in the current page.
9813 * If no page is selected, the first selectable page will be selected.
9814 * If the focus is already in an element on the current page, nothing will happen.
9815 * @param {number} [itemIndex] A specific item to focus on
9817 OO
.ui
.BookletLayout
.prototype.focus = function ( itemIndex
) {
9819 items
= this.stackLayout
.getItems();
9821 if ( itemIndex
!== undefined && items
[ itemIndex
] ) {
9822 page
= items
[ itemIndex
];
9824 page
= this.stackLayout
.getCurrentItem();
9827 if ( !page
&& this.outlined
) {
9828 this.selectFirstSelectablePage();
9829 page
= this.stackLayout
.getCurrentItem();
9834 // Only change the focus if is not already in the current page
9835 if ( !page
.$element
.find( ':focus' ).length
) {
9836 OO
.ui
.findFocusable( page
.$element
).focus();
9841 * Find the first focusable input in the booklet layout and focus
9844 OO
.ui
.BookletLayout
.prototype.focusFirstFocusable = function () {
9845 OO
.ui
.findFocusable( this.stackLayout
.$element
).focus();
9849 * Handle outline widget select events.
9852 * @param {OO.ui.OptionWidget|null} item Selected item
9854 OO
.ui
.BookletLayout
.prototype.onOutlineSelectWidgetSelect = function ( item
) {
9856 this.setPage( item
.getData() );
9861 * Check if booklet has an outline.
9863 * @return {boolean} Booklet has an outline
9865 OO
.ui
.BookletLayout
.prototype.isOutlined = function () {
9866 return this.outlined
;
9870 * Check if booklet has editing controls.
9872 * @return {boolean} Booklet is editable
9874 OO
.ui
.BookletLayout
.prototype.isEditable = function () {
9875 return this.editable
;
9879 * Check if booklet has a visible outline.
9881 * @return {boolean} Outline is visible
9883 OO
.ui
.BookletLayout
.prototype.isOutlineVisible = function () {
9884 return this.outlined
&& this.outlineVisible
;
9888 * Hide or show the outline.
9890 * @param {boolean} [show] Show outline, omit to invert current state
9893 OO
.ui
.BookletLayout
.prototype.toggleOutline = function ( show
) {
9894 if ( this.outlined
) {
9895 show
= show
=== undefined ? !this.outlineVisible
: !!show
;
9896 this.outlineVisible
= show
;
9897 this.toggleMenu( show
);
9904 * Get the page closest to the specified page.
9906 * @param {OO.ui.PageLayout} page Page to use as a reference point
9907 * @return {OO.ui.PageLayout|null} Page closest to the specified page
9909 OO
.ui
.BookletLayout
.prototype.getClosestPage = function ( page
) {
9910 var next
, prev
, level
,
9911 pages
= this.stackLayout
.getItems(),
9912 index
= pages
.indexOf( page
);
9914 if ( index
!== -1 ) {
9915 next
= pages
[ index
+ 1 ];
9916 prev
= pages
[ index
- 1 ];
9917 // Prefer adjacent pages at the same level
9918 if ( this.outlined
) {
9919 level
= this.outlineSelectWidget
.getItemFromData( page
.getName() ).getLevel();
9922 level
=== this.outlineSelectWidget
.getItemFromData( prev
.getName() ).getLevel()
9928 level
=== this.outlineSelectWidget
.getItemFromData( next
.getName() ).getLevel()
9934 return prev
|| next
|| null;
9938 * Get the outline widget.
9940 * If the booklet is not outlined, the method will return `null`.
9942 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
9944 OO
.ui
.BookletLayout
.prototype.getOutline = function () {
9945 return this.outlineSelectWidget
;
9949 * Get the outline controls widget.
9951 * If the outline is not editable, the method will return `null`.
9953 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
9955 OO
.ui
.BookletLayout
.prototype.getOutlineControls = function () {
9956 return this.outlineControlsWidget
;
9960 * Get a page by its symbolic name.
9962 * @param {string} name Symbolic name of page
9963 * @return {OO.ui.PageLayout|undefined} Page, if found
9965 OO
.ui
.BookletLayout
.prototype.getPage = function ( name
) {
9966 return this.pages
[ name
];
9970 * Get the current page.
9972 * @return {OO.ui.PageLayout|undefined} Current page, if found
9974 OO
.ui
.BookletLayout
.prototype.getCurrentPage = function () {
9975 var name
= this.getCurrentPageName();
9976 return name
? this.getPage( name
) : undefined;
9980 * Get the symbolic name of the current page.
9982 * @return {string|null} Symbolic name of the current page
9984 OO
.ui
.BookletLayout
.prototype.getCurrentPageName = function () {
9985 return this.currentPageName
;
9989 * Add pages to the booklet layout
9991 * When pages are added with the same names as existing pages, the existing pages will be
9992 * automatically removed before the new pages are added.
9994 * @param {OO.ui.PageLayout[]} pages Pages to add
9995 * @param {number} index Index of the insertion point
9999 OO
.ui
.BookletLayout
.prototype.addPages = function ( pages
, index
) {
10000 var i
, len
, name
, page
, item
, currentIndex
,
10001 stackLayoutPages
= this.stackLayout
.getItems(),
10005 // Remove pages with same names
10006 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
10008 name
= page
.getName();
10010 if ( Object
.prototype.hasOwnProperty
.call( this.pages
, name
) ) {
10011 // Correct the insertion index
10012 currentIndex
= stackLayoutPages
.indexOf( this.pages
[ name
] );
10013 if ( currentIndex
!== -1 && currentIndex
+ 1 < index
) {
10016 remove
.push( this.pages
[ name
] );
10019 if ( remove
.length
) {
10020 this.removePages( remove
);
10024 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
10026 name
= page
.getName();
10027 this.pages
[ page
.getName() ] = page
;
10028 if ( this.outlined
) {
10029 item
= new OO
.ui
.OutlineOptionWidget( { data
: name
} );
10030 page
.setOutlineItem( item
);
10031 items
.push( item
);
10035 if ( this.outlined
&& items
.length
) {
10036 this.outlineSelectWidget
.addItems( items
, index
);
10037 this.selectFirstSelectablePage();
10039 this.stackLayout
.addItems( pages
, index
);
10040 this.emit( 'add', pages
, index
);
10046 * Remove the specified pages from the booklet layout.
10048 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
10050 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
10054 OO
.ui
.BookletLayout
.prototype.removePages = function ( pages
) {
10055 var i
, len
, name
, page
,
10058 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
10060 name
= page
.getName();
10061 delete this.pages
[ name
];
10062 if ( this.outlined
) {
10063 items
.push( this.outlineSelectWidget
.getItemFromData( name
) );
10064 page
.setOutlineItem( null );
10067 if ( this.outlined
&& items
.length
) {
10068 this.outlineSelectWidget
.removeItems( items
);
10069 this.selectFirstSelectablePage();
10071 this.stackLayout
.removeItems( pages
);
10072 this.emit( 'remove', pages
);
10078 * Clear all pages from the booklet layout.
10080 * To remove only a subset of pages from the booklet, use the #removePages method.
10085 OO
.ui
.BookletLayout
.prototype.clearPages = function () {
10087 pages
= this.stackLayout
.getItems();
10090 this.currentPageName
= null;
10091 if ( this.outlined
) {
10092 this.outlineSelectWidget
.clearItems();
10093 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
10094 pages
[ i
].setOutlineItem( null );
10097 this.stackLayout
.clearItems();
10099 this.emit( 'remove', pages
);
10105 * Set the current page by symbolic name.
10108 * @param {string} name Symbolic name of page
10110 OO
.ui
.BookletLayout
.prototype.setPage = function ( name
) {
10113 page
= this.pages
[ name
],
10114 previousPage
= this.currentPageName
&& this.pages
[ this.currentPageName
];
10116 if ( name
!== this.currentPageName
) {
10117 if ( this.outlined
) {
10118 selectedItem
= this.outlineSelectWidget
.getSelectedItem();
10119 if ( selectedItem
&& selectedItem
.getData() !== name
) {
10120 this.outlineSelectWidget
.selectItemByData( name
);
10124 if ( previousPage
) {
10125 previousPage
.setActive( false );
10126 // Blur anything focused if the next page doesn't have anything focusable.
10127 // This is not needed if the next page has something focusable (because once it is focused
10128 // this blur happens automatically). If the layout is non-continuous, this check is
10129 // meaningless because the next page is not visible yet and thus can't hold focus.
10132 this.stackLayout
.continuous
&&
10133 OO
.ui
.findFocusable( page
.$element
).length
!== 0
10135 $focused
= previousPage
.$element
.find( ':focus' );
10136 if ( $focused
.length
) {
10137 $focused
[ 0 ].blur();
10141 this.currentPageName
= name
;
10142 page
.setActive( true );
10143 this.stackLayout
.setItem( page
);
10144 if ( !this.stackLayout
.continuous
&& previousPage
) {
10145 // This should not be necessary, since any inputs on the previous page should have been
10146 // blurred when it was hidden, but browsers are not very consistent about this.
10147 $focused
= previousPage
.$element
.find( ':focus' );
10148 if ( $focused
.length
) {
10149 $focused
[ 0 ].blur();
10152 this.emit( 'set', page
);
10158 * Select the first selectable page.
10162 OO
.ui
.BookletLayout
.prototype.selectFirstSelectablePage = function () {
10163 if ( !this.outlineSelectWidget
.getSelectedItem() ) {
10164 this.outlineSelectWidget
.selectItem( this.outlineSelectWidget
.getFirstSelectableItem() );
10171 * IndexLayouts contain {@link OO.ui.CardLayout card layouts} as well as
10172 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the cards and
10173 * select which one to display. By default, only one card is displayed at a time. When a user
10174 * navigates to a new card, the index layout automatically focuses on the first focusable element,
10175 * unless the default setting is changed.
10177 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
10180 * // Example of a IndexLayout that contains two CardLayouts.
10182 * function CardOneLayout( name, config ) {
10183 * CardOneLayout.parent.call( this, name, config );
10184 * this.$element.append( '<p>First card</p>' );
10186 * OO.inheritClass( CardOneLayout, OO.ui.CardLayout );
10187 * CardOneLayout.prototype.setupTabItem = function () {
10188 * this.tabItem.setLabel( 'Card one' );
10191 * var card1 = new CardOneLayout( 'one' ),
10192 * card2 = new CardLayout( 'two', { label: 'Card two' } );
10194 * card2.$element.append( '<p>Second card</p>' );
10196 * var index = new OO.ui.IndexLayout();
10198 * index.addCards ( [ card1, card2 ] );
10199 * $( 'body' ).append( index.$element );
10202 * @extends OO.ui.MenuLayout
10205 * @param {Object} [config] Configuration options
10206 * @cfg {boolean} [continuous=false] Show all cards, one after another
10207 * @cfg {boolean} [expanded=true] Expand the content panel to fill the entire parent element.
10208 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new card is displayed.
10210 OO
.ui
.IndexLayout
= function OoUiIndexLayout( config
) {
10211 // Configuration initialization
10212 config
= $.extend( {}, config
, { menuPosition
: 'top' } );
10214 // Parent constructor
10215 OO
.ui
.IndexLayout
.parent
.call( this, config
);
10218 this.currentCardName
= null;
10220 this.ignoreFocus
= false;
10221 this.stackLayout
= new OO
.ui
.StackLayout( {
10222 continuous
: !!config
.continuous
,
10223 expanded
: config
.expanded
10225 this.$content
.append( this.stackLayout
.$element
);
10226 this.autoFocus
= config
.autoFocus
=== undefined || !!config
.autoFocus
;
10228 this.tabSelectWidget
= new OO
.ui
.TabSelectWidget();
10229 this.tabPanel
= new OO
.ui
.PanelLayout();
10230 this.$menu
.append( this.tabPanel
.$element
);
10232 this.toggleMenu( true );
10235 this.stackLayout
.connect( this, { set: 'onStackLayoutSet' } );
10236 this.tabSelectWidget
.connect( this, { select
: 'onTabSelectWidgetSelect' } );
10237 if ( this.autoFocus
) {
10238 // Event 'focus' does not bubble, but 'focusin' does
10239 this.stackLayout
.$element
.on( 'focusin', this.onStackLayoutFocus
.bind( this ) );
10243 this.$element
.addClass( 'oo-ui-indexLayout' );
10244 this.stackLayout
.$element
.addClass( 'oo-ui-indexLayout-stackLayout' );
10245 this.tabPanel
.$element
10246 .addClass( 'oo-ui-indexLayout-tabPanel' )
10247 .append( this.tabSelectWidget
.$element
);
10252 OO
.inheritClass( OO
.ui
.IndexLayout
, OO
.ui
.MenuLayout
);
10257 * A 'set' event is emitted when a card is {@link #setCard set} to be displayed by the index layout.
10259 * @param {OO.ui.CardLayout} card Current card
10263 * An 'add' event is emitted when cards are {@link #addCards added} to the index layout.
10266 * @param {OO.ui.CardLayout[]} card Added cards
10267 * @param {number} index Index cards were added at
10271 * A 'remove' event is emitted when cards are {@link #clearCards cleared} or
10272 * {@link #removeCards removed} from the index.
10275 * @param {OO.ui.CardLayout[]} cards Removed cards
10281 * Handle stack layout focus.
10284 * @param {jQuery.Event} e Focusin event
10286 OO
.ui
.IndexLayout
.prototype.onStackLayoutFocus = function ( e
) {
10289 // Find the card that an element was focused within
10290 $target
= $( e
.target
).closest( '.oo-ui-cardLayout' );
10291 for ( name
in this.cards
) {
10292 // Check for card match, exclude current card to find only card changes
10293 if ( this.cards
[ name
].$element
[ 0 ] === $target
[ 0 ] && name
!== this.currentCardName
) {
10294 this.setCard( name
);
10301 * Handle stack layout set events.
10304 * @param {OO.ui.PanelLayout|null} card The card panel that is now the current panel
10306 OO
.ui
.IndexLayout
.prototype.onStackLayoutSet = function ( card
) {
10309 card
.scrollElementIntoView( { complete: function () {
10310 if ( layout
.autoFocus
) {
10318 * Focus the first input in the current card.
10320 * If no card is selected, the first selectable card will be selected.
10321 * If the focus is already in an element on the current card, nothing will happen.
10322 * @param {number} [itemIndex] A specific item to focus on
10324 OO
.ui
.IndexLayout
.prototype.focus = function ( itemIndex
) {
10326 items
= this.stackLayout
.getItems();
10328 if ( itemIndex
!== undefined && items
[ itemIndex
] ) {
10329 card
= items
[ itemIndex
];
10331 card
= this.stackLayout
.getCurrentItem();
10335 this.selectFirstSelectableCard();
10336 card
= this.stackLayout
.getCurrentItem();
10341 // Only change the focus if is not already in the current card
10342 if ( !card
.$element
.find( ':focus' ).length
) {
10343 OO
.ui
.findFocusable( card
.$element
).focus();
10348 * Find the first focusable input in the index layout and focus
10351 OO
.ui
.IndexLayout
.prototype.focusFirstFocusable = function () {
10352 OO
.ui
.findFocusable( this.stackLayout
.$element
).focus();
10356 * Handle tab widget select events.
10359 * @param {OO.ui.OptionWidget|null} item Selected item
10361 OO
.ui
.IndexLayout
.prototype.onTabSelectWidgetSelect = function ( item
) {
10363 this.setCard( item
.getData() );
10368 * Get the card closest to the specified card.
10370 * @param {OO.ui.CardLayout} card Card to use as a reference point
10371 * @return {OO.ui.CardLayout|null} Card closest to the specified card
10373 OO
.ui
.IndexLayout
.prototype.getClosestCard = function ( card
) {
10374 var next
, prev
, level
,
10375 cards
= this.stackLayout
.getItems(),
10376 index
= cards
.indexOf( card
);
10378 if ( index
!== -1 ) {
10379 next
= cards
[ index
+ 1 ];
10380 prev
= cards
[ index
- 1 ];
10381 // Prefer adjacent cards at the same level
10382 level
= this.tabSelectWidget
.getItemFromData( card
.getName() ).getLevel();
10385 level
=== this.tabSelectWidget
.getItemFromData( prev
.getName() ).getLevel()
10391 level
=== this.tabSelectWidget
.getItemFromData( next
.getName() ).getLevel()
10396 return prev
|| next
|| null;
10400 * Get the tabs widget.
10402 * @return {OO.ui.TabSelectWidget} Tabs widget
10404 OO
.ui
.IndexLayout
.prototype.getTabs = function () {
10405 return this.tabSelectWidget
;
10409 * Get a card by its symbolic name.
10411 * @param {string} name Symbolic name of card
10412 * @return {OO.ui.CardLayout|undefined} Card, if found
10414 OO
.ui
.IndexLayout
.prototype.getCard = function ( name
) {
10415 return this.cards
[ name
];
10419 * Get the current card.
10421 * @return {OO.ui.CardLayout|undefined} Current card, if found
10423 OO
.ui
.IndexLayout
.prototype.getCurrentCard = function () {
10424 var name
= this.getCurrentCardName();
10425 return name
? this.getCard( name
) : undefined;
10429 * Get the symbolic name of the current card.
10431 * @return {string|null} Symbolic name of the current card
10433 OO
.ui
.IndexLayout
.prototype.getCurrentCardName = function () {
10434 return this.currentCardName
;
10438 * Add cards to the index layout
10440 * When cards are added with the same names as existing cards, the existing cards will be
10441 * automatically removed before the new cards are added.
10443 * @param {OO.ui.CardLayout[]} cards Cards to add
10444 * @param {number} index Index of the insertion point
10448 OO
.ui
.IndexLayout
.prototype.addCards = function ( cards
, index
) {
10449 var i
, len
, name
, card
, item
, currentIndex
,
10450 stackLayoutCards
= this.stackLayout
.getItems(),
10454 // Remove cards with same names
10455 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10457 name
= card
.getName();
10459 if ( Object
.prototype.hasOwnProperty
.call( this.cards
, name
) ) {
10460 // Correct the insertion index
10461 currentIndex
= stackLayoutCards
.indexOf( this.cards
[ name
] );
10462 if ( currentIndex
!== -1 && currentIndex
+ 1 < index
) {
10465 remove
.push( this.cards
[ name
] );
10468 if ( remove
.length
) {
10469 this.removeCards( remove
);
10473 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10475 name
= card
.getName();
10476 this.cards
[ card
.getName() ] = card
;
10477 item
= new OO
.ui
.TabOptionWidget( { data
: name
} );
10478 card
.setTabItem( item
);
10479 items
.push( item
);
10482 if ( items
.length
) {
10483 this.tabSelectWidget
.addItems( items
, index
);
10484 this.selectFirstSelectableCard();
10486 this.stackLayout
.addItems( cards
, index
);
10487 this.emit( 'add', cards
, index
);
10493 * Remove the specified cards from the index layout.
10495 * To remove all cards from the index, you may wish to use the #clearCards method instead.
10497 * @param {OO.ui.CardLayout[]} cards An array of cards to remove
10501 OO
.ui
.IndexLayout
.prototype.removeCards = function ( cards
) {
10502 var i
, len
, name
, card
,
10505 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10507 name
= card
.getName();
10508 delete this.cards
[ name
];
10509 items
.push( this.tabSelectWidget
.getItemFromData( name
) );
10510 card
.setTabItem( null );
10512 if ( items
.length
) {
10513 this.tabSelectWidget
.removeItems( items
);
10514 this.selectFirstSelectableCard();
10516 this.stackLayout
.removeItems( cards
);
10517 this.emit( 'remove', cards
);
10523 * Clear all cards from the index layout.
10525 * To remove only a subset of cards from the index, use the #removeCards method.
10530 OO
.ui
.IndexLayout
.prototype.clearCards = function () {
10532 cards
= this.stackLayout
.getItems();
10535 this.currentCardName
= null;
10536 this.tabSelectWidget
.clearItems();
10537 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10538 cards
[ i
].setTabItem( null );
10540 this.stackLayout
.clearItems();
10542 this.emit( 'remove', cards
);
10548 * Set the current card by symbolic name.
10551 * @param {string} name Symbolic name of card
10553 OO
.ui
.IndexLayout
.prototype.setCard = function ( name
) {
10556 card
= this.cards
[ name
],
10557 previousCard
= this.currentCardName
&& this.cards
[ this.currentCardName
];
10559 if ( name
!== this.currentCardName
) {
10560 selectedItem
= this.tabSelectWidget
.getSelectedItem();
10561 if ( selectedItem
&& selectedItem
.getData() !== name
) {
10562 this.tabSelectWidget
.selectItemByData( name
);
10565 if ( previousCard
) {
10566 previousCard
.setActive( false );
10567 // Blur anything focused if the next card doesn't have anything focusable.
10568 // This is not needed if the next card has something focusable (because once it is focused
10569 // this blur happens automatically). If the layout is non-continuous, this check is
10570 // meaningless because the next card is not visible yet and thus can't hold focus.
10573 this.stackLayout
.continuous
&&
10574 OO
.ui
.findFocusable( card
.$element
).length
!== 0
10576 $focused
= previousCard
.$element
.find( ':focus' );
10577 if ( $focused
.length
) {
10578 $focused
[ 0 ].blur();
10582 this.currentCardName
= name
;
10583 card
.setActive( true );
10584 this.stackLayout
.setItem( card
);
10585 if ( !this.stackLayout
.continuous
&& previousCard
) {
10586 // This should not be necessary, since any inputs on the previous card should have been
10587 // blurred when it was hidden, but browsers are not very consistent about this.
10588 $focused
= previousCard
.$element
.find( ':focus' );
10589 if ( $focused
.length
) {
10590 $focused
[ 0 ].blur();
10593 this.emit( 'set', card
);
10599 * Select the first selectable card.
10603 OO
.ui
.IndexLayout
.prototype.selectFirstSelectableCard = function () {
10604 if ( !this.tabSelectWidget
.getSelectedItem() ) {
10605 this.tabSelectWidget
.selectItem( this.tabSelectWidget
.getFirstSelectableItem() );
10612 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
10613 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
10616 * // Example of a panel layout
10617 * var panel = new OO.ui.PanelLayout( {
10621 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
10623 * $( 'body' ).append( panel.$element );
10626 * @extends OO.ui.Layout
10629 * @param {Object} [config] Configuration options
10630 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
10631 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
10632 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
10633 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
10635 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
10636 // Configuration initialization
10637 config
= $.extend( {
10644 // Parent constructor
10645 OO
.ui
.PanelLayout
.parent
.call( this, config
);
10648 this.$element
.addClass( 'oo-ui-panelLayout' );
10649 if ( config
.scrollable
) {
10650 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
10652 if ( config
.padded
) {
10653 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
10655 if ( config
.expanded
) {
10656 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
10658 if ( config
.framed
) {
10659 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
10665 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
10668 * CardLayouts are used within {@link OO.ui.IndexLayout index layouts} to create cards that users can select and display
10669 * from the index's optional {@link OO.ui.TabSelectWidget tab} navigation. Cards are usually not instantiated directly,
10670 * rather extended to include the required content and functionality.
10672 * Each card must have a unique symbolic name, which is passed to the constructor. In addition, the card's tab
10673 * item is customized (with a label) using the #setupTabItem method. See
10674 * {@link OO.ui.IndexLayout IndexLayout} for an example.
10677 * @extends OO.ui.PanelLayout
10680 * @param {string} name Unique symbolic name of card
10681 * @param {Object} [config] Configuration options
10682 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] Label for card's tab
10684 OO
.ui
.CardLayout
= function OoUiCardLayout( name
, config
) {
10685 // Allow passing positional parameters inside the config object
10686 if ( OO
.isPlainObject( name
) && config
=== undefined ) {
10688 name
= config
.name
;
10691 // Configuration initialization
10692 config
= $.extend( { scrollable
: true }, config
);
10694 // Parent constructor
10695 OO
.ui
.CardLayout
.parent
.call( this, config
);
10699 this.label
= config
.label
;
10700 this.tabItem
= null;
10701 this.active
= false;
10704 this.$element
.addClass( 'oo-ui-cardLayout' );
10709 OO
.inheritClass( OO
.ui
.CardLayout
, OO
.ui
.PanelLayout
);
10714 * An 'active' event is emitted when the card becomes active. Cards become active when they are
10715 * shown in a index layout that is configured to display only one card at a time.
10718 * @param {boolean} active Card is active
10724 * Get the symbolic name of the card.
10726 * @return {string} Symbolic name of card
10728 OO
.ui
.CardLayout
.prototype.getName = function () {
10733 * Check if card is active.
10735 * Cards become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to display
10736 * only one card at a time. Additional CSS is applied to the card's tab item to reflect the active state.
10738 * @return {boolean} Card is active
10740 OO
.ui
.CardLayout
.prototype.isActive = function () {
10741 return this.active
;
10747 * The tab item allows users to access the card from the index's tab
10748 * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
10750 * @return {OO.ui.TabOptionWidget|null} Tab option widget
10752 OO
.ui
.CardLayout
.prototype.getTabItem = function () {
10753 return this.tabItem
;
10757 * Set or unset the tab item.
10759 * Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
10760 * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
10761 * level), use #setupTabItem instead of this method.
10763 * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
10766 OO
.ui
.CardLayout
.prototype.setTabItem = function ( tabItem
) {
10767 this.tabItem
= tabItem
|| null;
10769 this.setupTabItem();
10775 * Set up the tab item.
10777 * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
10778 * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
10779 * the #setTabItem method instead.
10781 * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
10784 OO
.ui
.CardLayout
.prototype.setupTabItem = function () {
10785 if ( this.label
) {
10786 this.tabItem
.setLabel( this.label
);
10792 * Set the card to its 'active' state.
10794 * Cards become active when they are shown in a index layout that is configured to display only one card at a time. Additional
10795 * CSS is applied to the tab item to reflect the card's active state. Outside of the index
10796 * context, setting the active state on a card does nothing.
10798 * @param {boolean} value Card is active
10801 OO
.ui
.CardLayout
.prototype.setActive = function ( active
) {
10804 if ( active
!== this.active
) {
10805 this.active
= active
;
10806 this.$element
.toggleClass( 'oo-ui-cardLayout-active', this.active
);
10807 this.emit( 'active', this.active
);
10812 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
10813 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
10814 * rather extended to include the required content and functionality.
10816 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
10817 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
10818 * {@link OO.ui.BookletLayout BookletLayout} for an example.
10821 * @extends OO.ui.PanelLayout
10824 * @param {string} name Unique symbolic name of page
10825 * @param {Object} [config] Configuration options
10827 OO
.ui
.PageLayout
= function OoUiPageLayout( name
, config
) {
10828 // Allow passing positional parameters inside the config object
10829 if ( OO
.isPlainObject( name
) && config
=== undefined ) {
10831 name
= config
.name
;
10834 // Configuration initialization
10835 config
= $.extend( { scrollable
: true }, config
);
10837 // Parent constructor
10838 OO
.ui
.PageLayout
.parent
.call( this, config
);
10842 this.outlineItem
= null;
10843 this.active
= false;
10846 this.$element
.addClass( 'oo-ui-pageLayout' );
10851 OO
.inheritClass( OO
.ui
.PageLayout
, OO
.ui
.PanelLayout
);
10856 * An 'active' event is emitted when the page becomes active. Pages become active when they are
10857 * shown in a booklet layout that is configured to display only one page at a time.
10860 * @param {boolean} active Page is active
10866 * Get the symbolic name of the page.
10868 * @return {string} Symbolic name of page
10870 OO
.ui
.PageLayout
.prototype.getName = function () {
10875 * Check if page is active.
10877 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
10878 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
10880 * @return {boolean} Page is active
10882 OO
.ui
.PageLayout
.prototype.isActive = function () {
10883 return this.active
;
10887 * Get outline item.
10889 * The outline item allows users to access the page from the booklet's outline
10890 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
10892 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
10894 OO
.ui
.PageLayout
.prototype.getOutlineItem = function () {
10895 return this.outlineItem
;
10899 * Set or unset the outline item.
10901 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
10902 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
10903 * level), use #setupOutlineItem instead of this method.
10905 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
10908 OO
.ui
.PageLayout
.prototype.setOutlineItem = function ( outlineItem
) {
10909 this.outlineItem
= outlineItem
|| null;
10910 if ( outlineItem
) {
10911 this.setupOutlineItem();
10917 * Set up the outline item.
10919 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
10920 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
10921 * the #setOutlineItem method instead.
10923 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
10926 OO
.ui
.PageLayout
.prototype.setupOutlineItem = function () {
10931 * Set the page to its 'active' state.
10933 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
10934 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
10935 * context, setting the active state on a page does nothing.
10937 * @param {boolean} value Page is active
10940 OO
.ui
.PageLayout
.prototype.setActive = function ( active
) {
10943 if ( active
!== this.active
) {
10944 this.active
= active
;
10945 this.$element
.toggleClass( 'oo-ui-pageLayout-active', active
);
10946 this.emit( 'active', this.active
);
10951 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
10952 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
10953 * by setting the #continuous option to 'true'.
10956 * // A stack layout with two panels, configured to be displayed continously
10957 * var myStack = new OO.ui.StackLayout( {
10959 * new OO.ui.PanelLayout( {
10960 * $content: $( '<p>Panel One</p>' ),
10964 * new OO.ui.PanelLayout( {
10965 * $content: $( '<p>Panel Two</p>' ),
10972 * $( 'body' ).append( myStack.$element );
10975 * @extends OO.ui.PanelLayout
10976 * @mixins OO.ui.mixin.GroupElement
10979 * @param {Object} [config] Configuration options
10980 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
10981 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
10983 OO
.ui
.StackLayout
= function OoUiStackLayout( config
) {
10984 // Configuration initialization
10985 config
= $.extend( { scrollable
: true }, config
);
10987 // Parent constructor
10988 OO
.ui
.StackLayout
.parent
.call( this, config
);
10990 // Mixin constructors
10991 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
10994 this.currentItem
= null;
10995 this.continuous
= !!config
.continuous
;
10998 this.$element
.addClass( 'oo-ui-stackLayout' );
10999 if ( this.continuous
) {
11000 this.$element
.addClass( 'oo-ui-stackLayout-continuous' );
11002 if ( Array
.isArray( config
.items
) ) {
11003 this.addItems( config
.items
);
11009 OO
.inheritClass( OO
.ui
.StackLayout
, OO
.ui
.PanelLayout
);
11010 OO
.mixinClass( OO
.ui
.StackLayout
, OO
.ui
.mixin
.GroupElement
);
11015 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
11016 * {@link #clearItems cleared} or {@link #setItem displayed}.
11019 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
11025 * Get the current panel.
11027 * @return {OO.ui.Layout|null}
11029 OO
.ui
.StackLayout
.prototype.getCurrentItem = function () {
11030 return this.currentItem
;
11034 * Unset the current item.
11037 * @param {OO.ui.StackLayout} layout
11040 OO
.ui
.StackLayout
.prototype.unsetCurrentItem = function () {
11041 var prevItem
= this.currentItem
;
11042 if ( prevItem
=== null ) {
11046 this.currentItem
= null;
11047 this.emit( 'set', null );
11051 * Add panel layouts to the stack layout.
11053 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
11054 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
11057 * @param {OO.ui.Layout[]} items Panels to add
11058 * @param {number} [index] Index of the insertion point
11061 OO
.ui
.StackLayout
.prototype.addItems = function ( items
, index
) {
11062 // Update the visibility
11063 this.updateHiddenState( items
, this.currentItem
);
11066 OO
.ui
.mixin
.GroupElement
.prototype.addItems
.call( this, items
, index
);
11068 if ( !this.currentItem
&& items
.length
) {
11069 this.setItem( items
[ 0 ] );
11076 * Remove the specified panels from the stack layout.
11078 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
11079 * you may wish to use the #clearItems method instead.
11081 * @param {OO.ui.Layout[]} items Panels to remove
11085 OO
.ui
.StackLayout
.prototype.removeItems = function ( items
) {
11087 OO
.ui
.mixin
.GroupElement
.prototype.removeItems
.call( this, items
);
11089 if ( items
.indexOf( this.currentItem
) !== -1 ) {
11090 if ( this.items
.length
) {
11091 this.setItem( this.items
[ 0 ] );
11093 this.unsetCurrentItem();
11101 * Clear all panels from the stack layout.
11103 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
11104 * a subset of panels, use the #removeItems method.
11109 OO
.ui
.StackLayout
.prototype.clearItems = function () {
11110 this.unsetCurrentItem();
11111 OO
.ui
.mixin
.GroupElement
.prototype.clearItems
.call( this );
11117 * Show the specified panel.
11119 * If another panel is currently displayed, it will be hidden.
11121 * @param {OO.ui.Layout} item Panel to show
11125 OO
.ui
.StackLayout
.prototype.setItem = function ( item
) {
11126 if ( item
!== this.currentItem
) {
11127 this.updateHiddenState( this.items
, item
);
11129 if ( this.items
.indexOf( item
) !== -1 ) {
11130 this.currentItem
= item
;
11131 this.emit( 'set', item
);
11133 this.unsetCurrentItem();
11141 * Update the visibility of all items in case of non-continuous view.
11143 * Ensure all items are hidden except for the selected one.
11144 * This method does nothing when the stack is continuous.
11147 * @param {OO.ui.Layout[]} items Item list iterate over
11148 * @param {OO.ui.Layout} [selectedItem] Selected item to show
11150 OO
.ui
.StackLayout
.prototype.updateHiddenState = function ( items
, selectedItem
) {
11153 if ( !this.continuous
) {
11154 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
11155 if ( !selectedItem
|| selectedItem
!== items
[ i
] ) {
11156 items
[ i
].$element
.addClass( 'oo-ui-element-hidden' );
11159 if ( selectedItem
) {
11160 selectedItem
.$element
.removeClass( 'oo-ui-element-hidden' );
11166 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
11167 * items), with small margins between them. Convenient when you need to put a number of block-level
11168 * widgets on a single line next to each other.
11170 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
11173 * // HorizontalLayout with a text input and a label
11174 * var layout = new OO.ui.HorizontalLayout( {
11176 * new OO.ui.LabelWidget( { label: 'Label' } ),
11177 * new OO.ui.TextInputWidget( { value: 'Text' } )
11180 * $( 'body' ).append( layout.$element );
11183 * @extends OO.ui.Layout
11184 * @mixins OO.ui.mixin.GroupElement
11187 * @param {Object} [config] Configuration options
11188 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
11190 OO
.ui
.HorizontalLayout
= function OoUiHorizontalLayout( config
) {
11191 // Configuration initialization
11192 config
= config
|| {};
11194 // Parent constructor
11195 OO
.ui
.HorizontalLayout
.parent
.call( this, config
);
11197 // Mixin constructors
11198 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
11201 this.$element
.addClass( 'oo-ui-horizontalLayout' );
11202 if ( Array
.isArray( config
.items
) ) {
11203 this.addItems( config
.items
);
11209 OO
.inheritClass( OO
.ui
.HorizontalLayout
, OO
.ui
.Layout
);
11210 OO
.mixinClass( OO
.ui
.HorizontalLayout
, OO
.ui
.mixin
.GroupElement
);
11213 * BarToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11214 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11215 * and {@link OO.ui.ListToolGroup ListToolGroup}). The {@link OO.ui.Tool tools} in a BarToolGroup are
11216 * displayed by icon in a single row. The title of the tool is displayed when users move the mouse over
11219 * BarToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar is
11223 * // Example of a BarToolGroup with two tools
11224 * var toolFactory = new OO.ui.ToolFactory();
11225 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11226 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11228 * // We will be placing status text in this element when tools are used
11229 * var $area = $( '<p>' ).text( 'Example of a BarToolGroup with two tools.' );
11231 * // Define the tools that we're going to place in our toolbar
11233 * // Create a class inheriting from OO.ui.Tool
11234 * function PictureTool() {
11235 * PictureTool.parent.apply( this, arguments );
11237 * OO.inheritClass( PictureTool, OO.ui.Tool );
11238 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
11239 * // of 'icon' and 'title' (displayed icon and text).
11240 * PictureTool.static.name = 'picture';
11241 * PictureTool.static.icon = 'picture';
11242 * PictureTool.static.title = 'Insert picture';
11243 * // Defines the action that will happen when this tool is selected (clicked).
11244 * PictureTool.prototype.onSelect = function () {
11245 * $area.text( 'Picture tool clicked!' );
11246 * // Never display this tool as "active" (selected).
11247 * this.setActive( false );
11249 * // Make this tool available in our toolFactory and thus our toolbar
11250 * toolFactory.register( PictureTool );
11252 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
11253 * // little popup window (a PopupWidget).
11254 * function HelpTool( toolGroup, config ) {
11255 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11260 * this.popup.$body.append( '<p>I am helpful!</p>' );
11262 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11263 * HelpTool.static.name = 'help';
11264 * HelpTool.static.icon = 'help';
11265 * HelpTool.static.title = 'Help';
11266 * toolFactory.register( HelpTool );
11268 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11269 * // used once (but not all defined tools must be used).
11272 * // 'bar' tool groups display tools by icon only
11274 * include: [ 'picture', 'help' ]
11278 * // Create some UI around the toolbar and place it in the document
11279 * var frame = new OO.ui.PanelLayout( {
11283 * var contentFrame = new OO.ui.PanelLayout( {
11287 * frame.$element.append(
11288 * toolbar.$element,
11289 * contentFrame.$element.append( $area )
11291 * $( 'body' ).append( frame.$element );
11293 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11295 * toolbar.initialize();
11297 * For more information about how to add tools to a bar tool group, please see {@link OO.ui.ToolGroup toolgroup}.
11298 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11300 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11303 * @extends OO.ui.ToolGroup
11306 * @param {OO.ui.Toolbar} toolbar
11307 * @param {Object} [config] Configuration options
11309 OO
.ui
.BarToolGroup
= function OoUiBarToolGroup( toolbar
, config
) {
11310 // Allow passing positional parameters inside the config object
11311 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11313 toolbar
= config
.toolbar
;
11316 // Parent constructor
11317 OO
.ui
.BarToolGroup
.parent
.call( this, toolbar
, config
);
11320 this.$element
.addClass( 'oo-ui-barToolGroup' );
11325 OO
.inheritClass( OO
.ui
.BarToolGroup
, OO
.ui
.ToolGroup
);
11327 /* Static Properties */
11329 OO
.ui
.BarToolGroup
.static.titleTooltips
= true;
11331 OO
.ui
.BarToolGroup
.static.accelTooltips
= true;
11333 OO
.ui
.BarToolGroup
.static.name
= 'bar';
11336 * PopupToolGroup is an abstract base class used by both {@link OO.ui.MenuToolGroup MenuToolGroup}
11337 * and {@link OO.ui.ListToolGroup ListToolGroup} to provide a popup--an overlaid menu or list of tools with an
11338 * optional icon and label. This class can be used for other base classes that also use this functionality.
11342 * @extends OO.ui.ToolGroup
11343 * @mixins OO.ui.mixin.IconElement
11344 * @mixins OO.ui.mixin.IndicatorElement
11345 * @mixins OO.ui.mixin.LabelElement
11346 * @mixins OO.ui.mixin.TitledElement
11347 * @mixins OO.ui.mixin.ClippableElement
11348 * @mixins OO.ui.mixin.TabIndexedElement
11351 * @param {OO.ui.Toolbar} toolbar
11352 * @param {Object} [config] Configuration options
11353 * @cfg {string} [header] Text to display at the top of the popup
11355 OO
.ui
.PopupToolGroup
= function OoUiPopupToolGroup( toolbar
, config
) {
11356 // Allow passing positional parameters inside the config object
11357 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11359 toolbar
= config
.toolbar
;
11362 // Configuration initialization
11363 config
= config
|| {};
11365 // Parent constructor
11366 OO
.ui
.PopupToolGroup
.parent
.call( this, toolbar
, config
);
11369 this.active
= false;
11370 this.dragging
= false;
11371 this.onBlurHandler
= this.onBlur
.bind( this );
11372 this.$handle
= $( '<span>' );
11374 // Mixin constructors
11375 OO
.ui
.mixin
.IconElement
.call( this, config
);
11376 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
11377 OO
.ui
.mixin
.LabelElement
.call( this, config
);
11378 OO
.ui
.mixin
.TitledElement
.call( this, config
);
11379 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
11380 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
11384 keydown
: this.onHandleMouseKeyDown
.bind( this ),
11385 keyup
: this.onHandleMouseKeyUp
.bind( this ),
11386 mousedown
: this.onHandleMouseKeyDown
.bind( this ),
11387 mouseup
: this.onHandleMouseKeyUp
.bind( this )
11392 .addClass( 'oo-ui-popupToolGroup-handle' )
11393 .append( this.$icon
, this.$label
, this.$indicator
);
11394 // If the pop-up should have a header, add it to the top of the toolGroup.
11395 // Note: If this feature is useful for other widgets, we could abstract it into an
11396 // OO.ui.HeaderedElement mixin constructor.
11397 if ( config
.header
!== undefined ) {
11399 .prepend( $( '<span>' )
11400 .addClass( 'oo-ui-popupToolGroup-header' )
11401 .text( config
.header
)
11405 .addClass( 'oo-ui-popupToolGroup' )
11406 .prepend( this.$handle
);
11411 OO
.inheritClass( OO
.ui
.PopupToolGroup
, OO
.ui
.ToolGroup
);
11412 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.IconElement
);
11413 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.IndicatorElement
);
11414 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.LabelElement
);
11415 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.TitledElement
);
11416 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.ClippableElement
);
11417 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.TabIndexedElement
);
11424 OO
.ui
.PopupToolGroup
.prototype.setDisabled = function () {
11426 OO
.ui
.PopupToolGroup
.parent
.prototype.setDisabled
.apply( this, arguments
);
11428 if ( this.isDisabled() && this.isElementAttached() ) {
11429 this.setActive( false );
11434 * Handle focus being lost.
11436 * The event is actually generated from a mouseup/keyup, so it is not a normal blur event object.
11439 * @param {jQuery.Event} e Mouse up or key up event
11441 OO
.ui
.PopupToolGroup
.prototype.onBlur = function ( e
) {
11442 // Only deactivate when clicking outside the dropdown element
11443 if ( $( e
.target
).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element
[ 0 ] ) {
11444 this.setActive( false );
11451 OO
.ui
.PopupToolGroup
.prototype.onMouseKeyUp = function ( e
) {
11452 // Only close toolgroup when a tool was actually selected
11454 !this.isDisabled() && this.pressed
&& this.pressed
=== this.getTargetTool( e
) &&
11455 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11457 this.setActive( false );
11459 return OO
.ui
.PopupToolGroup
.parent
.prototype.onMouseKeyUp
.call( this, e
);
11463 * Handle mouse up and key up events.
11466 * @param {jQuery.Event} e Mouse up or key up event
11468 OO
.ui
.PopupToolGroup
.prototype.onHandleMouseKeyUp = function ( e
) {
11470 !this.isDisabled() &&
11471 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11478 * Handle mouse down and key down events.
11481 * @param {jQuery.Event} e Mouse down or key down event
11483 OO
.ui
.PopupToolGroup
.prototype.onHandleMouseKeyDown = function ( e
) {
11485 !this.isDisabled() &&
11486 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11488 this.setActive( !this.active
);
11494 * Switch into 'active' mode.
11496 * When active, the popup is visible. A mouseup event anywhere in the document will trigger
11499 OO
.ui
.PopupToolGroup
.prototype.setActive = function ( value
) {
11500 var containerWidth
, containerLeft
;
11502 if ( this.active
!== value
) {
11503 this.active
= value
;
11505 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler
);
11506 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler
);
11508 this.$clippable
.css( 'left', '' );
11509 // Try anchoring the popup to the left first
11510 this.$element
.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
11511 this.toggleClipping( true );
11512 if ( this.isClippedHorizontally() ) {
11513 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
11514 this.toggleClipping( false );
11516 .removeClass( 'oo-ui-popupToolGroup-left' )
11517 .addClass( 'oo-ui-popupToolGroup-right' );
11518 this.toggleClipping( true );
11520 if ( this.isClippedHorizontally() ) {
11521 // Anchoring to the right also caused the popup to clip, so just make it fill the container
11522 containerWidth
= this.$clippableScrollableContainer
.width();
11523 containerLeft
= this.$clippableScrollableContainer
.offset().left
;
11525 this.toggleClipping( false );
11526 this.$element
.removeClass( 'oo-ui-popupToolGroup-right' );
11528 this.$clippable
.css( {
11529 left
: -( this.$element
.offset().left
- containerLeft
),
11530 width
: containerWidth
11534 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler
);
11535 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler
);
11536 this.$element
.removeClass(
11537 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
11539 this.toggleClipping( false );
11545 * ListToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11546 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11547 * and {@link OO.ui.BarToolGroup BarToolGroup}). The {@link OO.ui.Tool tools} in a ListToolGroup are displayed
11548 * by label in a dropdown menu. The title of the tool is used as the label text. The menu itself can be configured
11549 * with a label, icon, indicator, header, and title.
11551 * ListToolGroups can be configured to be expanded and collapsed. Collapsed lists will have a ‘More’ option that
11552 * users can select to see the full list of tools. If a collapsed toolgroup is expanded, a ‘Fewer’ option permits
11553 * users to collapse the list again.
11555 * ListToolGroups are created by a {@link OO.ui.ToolGroupFactory toolgroup factory} when the toolbar is set up. The factory
11556 * requires the ListToolGroup's symbolic name, 'list', which is specified along with the other configurations. For more
11557 * information about how to add tools to a ListToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11560 * // Example of a ListToolGroup
11561 * var toolFactory = new OO.ui.ToolFactory();
11562 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11563 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11565 * // Configure and register two tools
11566 * function SettingsTool() {
11567 * SettingsTool.parent.apply( this, arguments );
11569 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11570 * SettingsTool.static.name = 'settings';
11571 * SettingsTool.static.icon = 'settings';
11572 * SettingsTool.static.title = 'Change settings';
11573 * SettingsTool.prototype.onSelect = function () {
11574 * this.setActive( false );
11576 * toolFactory.register( SettingsTool );
11577 * // Register two more tools, nothing interesting here
11578 * function StuffTool() {
11579 * StuffTool.parent.apply( this, arguments );
11581 * OO.inheritClass( StuffTool, OO.ui.Tool );
11582 * StuffTool.static.name = 'stuff';
11583 * StuffTool.static.icon = 'ellipsis';
11584 * StuffTool.static.title = 'Change the world';
11585 * StuffTool.prototype.onSelect = function () {
11586 * this.setActive( false );
11588 * toolFactory.register( StuffTool );
11591 * // Configurations for list toolgroup.
11593 * label: 'ListToolGroup',
11594 * indicator: 'down',
11596 * title: 'This is the title, displayed when user moves the mouse over the list toolgroup',
11597 * header: 'This is the header',
11598 * include: [ 'settings', 'stuff' ],
11599 * allowCollapse: ['stuff']
11603 * // Create some UI around the toolbar and place it in the document
11604 * var frame = new OO.ui.PanelLayout( {
11608 * frame.$element.append(
11611 * $( 'body' ).append( frame.$element );
11612 * // Build the toolbar. This must be done after the toolbar has been appended to the document.
11613 * toolbar.initialize();
11615 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11617 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11620 * @extends OO.ui.PopupToolGroup
11623 * @param {OO.ui.Toolbar} toolbar
11624 * @param {Object} [config] Configuration options
11625 * @cfg {Array} [allowCollapse] Allow the specified tools to be collapsed. By default, collapsible tools
11626 * will only be displayed if users click the ‘More’ option displayed at the bottom of the list. If
11627 * the list is expanded, a ‘Fewer’ option permits users to collapse the list again. Any tools that
11628 * are included in the toolgroup, but are not designated as collapsible, will always be displayed.
11629 * To open a collapsible list in its expanded state, set #expanded to 'true'.
11630 * @cfg {Array} [forceExpand] Expand the specified tools. All other tools will be designated as collapsible.
11631 * Unless #expanded is set to true, the collapsible tools will be collapsed when the list is first opened.
11632 * @cfg {boolean} [expanded=false] Expand collapsible tools. This config is only relevant if tools have
11633 * been designated as collapsible. When expanded is set to true, all tools in the group will be displayed
11634 * when the list is first opened. Users can collapse the list with a ‘Fewer’ option at the bottom.
11636 OO
.ui
.ListToolGroup
= function OoUiListToolGroup( toolbar
, config
) {
11637 // Allow passing positional parameters inside the config object
11638 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11640 toolbar
= config
.toolbar
;
11643 // Configuration initialization
11644 config
= config
|| {};
11646 // Properties (must be set before parent constructor, which calls #populate)
11647 this.allowCollapse
= config
.allowCollapse
;
11648 this.forceExpand
= config
.forceExpand
;
11649 this.expanded
= config
.expanded
!== undefined ? config
.expanded
: false;
11650 this.collapsibleTools
= [];
11652 // Parent constructor
11653 OO
.ui
.ListToolGroup
.parent
.call( this, toolbar
, config
);
11656 this.$element
.addClass( 'oo-ui-listToolGroup' );
11661 OO
.inheritClass( OO
.ui
.ListToolGroup
, OO
.ui
.PopupToolGroup
);
11663 /* Static Properties */
11665 OO
.ui
.ListToolGroup
.static.name
= 'list';
11672 OO
.ui
.ListToolGroup
.prototype.populate = function () {
11673 var i
, len
, allowCollapse
= [];
11675 OO
.ui
.ListToolGroup
.parent
.prototype.populate
.call( this );
11677 // Update the list of collapsible tools
11678 if ( this.allowCollapse
!== undefined ) {
11679 allowCollapse
= this.allowCollapse
;
11680 } else if ( this.forceExpand
!== undefined ) {
11681 allowCollapse
= OO
.simpleArrayDifference( Object
.keys( this.tools
), this.forceExpand
);
11684 this.collapsibleTools
= [];
11685 for ( i
= 0, len
= allowCollapse
.length
; i
< len
; i
++ ) {
11686 if ( this.tools
[ allowCollapse
[ i
] ] !== undefined ) {
11687 this.collapsibleTools
.push( this.tools
[ allowCollapse
[ i
] ] );
11691 // Keep at the end, even when tools are added
11692 this.$group
.append( this.getExpandCollapseTool().$element
);
11694 this.getExpandCollapseTool().toggle( this.collapsibleTools
.length
!== 0 );
11695 this.updateCollapsibleState();
11698 OO
.ui
.ListToolGroup
.prototype.getExpandCollapseTool = function () {
11699 var ExpandCollapseTool
;
11700 if ( this.expandCollapseTool
=== undefined ) {
11701 ExpandCollapseTool = function () {
11702 ExpandCollapseTool
.parent
.apply( this, arguments
);
11705 OO
.inheritClass( ExpandCollapseTool
, OO
.ui
.Tool
);
11707 ExpandCollapseTool
.prototype.onSelect = function () {
11708 this.toolGroup
.expanded
= !this.toolGroup
.expanded
;
11709 this.toolGroup
.updateCollapsibleState();
11710 this.setActive( false );
11712 ExpandCollapseTool
.prototype.onUpdateState = function () {
11713 // Do nothing. Tool interface requires an implementation of this function.
11716 ExpandCollapseTool
.static.name
= 'more-fewer';
11718 this.expandCollapseTool
= new ExpandCollapseTool( this );
11720 return this.expandCollapseTool
;
11726 OO
.ui
.ListToolGroup
.prototype.onMouseKeyUp = function ( e
) {
11727 // Do not close the popup when the user wants to show more/fewer tools
11729 $( e
.target
).closest( '.oo-ui-tool-name-more-fewer' ).length
&&
11730 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11732 // HACK: Prevent the popup list from being hidden. Skip the PopupToolGroup implementation (which
11733 // hides the popup list when a tool is selected) and call ToolGroup's implementation directly.
11734 return OO
.ui
.ListToolGroup
.parent
.parent
.prototype.onMouseKeyUp
.call( this, e
);
11736 return OO
.ui
.ListToolGroup
.parent
.prototype.onMouseKeyUp
.call( this, e
);
11740 OO
.ui
.ListToolGroup
.prototype.updateCollapsibleState = function () {
11743 this.getExpandCollapseTool()
11744 .setIcon( this.expanded
? 'collapse' : 'expand' )
11745 .setTitle( OO
.ui
.msg( this.expanded
? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
11747 for ( i
= 0, len
= this.collapsibleTools
.length
; i
< len
; i
++ ) {
11748 this.collapsibleTools
[ i
].toggle( this.expanded
);
11753 * MenuToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11754 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.BarToolGroup BarToolGroup}
11755 * and {@link OO.ui.ListToolGroup ListToolGroup}). MenuToolGroups contain selectable {@link OO.ui.Tool tools},
11756 * which are displayed by label in a dropdown menu. The tool's title is used as the label text, and the
11757 * menu label is updated to reflect which tool or tools are currently selected. If no tools are selected,
11758 * the menu label is empty. The menu can be configured with an indicator, icon, title, and/or header.
11760 * MenuToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar
11761 * is set up. Note that all tools must define an {@link OO.ui.Tool#onUpdateState onUpdateState} method if
11762 * a MenuToolGroup is used.
11765 * // Example of a MenuToolGroup
11766 * var toolFactory = new OO.ui.ToolFactory();
11767 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11768 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11770 * // We will be placing status text in this element when tools are used
11771 * var $area = $( '<p>' ).text( 'An example of a MenuToolGroup. Select a tool from the dropdown menu.' );
11773 * // Define the tools that we're going to place in our toolbar
11775 * function SettingsTool() {
11776 * SettingsTool.parent.apply( this, arguments );
11777 * this.reallyActive = false;
11779 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11780 * SettingsTool.static.name = 'settings';
11781 * SettingsTool.static.icon = 'settings';
11782 * SettingsTool.static.title = 'Change settings';
11783 * SettingsTool.prototype.onSelect = function () {
11784 * $area.text( 'Settings tool clicked!' );
11785 * // Toggle the active state on each click
11786 * this.reallyActive = !this.reallyActive;
11787 * this.setActive( this.reallyActive );
11788 * // To update the menu label
11789 * this.toolbar.emit( 'updateState' );
11791 * SettingsTool.prototype.onUpdateState = function () {
11793 * toolFactory.register( SettingsTool );
11795 * function StuffTool() {
11796 * StuffTool.parent.apply( this, arguments );
11797 * this.reallyActive = false;
11799 * OO.inheritClass( StuffTool, OO.ui.Tool );
11800 * StuffTool.static.name = 'stuff';
11801 * StuffTool.static.icon = 'ellipsis';
11802 * StuffTool.static.title = 'More stuff';
11803 * StuffTool.prototype.onSelect = function () {
11804 * $area.text( 'More stuff tool clicked!' );
11805 * // Toggle the active state on each click
11806 * this.reallyActive = !this.reallyActive;
11807 * this.setActive( this.reallyActive );
11808 * // To update the menu label
11809 * this.toolbar.emit( 'updateState' );
11811 * StuffTool.prototype.onUpdateState = function () {
11813 * toolFactory.register( StuffTool );
11815 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11816 * // used once (but not all defined tools must be used).
11820 * header: 'This is the (optional) header',
11821 * title: 'This is the (optional) title',
11822 * indicator: 'down',
11823 * include: [ 'settings', 'stuff' ]
11827 * // Create some UI around the toolbar and place it in the document
11828 * var frame = new OO.ui.PanelLayout( {
11832 * var contentFrame = new OO.ui.PanelLayout( {
11836 * frame.$element.append(
11837 * toolbar.$element,
11838 * contentFrame.$element.append( $area )
11840 * $( 'body' ).append( frame.$element );
11842 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11844 * toolbar.initialize();
11845 * toolbar.emit( 'updateState' );
11847 * For more information about how to add tools to a MenuToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11848 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki] [1].
11850 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11853 * @extends OO.ui.PopupToolGroup
11856 * @param {OO.ui.Toolbar} toolbar
11857 * @param {Object} [config] Configuration options
11859 OO
.ui
.MenuToolGroup
= function OoUiMenuToolGroup( toolbar
, config
) {
11860 // Allow passing positional parameters inside the config object
11861 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11863 toolbar
= config
.toolbar
;
11866 // Configuration initialization
11867 config
= config
|| {};
11869 // Parent constructor
11870 OO
.ui
.MenuToolGroup
.parent
.call( this, toolbar
, config
);
11873 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
11876 this.$element
.addClass( 'oo-ui-menuToolGroup' );
11881 OO
.inheritClass( OO
.ui
.MenuToolGroup
, OO
.ui
.PopupToolGroup
);
11883 /* Static Properties */
11885 OO
.ui
.MenuToolGroup
.static.name
= 'menu';
11890 * Handle the toolbar state being updated.
11892 * When the state changes, the title of each active item in the menu will be joined together and
11893 * used as a label for the group. The label will be empty if none of the items are active.
11897 OO
.ui
.MenuToolGroup
.prototype.onUpdateState = function () {
11901 for ( name
in this.tools
) {
11902 if ( this.tools
[ name
].isActive() ) {
11903 labelTexts
.push( this.tools
[ name
].getTitle() );
11907 this.setLabel( labelTexts
.join( ', ' ) || ' ' );
11911 * Popup tools open a popup window when they are selected from the {@link OO.ui.Toolbar toolbar}. Each popup tool is configured
11912 * 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
11913 * an #onSelect or #onUpdateState method, as these methods have been implemented already.
11915 * // Example of a popup tool. When selected, a popup tool displays
11916 * // a popup window.
11917 * function HelpTool( toolGroup, config ) {
11918 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11923 * this.popup.$body.append( '<p>I am helpful!</p>' );
11925 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11926 * HelpTool.static.name = 'help';
11927 * HelpTool.static.icon = 'help';
11928 * HelpTool.static.title = 'Help';
11929 * toolFactory.register( HelpTool );
11931 * For an example of a toolbar that contains a popup tool, see {@link OO.ui.Toolbar toolbars}. For more information about
11932 * toolbars in genreral, please see the [OOjs UI documentation on MediaWiki][1].
11934 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11938 * @extends OO.ui.Tool
11939 * @mixins OO.ui.mixin.PopupElement
11942 * @param {OO.ui.ToolGroup} toolGroup
11943 * @param {Object} [config] Configuration options
11945 OO
.ui
.PopupTool
= function OoUiPopupTool( toolGroup
, config
) {
11946 // Allow passing positional parameters inside the config object
11947 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
11948 config
= toolGroup
;
11949 toolGroup
= config
.toolGroup
;
11952 // Parent constructor
11953 OO
.ui
.PopupTool
.parent
.call( this, toolGroup
, config
);
11955 // Mixin constructors
11956 OO
.ui
.mixin
.PopupElement
.call( this, config
);
11960 .addClass( 'oo-ui-popupTool' )
11961 .append( this.popup
.$element
);
11966 OO
.inheritClass( OO
.ui
.PopupTool
, OO
.ui
.Tool
);
11967 OO
.mixinClass( OO
.ui
.PopupTool
, OO
.ui
.mixin
.PopupElement
);
11972 * Handle the tool being selected.
11976 OO
.ui
.PopupTool
.prototype.onSelect = function () {
11977 if ( !this.isDisabled() ) {
11978 this.popup
.toggle();
11980 this.setActive( false );
11985 * Handle the toolbar state being updated.
11989 OO
.ui
.PopupTool
.prototype.onUpdateState = function () {
11990 this.setActive( false );
11994 * A ToolGroupTool is a special sort of tool that can contain other {@link OO.ui.Tool tools}
11995 * and {@link OO.ui.ToolGroup toolgroups}. The ToolGroupTool was specifically designed to be used
11996 * inside a {@link OO.ui.BarToolGroup bar} toolgroup to provide access to additional tools from
11997 * the bar item. Included tools will be displayed in a dropdown {@link OO.ui.ListToolGroup list}
11998 * when the ToolGroupTool is selected.
12000 * // Example: ToolGroupTool with two nested tools, 'setting1' and 'setting2', defined elsewhere.
12002 * function SettingsTool() {
12003 * SettingsTool.parent.apply( this, arguments );
12005 * OO.inheritClass( SettingsTool, OO.ui.ToolGroupTool );
12006 * SettingsTool.static.name = 'settings';
12007 * SettingsTool.static.title = 'Change settings';
12008 * SettingsTool.static.groupConfig = {
12009 * icon: 'settings',
12010 * label: 'ToolGroupTool',
12011 * include: [ 'setting1', 'setting2' ]
12013 * toolFactory.register( SettingsTool );
12015 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
12017 * Please note that this implementation is subject to change per [T74159] [2].
12019 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars#ToolGroupTool
12020 * [2]: https://phabricator.wikimedia.org/T74159
12024 * @extends OO.ui.Tool
12027 * @param {OO.ui.ToolGroup} toolGroup
12028 * @param {Object} [config] Configuration options
12030 OO
.ui
.ToolGroupTool
= function OoUiToolGroupTool( toolGroup
, config
) {
12031 // Allow passing positional parameters inside the config object
12032 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
12033 config
= toolGroup
;
12034 toolGroup
= config
.toolGroup
;
12037 // Parent constructor
12038 OO
.ui
.ToolGroupTool
.parent
.call( this, toolGroup
, config
);
12041 this.innerToolGroup
= this.createGroup( this.constructor.static.groupConfig
);
12044 this.innerToolGroup
.connect( this, { disable
: 'onToolGroupDisable' } );
12047 this.$link
.remove();
12049 .addClass( 'oo-ui-toolGroupTool' )
12050 .append( this.innerToolGroup
.$element
);
12055 OO
.inheritClass( OO
.ui
.ToolGroupTool
, OO
.ui
.Tool
);
12057 /* Static Properties */
12060 * Toolgroup configuration.
12062 * The toolgroup configuration consists of the tools to include, as well as an icon and label
12063 * to use for the bar item. Tools can be included by symbolic name, group, or with the
12064 * wildcard selector. Please see {@link OO.ui.ToolGroup toolgroup} for more information.
12066 * @property {Object.<string,Array>}
12068 OO
.ui
.ToolGroupTool
.static.groupConfig
= {};
12073 * Handle the tool being selected.
12077 OO
.ui
.ToolGroupTool
.prototype.onSelect = function () {
12078 this.innerToolGroup
.setActive( !this.innerToolGroup
.active
);
12083 * Synchronize disabledness state of the tool with the inner toolgroup.
12086 * @param {boolean} disabled Element is disabled
12088 OO
.ui
.ToolGroupTool
.prototype.onToolGroupDisable = function ( disabled
) {
12089 this.setDisabled( disabled
);
12093 * Handle the toolbar state being updated.
12097 OO
.ui
.ToolGroupTool
.prototype.onUpdateState = function () {
12098 this.setActive( false );
12102 * Build a {@link OO.ui.ToolGroup toolgroup} from the specified configuration.
12104 * @param {Object.<string,Array>} group Toolgroup configuration. Please see {@link OO.ui.ToolGroup toolgroup} for
12105 * more information.
12106 * @return {OO.ui.ListToolGroup}
12108 OO
.ui
.ToolGroupTool
.prototype.createGroup = function ( group
) {
12109 if ( group
.include
=== '*' ) {
12110 // Apply defaults to catch-all groups
12111 if ( group
.label
=== undefined ) {
12112 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
12116 return this.toolbar
.getToolGroupFactory().create( 'list', this.toolbar
, group
);
12120 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
12122 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
12127 * @extends OO.ui.mixin.GroupElement
12130 * @param {Object} [config] Configuration options
12132 OO
.ui
.mixin
.GroupWidget
= function OoUiMixinGroupWidget( config
) {
12133 // Parent constructor
12134 OO
.ui
.mixin
.GroupWidget
.parent
.call( this, config
);
12139 OO
.inheritClass( OO
.ui
.mixin
.GroupWidget
, OO
.ui
.mixin
.GroupElement
);
12144 * Set the disabled state of the widget.
12146 * This will also update the disabled state of child widgets.
12148 * @param {boolean} disabled Disable widget
12151 OO
.ui
.mixin
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
12155 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
12156 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
12158 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
12159 if ( this.items
) {
12160 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
12161 this.items
[ i
].updateDisabled();
12169 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
12171 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
12172 * allows bidirectional communication.
12174 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
12182 OO
.ui
.mixin
.ItemWidget
= function OoUiMixinItemWidget() {
12189 * Check if widget is disabled.
12191 * Checks parent if present, making disabled state inheritable.
12193 * @return {boolean} Widget is disabled
12195 OO
.ui
.mixin
.ItemWidget
.prototype.isDisabled = function () {
12196 return this.disabled
||
12197 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
12201 * Set group element is in.
12203 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
12206 OO
.ui
.mixin
.ItemWidget
.prototype.setElementGroup = function ( group
) {
12208 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
12209 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
12211 // Initialize item disabled states
12212 this.updateDisabled();
12218 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
12219 * Controls include moving items up and down, removing items, and adding different kinds of items.
12221 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
12224 * @extends OO.ui.Widget
12225 * @mixins OO.ui.mixin.GroupElement
12226 * @mixins OO.ui.mixin.IconElement
12229 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
12230 * @param {Object} [config] Configuration options
12231 * @cfg {Object} [abilities] List of abilties
12232 * @cfg {boolean} [abilities.move=true] Allow moving movable items
12233 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
12235 OO
.ui
.OutlineControlsWidget
= function OoUiOutlineControlsWidget( outline
, config
) {
12236 // Allow passing positional parameters inside the config object
12237 if ( OO
.isPlainObject( outline
) && config
=== undefined ) {
12239 outline
= config
.outline
;
12242 // Configuration initialization
12243 config
= $.extend( { icon
: 'add' }, config
);
12245 // Parent constructor
12246 OO
.ui
.OutlineControlsWidget
.parent
.call( this, config
);
12248 // Mixin constructors
12249 OO
.ui
.mixin
.GroupElement
.call( this, config
);
12250 OO
.ui
.mixin
.IconElement
.call( this, config
);
12253 this.outline
= outline
;
12254 this.$movers
= $( '<div>' );
12255 this.upButton
= new OO
.ui
.ButtonWidget( {
12258 title
: OO
.ui
.msg( 'ooui-outline-control-move-up' )
12260 this.downButton
= new OO
.ui
.ButtonWidget( {
12263 title
: OO
.ui
.msg( 'ooui-outline-control-move-down' )
12265 this.removeButton
= new OO
.ui
.ButtonWidget( {
12268 title
: OO
.ui
.msg( 'ooui-outline-control-remove' )
12270 this.abilities
= { move: true, remove
: true };
12273 outline
.connect( this, {
12274 select
: 'onOutlineChange',
12275 add
: 'onOutlineChange',
12276 remove
: 'onOutlineChange'
12278 this.upButton
.connect( this, { click
: [ 'emit', 'move', -1 ] } );
12279 this.downButton
.connect( this, { click
: [ 'emit', 'move', 1 ] } );
12280 this.removeButton
.connect( this, { click
: [ 'emit', 'remove' ] } );
12283 this.$element
.addClass( 'oo-ui-outlineControlsWidget' );
12284 this.$group
.addClass( 'oo-ui-outlineControlsWidget-items' );
12286 .addClass( 'oo-ui-outlineControlsWidget-movers' )
12287 .append( this.removeButton
.$element
, this.upButton
.$element
, this.downButton
.$element
);
12288 this.$element
.append( this.$icon
, this.$group
, this.$movers
);
12289 this.setAbilities( config
.abilities
|| {} );
12294 OO
.inheritClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.Widget
);
12295 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.mixin
.GroupElement
);
12296 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.mixin
.IconElement
);
12302 * @param {number} places Number of places to move
12314 * @param {Object} abilities List of abilties
12315 * @param {boolean} [abilities.move] Allow moving movable items
12316 * @param {boolean} [abilities.remove] Allow removing removable items
12318 OO
.ui
.OutlineControlsWidget
.prototype.setAbilities = function ( abilities
) {
12321 for ( ability
in this.abilities
) {
12322 if ( abilities
[ ability
] !== undefined ) {
12323 this.abilities
[ ability
] = !!abilities
[ ability
];
12327 this.onOutlineChange();
12332 * Handle outline change events.
12334 OO
.ui
.OutlineControlsWidget
.prototype.onOutlineChange = function () {
12335 var i
, len
, firstMovable
, lastMovable
,
12336 items
= this.outline
.getItems(),
12337 selectedItem
= this.outline
.getSelectedItem(),
12338 movable
= this.abilities
.move && selectedItem
&& selectedItem
.isMovable(),
12339 removable
= this.abilities
.remove
&& selectedItem
&& selectedItem
.isRemovable();
12343 len
= items
.length
;
12344 while ( ++i
< len
) {
12345 if ( items
[ i
].isMovable() ) {
12346 firstMovable
= items
[ i
];
12352 if ( items
[ i
].isMovable() ) {
12353 lastMovable
= items
[ i
];
12358 this.upButton
.setDisabled( !movable
|| selectedItem
=== firstMovable
);
12359 this.downButton
.setDisabled( !movable
|| selectedItem
=== lastMovable
);
12360 this.removeButton
.setDisabled( !removable
);
12364 * ToggleWidget implements basic behavior of widgets with an on/off state.
12365 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
12369 * @extends OO.ui.Widget
12372 * @param {Object} [config] Configuration options
12373 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
12374 * By default, the toggle is in the 'off' state.
12376 OO
.ui
.ToggleWidget
= function OoUiToggleWidget( config
) {
12377 // Configuration initialization
12378 config
= config
|| {};
12380 // Parent constructor
12381 OO
.ui
.ToggleWidget
.parent
.call( this, config
);
12387 this.$element
.addClass( 'oo-ui-toggleWidget' );
12388 this.setValue( !!config
.value
);
12393 OO
.inheritClass( OO
.ui
.ToggleWidget
, OO
.ui
.Widget
);
12400 * A change event is emitted when the on/off state of the toggle changes.
12402 * @param {boolean} value Value representing the new state of the toggle
12408 * Get the value representing the toggle’s state.
12410 * @return {boolean} The on/off state of the toggle
12412 OO
.ui
.ToggleWidget
.prototype.getValue = function () {
12417 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
12419 * @param {boolean} value The state of the toggle
12423 OO
.ui
.ToggleWidget
.prototype.setValue = function ( value
) {
12425 if ( this.value
!== value
) {
12426 this.value
= value
;
12427 this.emit( 'change', value
);
12428 this.$element
.toggleClass( 'oo-ui-toggleWidget-on', value
);
12429 this.$element
.toggleClass( 'oo-ui-toggleWidget-off', !value
);
12430 this.$element
.attr( 'aria-checked', value
.toString() );
12436 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
12437 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
12438 * removed, and cleared from the group.
12441 * // Example: A ButtonGroupWidget with two buttons
12442 * var button1 = new OO.ui.PopupButtonWidget( {
12443 * label: 'Select a category',
12446 * $content: $( '<p>List of categories...</p>' ),
12451 * var button2 = new OO.ui.ButtonWidget( {
12452 * label: 'Add item'
12454 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
12455 * items: [button1, button2]
12457 * $( 'body' ).append( buttonGroup.$element );
12460 * @extends OO.ui.Widget
12461 * @mixins OO.ui.mixin.GroupElement
12464 * @param {Object} [config] Configuration options
12465 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
12467 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
12468 // Configuration initialization
12469 config
= config
|| {};
12471 // Parent constructor
12472 OO
.ui
.ButtonGroupWidget
.parent
.call( this, config
);
12474 // Mixin constructors
12475 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
12478 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
12479 if ( Array
.isArray( config
.items
) ) {
12480 this.addItems( config
.items
);
12486 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
12487 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.GroupElement
);
12490 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
12491 * feels, and functionality can be customized via the class’s configuration options
12492 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12495 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
12498 * // A button widget
12499 * var button = new OO.ui.ButtonWidget( {
12500 * label: 'Button with Icon',
12502 * iconTitle: 'Remove'
12504 * $( 'body' ).append( button.$element );
12506 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
12509 * @extends OO.ui.Widget
12510 * @mixins OO.ui.mixin.ButtonElement
12511 * @mixins OO.ui.mixin.IconElement
12512 * @mixins OO.ui.mixin.IndicatorElement
12513 * @mixins OO.ui.mixin.LabelElement
12514 * @mixins OO.ui.mixin.TitledElement
12515 * @mixins OO.ui.mixin.FlaggedElement
12516 * @mixins OO.ui.mixin.TabIndexedElement
12517 * @mixins OO.ui.mixin.AccessKeyedElement
12520 * @param {Object} [config] Configuration options
12521 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
12522 * @cfg {string} [target] The frame or window in which to open the hyperlink.
12523 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
12525 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
12526 // Configuration initialization
12527 config
= config
|| {};
12529 // Parent constructor
12530 OO
.ui
.ButtonWidget
.parent
.call( this, config
);
12532 // Mixin constructors
12533 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
12534 OO
.ui
.mixin
.IconElement
.call( this, config
);
12535 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
12536 OO
.ui
.mixin
.LabelElement
.call( this, config
);
12537 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
12538 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
12539 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
12540 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$button
} ) );
12544 this.target
= null;
12545 this.noFollow
= false;
12548 this.connect( this, { disable
: 'onDisable' } );
12551 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
12553 .addClass( 'oo-ui-buttonWidget' )
12554 .append( this.$button
);
12555 this.setHref( config
.href
);
12556 this.setTarget( config
.target
);
12557 this.setNoFollow( config
.noFollow
);
12562 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
12563 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
12564 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IconElement
);
12565 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
12566 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.LabelElement
);
12567 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TitledElement
);
12568 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
12569 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
12570 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
12577 OO
.ui
.ButtonWidget
.prototype.onMouseDown = function ( e
) {
12578 if ( !this.isDisabled() ) {
12579 // Remove the tab-index while the button is down to prevent the button from stealing focus
12580 this.$button
.removeAttr( 'tabindex' );
12583 return OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown
.call( this, e
);
12589 OO
.ui
.ButtonWidget
.prototype.onMouseUp = function ( e
) {
12590 if ( !this.isDisabled() ) {
12591 // Restore the tab-index after the button is up to restore the button's accessibility
12592 this.$button
.attr( 'tabindex', this.tabIndex
);
12595 return OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp
.call( this, e
);
12599 * Get hyperlink location.
12601 * @return {string} Hyperlink location
12603 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
12608 * Get hyperlink target.
12610 * @return {string} Hyperlink target
12612 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
12613 return this.target
;
12617 * Get search engine traversal hint.
12619 * @return {boolean} Whether search engines should avoid traversing this hyperlink
12621 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
12622 return this.noFollow
;
12626 * Set hyperlink location.
12628 * @param {string|null} href Hyperlink location, null to remove
12630 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
12631 href
= typeof href
=== 'string' ? href
: null;
12632 if ( href
!== null ) {
12633 if ( !OO
.ui
.isSafeUrl( href
) ) {
12634 throw new Error( 'Potentially unsafe href provided: ' + href
);
12639 if ( href
!== this.href
) {
12648 * Update the `href` attribute, in case of changes to href or
12654 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
12655 if ( this.href
!== null && !this.isDisabled() ) {
12656 this.$button
.attr( 'href', this.href
);
12658 this.$button
.removeAttr( 'href' );
12665 * Handle disable events.
12668 * @param {boolean} disabled Element is disabled
12670 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
12675 * Set hyperlink target.
12677 * @param {string|null} target Hyperlink target, null to remove
12679 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
12680 target
= typeof target
=== 'string' ? target
: null;
12682 if ( target
!== this.target
) {
12683 this.target
= target
;
12684 if ( target
!== null ) {
12685 this.$button
.attr( 'target', target
);
12687 this.$button
.removeAttr( 'target' );
12695 * Set search engine traversal hint.
12697 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
12699 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
12700 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
12702 if ( noFollow
!== this.noFollow
) {
12703 this.noFollow
= noFollow
;
12705 this.$button
.attr( 'rel', 'nofollow' );
12707 this.$button
.removeAttr( 'rel' );
12715 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
12716 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
12719 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
12720 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12723 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
12726 * @extends OO.ui.ButtonWidget
12727 * @mixins OO.ui.mixin.PendingElement
12730 * @param {Object} [config] Configuration options
12731 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12732 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
12733 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
12734 * for more information about setting modes.
12735 * @cfg {boolean} [framed=false] Render the action button with a frame
12737 OO
.ui
.ActionWidget
= function OoUiActionWidget( config
) {
12738 // Configuration initialization
12739 config
= $.extend( { framed
: false }, config
);
12741 // Parent constructor
12742 OO
.ui
.ActionWidget
.parent
.call( this, config
);
12744 // Mixin constructors
12745 OO
.ui
.mixin
.PendingElement
.call( this, config
);
12748 this.action
= config
.action
|| '';
12749 this.modes
= config
.modes
|| [];
12754 this.$element
.addClass( 'oo-ui-actionWidget' );
12759 OO
.inheritClass( OO
.ui
.ActionWidget
, OO
.ui
.ButtonWidget
);
12760 OO
.mixinClass( OO
.ui
.ActionWidget
, OO
.ui
.mixin
.PendingElement
);
12765 * A resize event is emitted when the size of the widget changes.
12773 * Check if the action is configured to be available in the specified `mode`.
12775 * @param {string} mode Name of mode
12776 * @return {boolean} The action is configured with the mode
12778 OO
.ui
.ActionWidget
.prototype.hasMode = function ( mode
) {
12779 return this.modes
.indexOf( mode
) !== -1;
12783 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12787 OO
.ui
.ActionWidget
.prototype.getAction = function () {
12788 return this.action
;
12792 * Get the symbolic name of the mode or modes for which the action is configured to be available.
12794 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
12795 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
12798 * @return {string[]}
12800 OO
.ui
.ActionWidget
.prototype.getModes = function () {
12801 return this.modes
.slice();
12805 * Emit a resize event if the size has changed.
12810 OO
.ui
.ActionWidget
.prototype.propagateResize = function () {
12813 if ( this.isElementAttached() ) {
12814 width
= this.$element
.width();
12815 height
= this.$element
.height();
12817 if ( width
!== this.width
|| height
!== this.height
) {
12818 this.width
= width
;
12819 this.height
= height
;
12820 this.emit( 'resize' );
12830 OO
.ui
.ActionWidget
.prototype.setIcon = function () {
12832 OO
.ui
.mixin
.IconElement
.prototype.setIcon
.apply( this, arguments
);
12833 this.propagateResize();
12841 OO
.ui
.ActionWidget
.prototype.setLabel = function () {
12843 OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.apply( this, arguments
);
12844 this.propagateResize();
12852 OO
.ui
.ActionWidget
.prototype.setFlags = function () {
12854 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags
.apply( this, arguments
);
12855 this.propagateResize();
12863 OO
.ui
.ActionWidget
.prototype.clearFlags = function () {
12865 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags
.apply( this, arguments
);
12866 this.propagateResize();
12872 * Toggle the visibility of the action button.
12874 * @param {boolean} [show] Show button, omit to toggle visibility
12877 OO
.ui
.ActionWidget
.prototype.toggle = function () {
12879 OO
.ui
.ActionWidget
.parent
.prototype.toggle
.apply( this, arguments
);
12880 this.propagateResize();
12886 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
12887 * which is used to display additional information or options.
12890 * // Example of a popup button.
12891 * var popupButton = new OO.ui.PopupButtonWidget( {
12892 * label: 'Popup button with options',
12895 * $content: $( '<p>Additional options here.</p>' ),
12897 * align: 'force-left'
12900 * // Append the button to the DOM.
12901 * $( 'body' ).append( popupButton.$element );
12904 * @extends OO.ui.ButtonWidget
12905 * @mixins OO.ui.mixin.PopupElement
12908 * @param {Object} [config] Configuration options
12910 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
12911 // Parent constructor
12912 OO
.ui
.PopupButtonWidget
.parent
.call( this, config
);
12914 // Mixin constructors
12915 OO
.ui
.mixin
.PopupElement
.call( this, config
);
12918 this.connect( this, { click
: 'onAction' } );
12922 .addClass( 'oo-ui-popupButtonWidget' )
12923 .attr( 'aria-haspopup', 'true' )
12924 .append( this.popup
.$element
);
12929 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
12930 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.mixin
.PopupElement
);
12935 * Handle the button action being triggered.
12939 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
12940 this.popup
.toggle();
12944 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
12945 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
12946 * configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators},
12947 * {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags},
12948 * and {@link OO.ui.mixin.LabelElement labels}. Please see
12949 * the [OOjs UI documentation][1] on MediaWiki for more information.
12952 * // Toggle buttons in the 'off' and 'on' state.
12953 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
12954 * label: 'Toggle Button off'
12956 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
12957 * label: 'Toggle Button on',
12960 * // Append the buttons to the DOM.
12961 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
12963 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
12966 * @extends OO.ui.ToggleWidget
12967 * @mixins OO.ui.mixin.ButtonElement
12968 * @mixins OO.ui.mixin.IconElement
12969 * @mixins OO.ui.mixin.IndicatorElement
12970 * @mixins OO.ui.mixin.LabelElement
12971 * @mixins OO.ui.mixin.TitledElement
12972 * @mixins OO.ui.mixin.FlaggedElement
12973 * @mixins OO.ui.mixin.TabIndexedElement
12976 * @param {Object} [config] Configuration options
12977 * @cfg {boolean} [value=false] The toggle button’s initial on/off
12978 * state. By default, the button is in the 'off' state.
12980 OO
.ui
.ToggleButtonWidget
= function OoUiToggleButtonWidget( config
) {
12981 // Configuration initialization
12982 config
= config
|| {};
12984 // Parent constructor
12985 OO
.ui
.ToggleButtonWidget
.parent
.call( this, config
);
12987 // Mixin constructors
12988 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
12989 OO
.ui
.mixin
.IconElement
.call( this, config
);
12990 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
12991 OO
.ui
.mixin
.LabelElement
.call( this, config
);
12992 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
12993 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
12994 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
12997 this.connect( this, { click
: 'onAction' } );
13000 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
13002 .addClass( 'oo-ui-toggleButtonWidget' )
13003 .append( this.$button
);
13008 OO
.inheritClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.ToggleWidget
);
13009 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
13010 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.IconElement
);
13011 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
13012 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.LabelElement
);
13013 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.TitledElement
);
13014 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
13015 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
13020 * Handle the button action being triggered.
13024 OO
.ui
.ToggleButtonWidget
.prototype.onAction = function () {
13025 this.setValue( !this.value
);
13031 OO
.ui
.ToggleButtonWidget
.prototype.setValue = function ( value
) {
13033 if ( value
!== this.value
) {
13034 // Might be called from parent constructor before ButtonElement constructor
13035 if ( this.$button
) {
13036 this.$button
.attr( 'aria-pressed', value
.toString() );
13038 this.setActive( value
);
13042 OO
.ui
.ToggleButtonWidget
.parent
.prototype.setValue
.call( this, value
);
13050 OO
.ui
.ToggleButtonWidget
.prototype.setButtonElement = function ( $button
) {
13051 if ( this.$button
) {
13052 this.$button
.removeAttr( 'aria-pressed' );
13054 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement
.call( this, $button
);
13055 this.$button
.attr( 'aria-pressed', this.value
.toString() );
13059 * CapsuleMultiSelectWidgets are something like a {@link OO.ui.ComboBoxWidget combo box widget}
13060 * that allows for selecting multiple values.
13062 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
13065 * // Example: A CapsuleMultiSelectWidget.
13066 * var capsule = new OO.ui.CapsuleMultiSelectWidget( {
13067 * label: 'CapsuleMultiSelectWidget',
13068 * selected: [ 'Option 1', 'Option 3' ],
13071 * new OO.ui.MenuOptionWidget( {
13072 * data: 'Option 1',
13073 * label: 'Option One'
13075 * new OO.ui.MenuOptionWidget( {
13076 * data: 'Option 2',
13077 * label: 'Option Two'
13079 * new OO.ui.MenuOptionWidget( {
13080 * data: 'Option 3',
13081 * label: 'Option Three'
13083 * new OO.ui.MenuOptionWidget( {
13084 * data: 'Option 4',
13085 * label: 'Option Four'
13087 * new OO.ui.MenuOptionWidget( {
13088 * data: 'Option 5',
13089 * label: 'Option Five'
13094 * $( 'body' ).append( capsule.$element );
13096 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13099 * @extends OO.ui.Widget
13100 * @mixins OO.ui.mixin.TabIndexedElement
13101 * @mixins OO.ui.mixin.GroupElement
13104 * @param {Object} [config] Configuration options
13105 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if not present in the menu.
13106 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
13107 * @cfg {Object} [popup] Configuration options to pass to the {@link OO.ui.PopupWidget popup widget}.
13108 * If specified, this popup will be shown instead of the menu (but the menu
13109 * will still be used for item labels and allowArbitrary=false). The widgets
13110 * in the popup should use this.addItemsFromData() or this.addItems() as necessary.
13111 * @cfg {jQuery} [$overlay] Render the menu or popup into a separate layer.
13112 * This configuration is useful in cases where the expanded menu is larger than
13113 * its containing `<div>`. The specified overlay layer is usually on top of
13114 * the containing `<div>` and has a larger area. By default, the menu uses
13115 * relative positioning.
13117 OO
.ui
.CapsuleMultiSelectWidget
= function OoUiCapsuleMultiSelectWidget( config
) {
13120 // Configuration initialization
13121 config
= config
|| {};
13123 // Parent constructor
13124 OO
.ui
.CapsuleMultiSelectWidget
.parent
.call( this, config
);
13126 // Properties (must be set before mixin constructor calls)
13127 this.$input
= config
.popup
? null : $( '<input>' );
13128 this.$handle
= $( '<div>' );
13130 // Mixin constructors
13131 OO
.ui
.mixin
.GroupElement
.call( this, config
);
13132 if ( config
.popup
) {
13133 config
.popup
= $.extend( {}, config
.popup
, {
13137 OO
.ui
.mixin
.PopupElement
.call( this, config
);
13138 $tabFocus
= $( '<span>' );
13139 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: $tabFocus
} ) );
13143 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
13145 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
13146 OO
.ui
.mixin
.IconElement
.call( this, config
);
13149 this.allowArbitrary
= !!config
.allowArbitrary
;
13150 this.$overlay
= config
.$overlay
|| this.$element
;
13151 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend(
13154 $input
: this.$input
,
13155 $container
: this.$element
,
13156 filterFromInput
: true,
13157 disabled
: this.isDisabled()
13163 if ( this.popup
) {
13165 focus
: this.onFocusForPopup
.bind( this )
13167 this.popup
.$element
.on( 'focusout', this.onPopupFocusOut
.bind( this ) );
13168 if ( this.popup
.$autoCloseIgnore
) {
13169 this.popup
.$autoCloseIgnore
.on( 'focusout', this.onPopupFocusOut
.bind( this ) );
13171 this.popup
.connect( this, {
13172 toggle: function ( visible
) {
13173 $tabFocus
.toggle( !visible
);
13178 focus
: this.onInputFocus
.bind( this ),
13179 blur
: this.onInputBlur
.bind( this ),
13180 'propertychange change click mouseup keydown keyup input cut paste select': this.onInputChange
.bind( this ),
13181 keydown
: this.onKeyDown
.bind( this ),
13182 keypress
: this.onKeyPress
.bind( this )
13185 this.menu
.connect( this, {
13186 choose
: 'onMenuChoose',
13187 add
: 'onMenuItemsChange',
13188 remove
: 'onMenuItemsChange'
13191 click
: this.onClick
.bind( this )
13195 if ( this.$input
) {
13196 this.$input
.prop( 'disabled', this.isDisabled() );
13197 this.$input
.attr( {
13199 'aria-autocomplete': 'list'
13201 this.$input
.width( '1em' );
13203 if ( config
.data
) {
13204 this.setItemsFromData( config
.data
);
13206 this.$group
.addClass( 'oo-ui-capsuleMultiSelectWidget-group' );
13207 this.$handle
.addClass( 'oo-ui-capsuleMultiSelectWidget-handle' )
13208 .append( this.$indicator
, this.$icon
, this.$group
);
13209 this.$element
.addClass( 'oo-ui-capsuleMultiSelectWidget' )
13210 .append( this.$handle
);
13211 if ( this.popup
) {
13212 this.$handle
.append( $tabFocus
);
13213 this.$overlay
.append( this.popup
.$element
);
13215 this.$handle
.append( this.$input
);
13216 this.$overlay
.append( this.menu
.$element
);
13218 this.onMenuItemsChange();
13223 OO
.inheritClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.Widget
);
13224 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.GroupElement
);
13225 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.PopupElement
);
13226 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
13227 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.IndicatorElement
);
13228 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.IconElement
);
13235 * A change event is emitted when the set of selected items changes.
13237 * @param {Mixed[]} datas Data of the now-selected items
13243 * Construct a OO.ui.CapsuleItemWidget (or a subclass thereof) from given label and data.
13246 * @param {Mixed} data Custom data of any type.
13247 * @param {string} label The label text.
13248 * @return {OO.ui.CapsuleItemWidget}
13250 OO
.ui
.CapsuleMultiSelectWidget
.prototype.createItemWidget = function ( data
, label
) {
13251 return new OO
.ui
.CapsuleItemWidget( { data
: data
, label
: label
} );
13255 * Get the data of the items in the capsule
13256 * @return {Mixed[]}
13258 OO
.ui
.CapsuleMultiSelectWidget
.prototype.getItemsData = function () {
13259 return $.map( this.getItems(), function ( e
) { return e
.data
; } );
13263 * Set the items in the capsule by providing data
13265 * @param {Mixed[]} datas
13266 * @return {OO.ui.CapsuleMultiSelectWidget}
13268 OO
.ui
.CapsuleMultiSelectWidget
.prototype.setItemsFromData = function ( datas
) {
13271 items
= this.getItems();
13273 $.each( datas
, function ( i
, data
) {
13275 item
= menu
.getItemFromData( data
);
13278 label
= item
.label
;
13279 } else if ( widget
.allowArbitrary
) {
13280 label
= String( data
);
13286 for ( j
= 0; j
< items
.length
; j
++ ) {
13287 if ( items
[ j
].data
=== data
&& items
[ j
].label
=== label
) {
13289 items
.splice( j
, 1 );
13294 item
= widget
.createItemWidget( data
, label
);
13296 widget
.addItems( [ item
], i
);
13299 if ( items
.length
) {
13300 widget
.removeItems( items
);
13307 * Add items to the capsule by providing their data
13309 * @param {Mixed[]} datas
13310 * @return {OO.ui.CapsuleMultiSelectWidget}
13312 OO
.ui
.CapsuleMultiSelectWidget
.prototype.addItemsFromData = function ( datas
) {
13317 $.each( datas
, function ( i
, data
) {
13320 if ( !widget
.getItemFromData( data
) ) {
13321 item
= menu
.getItemFromData( data
);
13323 items
.push( widget
.createItemWidget( data
, item
.label
) );
13324 } else if ( widget
.allowArbitrary
) {
13325 items
.push( widget
.createItemWidget( data
, String( data
) ) );
13330 if ( items
.length
) {
13331 this.addItems( items
);
13338 * Remove items by data
13340 * @param {Mixed[]} datas
13341 * @return {OO.ui.CapsuleMultiSelectWidget}
13343 OO
.ui
.CapsuleMultiSelectWidget
.prototype.removeItemsFromData = function ( datas
) {
13347 $.each( datas
, function ( i
, data
) {
13348 var item
= widget
.getItemFromData( data
);
13350 items
.push( item
);
13354 if ( items
.length
) {
13355 this.removeItems( items
);
13364 OO
.ui
.CapsuleMultiSelectWidget
.prototype.addItems = function ( items
) {
13366 oldItems
= this.items
.slice();
13368 OO
.ui
.mixin
.GroupElement
.prototype.addItems
.call( this, items
);
13370 if ( this.items
.length
!== oldItems
.length
) {
13374 for ( i
= 0, l
= oldItems
.length
; same
&& i
< l
; i
++ ) {
13375 same
= same
&& this.items
[ i
] === oldItems
[ i
];
13379 this.emit( 'change', this.getItemsData() );
13388 OO
.ui
.CapsuleMultiSelectWidget
.prototype.removeItems = function ( items
) {
13390 oldItems
= this.items
.slice();
13392 OO
.ui
.mixin
.GroupElement
.prototype.removeItems
.call( this, items
);
13394 if ( this.items
.length
!== oldItems
.length
) {
13398 for ( i
= 0, l
= oldItems
.length
; same
&& i
< l
; i
++ ) {
13399 same
= same
&& this.items
[ i
] === oldItems
[ i
];
13403 this.emit( 'change', this.getItemsData() );
13412 OO
.ui
.CapsuleMultiSelectWidget
.prototype.clearItems = function () {
13413 if ( this.items
.length
) {
13414 OO
.ui
.mixin
.GroupElement
.prototype.clearItems
.call( this );
13415 this.emit( 'change', this.getItemsData() );
13421 * Get the capsule widget's menu.
13422 * @return {OO.ui.MenuSelectWidget} Menu widget
13424 OO
.ui
.CapsuleMultiSelectWidget
.prototype.getMenu = function () {
13429 * Handle focus events
13432 * @param {jQuery.Event} event
13434 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onInputFocus = function () {
13435 if ( !this.isDisabled() ) {
13436 this.menu
.toggle( true );
13441 * Handle blur events
13444 * @param {jQuery.Event} event
13446 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onInputBlur = function () {
13451 * Handle focus events
13454 * @param {jQuery.Event} event
13456 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onFocusForPopup = function () {
13457 if ( !this.isDisabled() ) {
13458 this.popup
.setSize( this.$handle
.width() );
13459 this.popup
.toggle( true );
13460 this.popup
.$element
.find( '*' )
13461 .filter( function () { return OO
.ui
.isFocusableElement( $( this ), true ); } )
13468 * Handles popup focus out events.
13471 * @param {Event} e Focus out event
13473 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onPopupFocusOut = function () {
13474 var widget
= this.popup
;
13476 setTimeout( function () {
13478 widget
.isVisible() &&
13479 !OO
.ui
.contains( widget
.$element
[ 0 ], document
.activeElement
, true ) &&
13480 ( !widget
.$autoCloseIgnore
|| !widget
.$autoCloseIgnore
.has( document
.activeElement
).length
)
13482 widget
.toggle( false );
13488 * Handle mouse click events.
13491 * @param {jQuery.Event} e Mouse click event
13493 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onClick = function ( e
) {
13494 if ( e
.which
=== 1 ) {
13501 * Handle key press events.
13504 * @param {jQuery.Event} e Key press event
13506 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onKeyPress = function ( e
) {
13509 if ( !this.isDisabled() ) {
13510 if ( e
.which
=== OO
.ui
.Keys
.ESCAPE
) {
13515 if ( !this.popup
) {
13516 this.menu
.toggle( true );
13517 if ( e
.which
=== OO
.ui
.Keys
.ENTER
) {
13518 item
= this.menu
.getItemFromLabel( this.$input
.val(), true );
13520 this.addItemsFromData( [ item
.data
] );
13522 } else if ( this.allowArbitrary
&& this.$input
.val().trim() !== '' ) {
13523 this.addItemsFromData( [ this.$input
.val() ] );
13529 // Make sure the input gets resized.
13530 setTimeout( this.onInputChange
.bind( this ), 0 );
13536 * Handle key down events.
13539 * @param {jQuery.Event} e Key down event
13541 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onKeyDown = function ( e
) {
13542 if ( !this.isDisabled() ) {
13543 // 'keypress' event is not triggered for Backspace
13544 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.$input
.val() === '' ) {
13545 if ( this.items
.length
) {
13546 this.removeItems( this.items
.slice( -1 ) );
13554 * Handle input change events.
13557 * @param {jQuery.Event} e Event of some sort
13559 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onInputChange = function () {
13560 if ( !this.isDisabled() ) {
13561 this.$input
.width( this.$input
.val().length
+ 'em' );
13566 * Handle menu choose events.
13569 * @param {OO.ui.OptionWidget} item Chosen item
13571 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onMenuChoose = function ( item
) {
13572 if ( item
&& item
.isVisible() ) {
13573 this.addItemsFromData( [ item
.getData() ] );
13579 * Handle menu item change events.
13583 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onMenuItemsChange = function () {
13584 this.setItemsFromData( this.getItemsData() );
13585 this.$element
.toggleClass( 'oo-ui-capsuleMultiSelectWidget-empty', this.menu
.isEmpty() );
13589 * Clear the input field
13592 OO
.ui
.CapsuleMultiSelectWidget
.prototype.clearInput = function () {
13593 if ( this.$input
) {
13594 this.$input
.val( '' );
13595 this.$input
.width( '1em' );
13597 if ( this.popup
) {
13598 this.popup
.toggle( false );
13600 this.menu
.toggle( false );
13601 this.menu
.selectItem();
13602 this.menu
.highlightItem();
13608 OO
.ui
.CapsuleMultiSelectWidget
.prototype.setDisabled = function ( disabled
) {
13612 OO
.ui
.CapsuleMultiSelectWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
13614 if ( this.$input
) {
13615 this.$input
.prop( 'disabled', this.isDisabled() );
13618 this.menu
.setDisabled( this.isDisabled() );
13620 if ( this.popup
) {
13621 this.popup
.setDisabled( this.isDisabled() );
13624 if ( this.items
) {
13625 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
13626 this.items
[ i
].updateDisabled();
13636 * @return {OO.ui.CapsuleMultiSelectWidget}
13638 OO
.ui
.CapsuleMultiSelectWidget
.prototype.focus = function () {
13639 if ( !this.isDisabled() ) {
13640 if ( this.popup
) {
13641 this.popup
.setSize( this.$handle
.width() );
13642 this.popup
.toggle( true );
13643 this.popup
.$element
.find( '*' )
13644 .filter( function () { return OO
.ui
.isFocusableElement( $( this ), true ); } )
13648 this.menu
.toggle( true );
13649 this.$input
.focus();
13656 * CapsuleItemWidgets are used within a {@link OO.ui.CapsuleMultiSelectWidget
13657 * CapsuleMultiSelectWidget} to display the selected items.
13660 * @extends OO.ui.Widget
13661 * @mixins OO.ui.mixin.ItemWidget
13662 * @mixins OO.ui.mixin.IndicatorElement
13663 * @mixins OO.ui.mixin.LabelElement
13664 * @mixins OO.ui.mixin.FlaggedElement
13665 * @mixins OO.ui.mixin.TabIndexedElement
13668 * @param {Object} [config] Configuration options
13670 OO
.ui
.CapsuleItemWidget
= function OoUiCapsuleItemWidget( config
) {
13671 // Configuration initialization
13672 config
= config
|| {};
13674 // Parent constructor
13675 OO
.ui
.CapsuleItemWidget
.parent
.call( this, config
);
13677 // Properties (must be set before mixin constructor calls)
13678 this.$indicator
= $( '<span>' );
13680 // Mixin constructors
13681 OO
.ui
.mixin
.ItemWidget
.call( this );
13682 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$indicator
, indicator
: 'clear' } ) );
13683 OO
.ui
.mixin
.LabelElement
.call( this, config
);
13684 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
13685 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$indicator
} ) );
13688 this.$indicator
.on( {
13689 keydown
: this.onCloseKeyDown
.bind( this ),
13690 click
: this.onCloseClick
.bind( this )
13695 .addClass( 'oo-ui-capsuleItemWidget' )
13696 .append( this.$indicator
, this.$label
);
13701 OO
.inheritClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.Widget
);
13702 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.ItemWidget
);
13703 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.IndicatorElement
);
13704 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.LabelElement
);
13705 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.FlaggedElement
);
13706 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.TabIndexedElement
);
13711 * Handle close icon clicks
13712 * @param {jQuery.Event} event
13714 OO
.ui
.CapsuleItemWidget
.prototype.onCloseClick = function () {
13715 var element
= this.getElementGroup();
13717 if ( !this.isDisabled() && element
&& $.isFunction( element
.removeItems
) ) {
13718 element
.removeItems( [ this ] );
13724 * Handle close keyboard events
13725 * @param {jQuery.Event} event Key down event
13727 OO
.ui
.CapsuleItemWidget
.prototype.onCloseKeyDown = function ( e
) {
13728 if ( !this.isDisabled() && $.isFunction( this.getElementGroup().removeItems
) ) {
13729 switch ( e
.which
) {
13730 case OO
.ui
.Keys
.ENTER
:
13731 case OO
.ui
.Keys
.BACKSPACE
:
13732 case OO
.ui
.Keys
.SPACE
:
13733 this.getElementGroup().removeItems( [ this ] );
13740 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
13741 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
13742 * users can interact with it.
13744 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
13745 * OO.ui.DropdownInputWidget instead.
13748 * // Example: A DropdownWidget with a menu that contains three options
13749 * var dropDown = new OO.ui.DropdownWidget( {
13750 * label: 'Dropdown menu: Select a menu option',
13753 * new OO.ui.MenuOptionWidget( {
13757 * new OO.ui.MenuOptionWidget( {
13761 * new OO.ui.MenuOptionWidget( {
13769 * $( 'body' ).append( dropDown.$element );
13771 * dropDown.getMenu().selectItemByData( 'b' );
13773 * dropDown.getMenu().getSelectedItem().getData(); // returns 'b'
13775 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
13777 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13780 * @extends OO.ui.Widget
13781 * @mixins OO.ui.mixin.IconElement
13782 * @mixins OO.ui.mixin.IndicatorElement
13783 * @mixins OO.ui.mixin.LabelElement
13784 * @mixins OO.ui.mixin.TitledElement
13785 * @mixins OO.ui.mixin.TabIndexedElement
13788 * @param {Object} [config] Configuration options
13789 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
13790 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
13791 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
13792 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
13794 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
13795 // Configuration initialization
13796 config
= $.extend( { indicator
: 'down' }, config
);
13798 // Parent constructor
13799 OO
.ui
.DropdownWidget
.parent
.call( this, config
);
13801 // Properties (must be set before TabIndexedElement constructor call)
13802 this.$handle
= this.$( '<span>' );
13803 this.$overlay
= config
.$overlay
|| this.$element
;
13805 // Mixin constructors
13806 OO
.ui
.mixin
.IconElement
.call( this, config
);
13807 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
13808 OO
.ui
.mixin
.LabelElement
.call( this, config
);
13809 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
13810 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
13813 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend( {
13815 $container
: this.$element
13816 }, config
.menu
) );
13820 click
: this.onClick
.bind( this ),
13821 keypress
: this.onKeyPress
.bind( this )
13823 this.menu
.connect( this, { select
: 'onMenuSelect' } );
13827 .addClass( 'oo-ui-dropdownWidget-handle' )
13828 .append( this.$icon
, this.$label
, this.$indicator
);
13830 .addClass( 'oo-ui-dropdownWidget' )
13831 .append( this.$handle
);
13832 this.$overlay
.append( this.menu
.$element
);
13837 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
13838 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IconElement
);
13839 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IndicatorElement
);
13840 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.LabelElement
);
13841 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TitledElement
);
13842 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TabIndexedElement
);
13849 * @return {OO.ui.MenuSelectWidget} Menu of widget
13851 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
13856 * Handles menu select events.
13859 * @param {OO.ui.MenuOptionWidget} item Selected menu item
13861 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
13865 this.setLabel( null );
13869 selectedLabel
= item
.getLabel();
13871 // If the label is a DOM element, clone it, because setLabel will append() it
13872 if ( selectedLabel
instanceof jQuery
) {
13873 selectedLabel
= selectedLabel
.clone();
13876 this.setLabel( selectedLabel
);
13880 * Handle mouse click events.
13883 * @param {jQuery.Event} e Mouse click event
13885 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
13886 if ( !this.isDisabled() && e
.which
=== 1 ) {
13887 this.menu
.toggle();
13893 * Handle key press events.
13896 * @param {jQuery.Event} e Key press event
13898 OO
.ui
.DropdownWidget
.prototype.onKeyPress = function ( e
) {
13899 if ( !this.isDisabled() &&
13900 ( ( e
.which
=== OO
.ui
.Keys
.SPACE
&& !this.menu
.isVisible() ) || e
.which
=== OO
.ui
.Keys
.ENTER
)
13902 this.menu
.toggle();
13908 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
13909 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
13910 * OO.ui.mixin.IndicatorElement indicators}.
13911 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
13914 * // Example of a file select widget
13915 * var selectFile = new OO.ui.SelectFileWidget();
13916 * $( 'body' ).append( selectFile.$element );
13918 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets
13921 * @extends OO.ui.Widget
13922 * @mixins OO.ui.mixin.IconElement
13923 * @mixins OO.ui.mixin.IndicatorElement
13924 * @mixins OO.ui.mixin.PendingElement
13925 * @mixins OO.ui.mixin.LabelElement
13928 * @param {Object} [config] Configuration options
13929 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
13930 * @cfg {string} [placeholder] Text to display when no file is selected.
13931 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
13932 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
13933 * @cfg {boolean} [showDropTarget=false] Whether to show a drop target. Requires droppable to be true.
13934 * @cfg {boolean} [dragDropUI=false] Deprecated alias for showDropTarget
13936 OO
.ui
.SelectFileWidget
= function OoUiSelectFileWidget( config
) {
13939 // TODO: Remove in next release
13940 if ( config
&& config
.dragDropUI
) {
13941 config
.showDropTarget
= true;
13944 // Configuration initialization
13945 config
= $.extend( {
13947 placeholder
: OO
.ui
.msg( 'ooui-selectfile-placeholder' ),
13948 notsupported
: OO
.ui
.msg( 'ooui-selectfile-not-supported' ),
13950 showDropTarget
: false
13953 // Parent constructor
13954 OO
.ui
.SelectFileWidget
.parent
.call( this, config
);
13956 // Mixin constructors
13957 OO
.ui
.mixin
.IconElement
.call( this, config
);
13958 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
13959 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$info
} ) );
13960 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { autoFitLabel
: true } ) );
13963 this.$info
= $( '<span>' );
13966 this.showDropTarget
= config
.showDropTarget
;
13967 this.isSupported
= this.constructor.static.isSupported();
13968 this.currentFile
= null;
13969 if ( Array
.isArray( config
.accept
) ) {
13970 this.accept
= config
.accept
;
13972 this.accept
= null;
13974 this.placeholder
= config
.placeholder
;
13975 this.notsupported
= config
.notsupported
;
13976 this.onFileSelectedHandler
= this.onFileSelected
.bind( this );
13978 this.selectButton
= new OO
.ui
.ButtonWidget( {
13979 classes
: [ 'oo-ui-selectFileWidget-selectButton' ],
13980 label
: 'Select a file',
13981 disabled
: this.disabled
|| !this.isSupported
13984 this.clearButton
= new OO
.ui
.ButtonWidget( {
13985 classes
: [ 'oo-ui-selectFileWidget-clearButton' ],
13988 disabled
: this.disabled
13992 this.selectButton
.$button
.on( {
13993 keypress
: this.onKeyPress
.bind( this )
13995 this.clearButton
.connect( this, {
13996 click
: 'onClearClick'
13998 if ( config
.droppable
) {
13999 dragHandler
= this.onDragEnterOrOver
.bind( this );
14000 this.$element
.on( {
14001 dragenter
: dragHandler
,
14002 dragover
: dragHandler
,
14003 dragleave
: this.onDragLeave
.bind( this ),
14004 drop
: this.onDrop
.bind( this )
14011 this.$label
.addClass( 'oo-ui-selectFileWidget-label' );
14013 .addClass( 'oo-ui-selectFileWidget-info' )
14014 .append( this.$icon
, this.$label
, this.clearButton
.$element
, this.$indicator
);
14016 .addClass( 'oo-ui-selectFileWidget' )
14017 .append( this.$info
, this.selectButton
.$element
);
14018 if ( config
.droppable
&& config
.showDropTarget
) {
14019 this.$dropTarget
= $( '<div>' )
14020 .addClass( 'oo-ui-selectFileWidget-dropTarget' )
14021 .text( OO
.ui
.msg( 'ooui-selectfile-dragdrop-placeholder' ) )
14023 click
: this.onDropTargetClick
.bind( this )
14025 this.$element
.prepend( this.$dropTarget
);
14031 OO
.inheritClass( OO
.ui
.SelectFileWidget
, OO
.ui
.Widget
);
14032 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.IconElement
);
14033 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.IndicatorElement
);
14034 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.PendingElement
);
14035 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.LabelElement
);
14037 /* Static Properties */
14040 * Check if this widget is supported
14043 * @return {boolean}
14045 OO
.ui
.SelectFileWidget
.static.isSupported = function () {
14047 if ( OO
.ui
.SelectFileWidget
.static.isSupportedCache
=== null ) {
14048 $input
= $( '<input type="file">' );
14049 OO
.ui
.SelectFileWidget
.static.isSupportedCache
= $input
[ 0 ].files
!== undefined;
14051 return OO
.ui
.SelectFileWidget
.static.isSupportedCache
;
14054 OO
.ui
.SelectFileWidget
.static.isSupportedCache
= null;
14061 * A change event is emitted when the on/off state of the toggle changes.
14063 * @param {File|null} value New value
14069 * Get the current value of the field
14071 * @return {File|null}
14073 OO
.ui
.SelectFileWidget
.prototype.getValue = function () {
14074 return this.currentFile
;
14078 * Set the current value of the field
14080 * @param {File|null} file File to select
14082 OO
.ui
.SelectFileWidget
.prototype.setValue = function ( file
) {
14083 if ( this.currentFile
!== file
) {
14084 this.currentFile
= file
;
14086 this.emit( 'change', this.currentFile
);
14091 * Update the user interface when a file is selected or unselected
14095 OO
.ui
.SelectFileWidget
.prototype.updateUI = function () {
14097 if ( !this.isSupported
) {
14098 this.$element
.addClass( 'oo-ui-selectFileWidget-notsupported' );
14099 this.$element
.removeClass( 'oo-ui-selectFileWidget-empty' );
14100 this.setLabel( this.notsupported
);
14102 this.$element
.addClass( 'oo-ui-selectFileWidget-supported' );
14103 if ( this.currentFile
) {
14104 this.$element
.removeClass( 'oo-ui-selectFileWidget-empty' );
14106 if ( this.currentFile
.type
!== '' ) {
14107 $label
= $label
.add( $( '<span>' ).addClass( 'oo-ui-selectFileWidget-fileType' ).text( this.currentFile
.type
) );
14109 $label
= $label
.add( $( '<span>' ).text( this.currentFile
.name
) );
14110 this.setLabel( $label
);
14112 this.$element
.addClass( 'oo-ui-selectFileWidget-empty' );
14113 this.setLabel( this.placeholder
);
14117 if ( this.$input
) {
14118 this.$input
.attr( 'title', this.getLabel() );
14123 * Add the input to the widget
14127 OO
.ui
.SelectFileWidget
.prototype.addInput = function () {
14128 if ( this.$input
) {
14129 this.$input
.remove();
14132 if ( !this.isSupported
) {
14133 this.$input
= null;
14137 this.$input
= $( '<input type="file">' );
14138 this.$input
.on( 'change', this.onFileSelectedHandler
);
14139 this.$input
.attr( {
14141 title
: this.getLabel()
14143 if ( this.accept
) {
14144 this.$input
.attr( 'accept', this.accept
.join( ', ' ) );
14146 this.selectButton
.$button
.append( this.$input
);
14150 * Determine if we should accept this file
14153 * @param {string} File MIME type
14154 * @return {boolean}
14156 OO
.ui
.SelectFileWidget
.prototype.isAllowedType = function ( mimeType
) {
14159 if ( !this.accept
|| !mimeType
) {
14163 for ( i
= 0; i
< this.accept
.length
; i
++ ) {
14164 mimeTest
= this.accept
[ i
];
14165 if ( mimeTest
=== mimeType
) {
14167 } else if ( mimeTest
.substr( -2 ) === '/*' ) {
14168 mimeTest
= mimeTest
.substr( 0, mimeTest
.length
- 1 );
14169 if ( mimeType
.substr( 0, mimeTest
.length
) === mimeTest
) {
14179 * Handle file selection from the input
14182 * @param {jQuery.Event} e
14184 OO
.ui
.SelectFileWidget
.prototype.onFileSelected = function ( e
) {
14185 var file
= OO
.getProp( e
.target
, 'files', 0 ) || null;
14187 if ( file
&& !this.isAllowedType( file
.type
) ) {
14191 this.setValue( file
);
14196 * Handle clear button click events.
14200 OO
.ui
.SelectFileWidget
.prototype.onClearClick = function () {
14201 this.setValue( null );
14206 * Handle key press events.
14209 * @param {jQuery.Event} e Key press event
14211 OO
.ui
.SelectFileWidget
.prototype.onKeyPress = function ( e
) {
14212 if ( this.isSupported
&& !this.isDisabled() && this.$input
&&
14213 ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
14215 this.$input
.click();
14221 * Handle drop target click events.
14224 * @param {jQuery.Event} e Key press event
14226 OO
.ui
.SelectFileWidget
.prototype.onDropTargetClick = function () {
14227 if ( this.isSupported
&& !this.isDisabled() && this.$input
) {
14228 this.$input
.click();
14234 * Handle drag enter and over events
14237 * @param {jQuery.Event} e Drag event
14239 OO
.ui
.SelectFileWidget
.prototype.onDragEnterOrOver = function ( e
) {
14241 droppableFile
= false,
14242 dt
= e
.originalEvent
.dataTransfer
;
14244 e
.preventDefault();
14245 e
.stopPropagation();
14247 if ( this.isDisabled() || !this.isSupported
) {
14248 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14249 dt
.dropEffect
= 'none';
14253 // DataTransferItem and File both have a type property, but in Chrome files
14254 // have no information at this point.
14255 itemOrFile
= OO
.getProp( dt
, 'items', 0 ) || OO
.getProp( dt
, 'files', 0 );
14256 if ( itemOrFile
) {
14257 if ( this.isAllowedType( itemOrFile
.type
) ) {
14258 droppableFile
= true;
14260 // dt.types is Array-like, but not an Array
14261 } else if ( Array
.prototype.indexOf
.call( OO
.getProp( dt
, 'types' ) || [], 'Files' ) !== -1 ) {
14262 // File information is not available at this point for security so just assume
14263 // it is acceptable for now.
14264 // https://bugzilla.mozilla.org/show_bug.cgi?id=640534
14265 droppableFile
= true;
14268 this.$element
.toggleClass( 'oo-ui-selectFileWidget-canDrop', droppableFile
);
14269 if ( !droppableFile
) {
14270 dt
.dropEffect
= 'none';
14277 * Handle drag leave events
14280 * @param {jQuery.Event} e Drag event
14282 OO
.ui
.SelectFileWidget
.prototype.onDragLeave = function () {
14283 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14287 * Handle drop events
14290 * @param {jQuery.Event} e Drop event
14292 OO
.ui
.SelectFileWidget
.prototype.onDrop = function ( e
) {
14294 dt
= e
.originalEvent
.dataTransfer
;
14296 e
.preventDefault();
14297 e
.stopPropagation();
14298 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14300 if ( this.isDisabled() || !this.isSupported
) {
14304 file
= OO
.getProp( dt
, 'files', 0 );
14305 if ( file
&& !this.isAllowedType( file
.type
) ) {
14309 this.setValue( file
);
14318 OO
.ui
.SelectFileWidget
.prototype.setDisabled = function ( disabled
) {
14319 OO
.ui
.SelectFileWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
14320 if ( this.selectButton
) {
14321 this.selectButton
.setDisabled( disabled
);
14323 if ( this.clearButton
) {
14324 this.clearButton
.setDisabled( disabled
);
14330 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
14331 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
14332 * for a list of icons included in the library.
14335 * // An icon widget with a label
14336 * var myIcon = new OO.ui.IconWidget( {
14338 * iconTitle: 'Help'
14340 * // Create a label.
14341 * var iconLabel = new OO.ui.LabelWidget( {
14344 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
14346 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
14349 * @extends OO.ui.Widget
14350 * @mixins OO.ui.mixin.IconElement
14351 * @mixins OO.ui.mixin.TitledElement
14352 * @mixins OO.ui.mixin.FlaggedElement
14355 * @param {Object} [config] Configuration options
14357 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
14358 // Configuration initialization
14359 config
= config
|| {};
14361 // Parent constructor
14362 OO
.ui
.IconWidget
.parent
.call( this, config
);
14364 // Mixin constructors
14365 OO
.ui
.mixin
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
14366 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
14367 OO
.ui
.mixin
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
14370 this.$element
.addClass( 'oo-ui-iconWidget' );
14375 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
14376 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.IconElement
);
14377 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.TitledElement
);
14378 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.FlaggedElement
);
14380 /* Static Properties */
14382 OO
.ui
.IconWidget
.static.tagName
= 'span';
14385 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
14386 * attention to the status of an item or to clarify the function of a control. For a list of
14387 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
14390 * // Example of an indicator widget
14391 * var indicator1 = new OO.ui.IndicatorWidget( {
14392 * indicator: 'alert'
14395 * // Create a fieldset layout to add a label
14396 * var fieldset = new OO.ui.FieldsetLayout();
14397 * fieldset.addItems( [
14398 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
14400 * $( 'body' ).append( fieldset.$element );
14402 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
14405 * @extends OO.ui.Widget
14406 * @mixins OO.ui.mixin.IndicatorElement
14407 * @mixins OO.ui.mixin.TitledElement
14410 * @param {Object} [config] Configuration options
14412 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
14413 // Configuration initialization
14414 config
= config
|| {};
14416 // Parent constructor
14417 OO
.ui
.IndicatorWidget
.parent
.call( this, config
);
14419 // Mixin constructors
14420 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
14421 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
14424 this.$element
.addClass( 'oo-ui-indicatorWidget' );
14429 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
14430 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.IndicatorElement
);
14431 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.TitledElement
);
14433 /* Static Properties */
14435 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
14438 * InputWidget is the base class for all input widgets, which
14439 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
14440 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
14441 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14443 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14447 * @extends OO.ui.Widget
14448 * @mixins OO.ui.mixin.FlaggedElement
14449 * @mixins OO.ui.mixin.TabIndexedElement
14450 * @mixins OO.ui.mixin.TitledElement
14451 * @mixins OO.ui.mixin.AccessKeyedElement
14454 * @param {Object} [config] Configuration options
14455 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
14456 * @cfg {string} [value=''] The value of the input.
14457 * @cfg {string} [accessKey=''] The access key of the input.
14458 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
14459 * before it is accepted.
14461 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
14462 // Configuration initialization
14463 config
= config
|| {};
14465 // Parent constructor
14466 OO
.ui
.InputWidget
.parent
.call( this, config
);
14469 this.$input
= this.getInputElement( config
);
14471 this.inputFilter
= config
.inputFilter
;
14473 // Mixin constructors
14474 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
14475 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
14476 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
14477 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$input
} ) );
14480 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
14484 .addClass( 'oo-ui-inputWidget-input' )
14485 .attr( 'name', config
.name
)
14486 .prop( 'disabled', this.isDisabled() );
14488 .addClass( 'oo-ui-inputWidget' )
14489 .append( this.$input
);
14490 this.setValue( config
.value
);
14491 this.setAccessKey( config
.accessKey
);
14496 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
14497 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.FlaggedElement
);
14498 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TabIndexedElement
);
14499 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TitledElement
);
14500 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
14502 /* Static Properties */
14504 OO
.ui
.InputWidget
.static.supportsSimpleLabel
= true;
14511 * A change event is emitted when the value of the input changes.
14513 * @param {string} value
14519 * Get input element.
14521 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
14522 * different circumstances. The element must have a `value` property (like form elements).
14525 * @param {Object} config Configuration options
14526 * @return {jQuery} Input element
14528 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
14529 return $( '<input>' );
14533 * Handle potentially value-changing events.
14536 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
14538 OO
.ui
.InputWidget
.prototype.onEdit = function () {
14540 if ( !this.isDisabled() ) {
14541 // Allow the stack to clear so the value will be updated
14542 setTimeout( function () {
14543 widget
.setValue( widget
.$input
.val() );
14549 * Get the value of the input.
14551 * @return {string} Input value
14553 OO
.ui
.InputWidget
.prototype.getValue = function () {
14554 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14555 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14556 var value
= this.$input
.val();
14557 if ( this.value
!== value
) {
14558 this.setValue( value
);
14564 * Set the direction of the input, either RTL (right-to-left) or LTR (left-to-right).
14566 * @param {boolean} isRTL
14567 * Direction is right-to-left
14569 OO
.ui
.InputWidget
.prototype.setRTL = function ( isRTL
) {
14570 this.$input
.prop( 'dir', isRTL
? 'rtl' : 'ltr' );
14574 * Set the value of the input.
14576 * @param {string} value New value
14580 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
14581 value
= this.cleanUpValue( value
);
14582 // Update the DOM if it has changed. Note that with cleanUpValue, it
14583 // is possible for the DOM value to change without this.value changing.
14584 if ( this.$input
.val() !== value
) {
14585 this.$input
.val( value
);
14587 if ( this.value
!== value
) {
14588 this.value
= value
;
14589 this.emit( 'change', this.value
);
14595 * Set the input's access key.
14596 * FIXME: This is the same code as in OO.ui.mixin.ButtonElement, maybe find a better place for it?
14598 * @param {string} accessKey Input's access key, use empty string to remove
14601 OO
.ui
.InputWidget
.prototype.setAccessKey = function ( accessKey
) {
14602 accessKey
= typeof accessKey
=== 'string' && accessKey
.length
? accessKey
: null;
14604 if ( this.accessKey
!== accessKey
) {
14605 if ( this.$input
) {
14606 if ( accessKey
!== null ) {
14607 this.$input
.attr( 'accesskey', accessKey
);
14609 this.$input
.removeAttr( 'accesskey' );
14612 this.accessKey
= accessKey
;
14619 * Clean up incoming value.
14621 * Ensures value is a string, and converts undefined and null to empty string.
14624 * @param {string} value Original value
14625 * @return {string} Cleaned up value
14627 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
14628 if ( value
=== undefined || value
=== null ) {
14630 } else if ( this.inputFilter
) {
14631 return this.inputFilter( String( value
) );
14633 return String( value
);
14638 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
14639 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
14642 OO
.ui
.InputWidget
.prototype.simulateLabelClick = function () {
14643 if ( !this.isDisabled() ) {
14644 if ( this.$input
.is( ':checkbox, :radio' ) ) {
14645 this.$input
.click();
14647 if ( this.$input
.is( ':input' ) ) {
14648 this.$input
[ 0 ].focus();
14656 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
14657 OO
.ui
.InputWidget
.parent
.prototype.setDisabled
.call( this, state
);
14658 if ( this.$input
) {
14659 this.$input
.prop( 'disabled', this.isDisabled() );
14669 OO
.ui
.InputWidget
.prototype.focus = function () {
14670 this.$input
[ 0 ].focus();
14679 OO
.ui
.InputWidget
.prototype.blur = function () {
14680 this.$input
[ 0 ].blur();
14687 OO
.ui
.InputWidget
.prototype.gatherPreInfuseState = function ( node
) {
14689 state
= OO
.ui
.InputWidget
.parent
.prototype.gatherPreInfuseState
.call( this, node
),
14690 $input
= state
.$input
|| $( node
).find( '.oo-ui-inputWidget-input' );
14691 state
.value
= $input
.val();
14692 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
14693 state
.focus
= $input
.is( ':focus' );
14700 OO
.ui
.InputWidget
.prototype.restorePreInfuseState = function ( state
) {
14701 OO
.ui
.InputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
14702 if ( state
.value
!== undefined && state
.value
!== this.getValue() ) {
14703 this.setValue( state
.value
);
14705 if ( state
.focus
) {
14711 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
14712 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
14713 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
14714 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
14715 * [OOjs UI documentation on MediaWiki] [1] for more information.
14718 * // A ButtonInputWidget rendered as an HTML button, the default.
14719 * var button = new OO.ui.ButtonInputWidget( {
14720 * label: 'Input button',
14724 * $( 'body' ).append( button.$element );
14726 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
14729 * @extends OO.ui.InputWidget
14730 * @mixins OO.ui.mixin.ButtonElement
14731 * @mixins OO.ui.mixin.IconElement
14732 * @mixins OO.ui.mixin.IndicatorElement
14733 * @mixins OO.ui.mixin.LabelElement
14734 * @mixins OO.ui.mixin.TitledElement
14737 * @param {Object} [config] Configuration options
14738 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
14739 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
14740 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
14741 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
14742 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
14744 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
14745 // Configuration initialization
14746 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
14748 // Properties (must be set before parent constructor, which calls #setValue)
14749 this.useInputTag
= config
.useInputTag
;
14751 // Parent constructor
14752 OO
.ui
.ButtonInputWidget
.parent
.call( this, config
);
14754 // Mixin constructors
14755 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
14756 OO
.ui
.mixin
.IconElement
.call( this, config
);
14757 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
14758 OO
.ui
.mixin
.LabelElement
.call( this, config
);
14759 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
14762 if ( !config
.useInputTag
) {
14763 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
14765 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
14770 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
14771 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.ButtonElement
);
14772 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IconElement
);
14773 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
14774 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.LabelElement
);
14775 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.TitledElement
);
14777 /* Static Properties */
14780 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
14781 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
14783 OO
.ui
.ButtonInputWidget
.static.supportsSimpleLabel
= false;
14791 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
14792 var type
= [ 'button', 'submit', 'reset' ].indexOf( config
.type
) !== -1 ?
14795 return $( '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + type
+ '">' );
14801 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
14803 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
14804 * text, or `null` for no label
14807 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
14808 OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.call( this, label
);
14810 if ( this.useInputTag
) {
14811 if ( typeof label
=== 'function' ) {
14812 label
= OO
.ui
.resolveMsg( label
);
14814 if ( label
instanceof jQuery
) {
14815 label
= label
.text();
14820 this.$input
.val( label
);
14827 * Set the value of the input.
14829 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
14830 * they do not support {@link #value values}.
14832 * @param {string} value New value
14835 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
14836 if ( !this.useInputTag
) {
14837 OO
.ui
.ButtonInputWidget
.parent
.prototype.setValue
.call( this, value
);
14843 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
14844 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
14845 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
14846 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
14848 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
14851 * // An example of selected, unselected, and disabled checkbox inputs
14852 * var checkbox1=new OO.ui.CheckboxInputWidget( {
14856 * var checkbox2=new OO.ui.CheckboxInputWidget( {
14859 * var checkbox3=new OO.ui.CheckboxInputWidget( {
14863 * // Create a fieldset layout with fields for each checkbox.
14864 * var fieldset = new OO.ui.FieldsetLayout( {
14865 * label: 'Checkboxes'
14867 * fieldset.addItems( [
14868 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
14869 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
14870 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
14872 * $( 'body' ).append( fieldset.$element );
14874 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14877 * @extends OO.ui.InputWidget
14880 * @param {Object} [config] Configuration options
14881 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
14883 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
14884 // Configuration initialization
14885 config
= config
|| {};
14887 // Parent constructor
14888 OO
.ui
.CheckboxInputWidget
.parent
.call( this, config
);
14892 .addClass( 'oo-ui-checkboxInputWidget' )
14893 // Required for pretty styling in MediaWiki theme
14894 .append( $( '<span>' ) );
14895 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
14900 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
14908 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
14909 return $( '<input type="checkbox" />' );
14915 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
14917 if ( !this.isDisabled() ) {
14918 // Allow the stack to clear so the value will be updated
14919 setTimeout( function () {
14920 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
14926 * Set selection state of this checkbox.
14928 * @param {boolean} state `true` for selected
14931 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
14933 if ( this.selected
!== state
) {
14934 this.selected
= state
;
14935 this.$input
.prop( 'checked', this.selected
);
14936 this.emit( 'change', this.selected
);
14942 * Check if this checkbox is selected.
14944 * @return {boolean} Checkbox is selected
14946 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
14947 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14948 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14949 var selected
= this.$input
.prop( 'checked' );
14950 if ( this.selected
!== selected
) {
14951 this.setSelected( selected
);
14953 return this.selected
;
14959 OO
.ui
.CheckboxInputWidget
.prototype.gatherPreInfuseState = function ( node
) {
14961 state
= OO
.ui
.CheckboxInputWidget
.parent
.prototype.gatherPreInfuseState
.call( this, node
),
14962 $input
= $( node
).find( '.oo-ui-inputWidget-input' );
14963 state
.$input
= $input
; // shortcut for performance, used in InputWidget
14964 state
.checked
= $input
.prop( 'checked' );
14971 OO
.ui
.CheckboxInputWidget
.prototype.restorePreInfuseState = function ( state
) {
14972 OO
.ui
.CheckboxInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
14973 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
14974 this.setSelected( state
.checked
);
14979 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
14980 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
14981 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
14982 * more information about input widgets.
14984 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
14985 * are no options. If no `value` configuration option is provided, the first option is selected.
14986 * If you need a state representing no value (no option being selected), use a DropdownWidget.
14988 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
14991 * // Example: A DropdownInputWidget with three options
14992 * var dropdownInput = new OO.ui.DropdownInputWidget( {
14994 * { data: 'a', label: 'First' },
14995 * { data: 'b', label: 'Second'},
14996 * { data: 'c', label: 'Third' }
14999 * $( 'body' ).append( dropdownInput.$element );
15001 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15004 * @extends OO.ui.InputWidget
15005 * @mixins OO.ui.mixin.TitledElement
15008 * @param {Object} [config] Configuration options
15009 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15010 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
15012 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
15013 // Configuration initialization
15014 config
= config
|| {};
15016 // Properties (must be done before parent constructor which calls #setDisabled)
15017 this.dropdownWidget
= new OO
.ui
.DropdownWidget( config
.dropdown
);
15019 // Parent constructor
15020 OO
.ui
.DropdownInputWidget
.parent
.call( this, config
);
15022 // Mixin constructors
15023 OO
.ui
.mixin
.TitledElement
.call( this, config
);
15026 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
15029 this.setOptions( config
.options
|| [] );
15031 .addClass( 'oo-ui-dropdownInputWidget' )
15032 .append( this.dropdownWidget
.$element
);
15037 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
15038 OO
.mixinClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.mixin
.TitledElement
);
15046 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
15047 return $( '<input type="hidden">' );
15051 * Handles menu select events.
15054 * @param {OO.ui.MenuOptionWidget} item Selected menu item
15056 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
15057 this.setValue( item
.getData() );
15063 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
15064 value
= this.cleanUpValue( value
);
15065 this.dropdownWidget
.getMenu().selectItemByData( value
);
15066 OO
.ui
.DropdownInputWidget
.parent
.prototype.setValue
.call( this, value
);
15073 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
15074 this.dropdownWidget
.setDisabled( state
);
15075 OO
.ui
.DropdownInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
15080 * Set the options available for this input.
15082 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15085 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
15087 value
= this.getValue(),
15090 // Rebuild the dropdown menu
15091 this.dropdownWidget
.getMenu()
15093 .addItems( options
.map( function ( opt
) {
15094 var optValue
= widget
.cleanUpValue( opt
.data
);
15095 return new OO
.ui
.MenuOptionWidget( {
15097 label
: opt
.label
!== undefined ? opt
.label
: optValue
15101 // Restore the previous value, or reset to something sensible
15102 if ( this.dropdownWidget
.getMenu().getItemFromData( value
) ) {
15103 // Previous value is still available, ensure consistency with the dropdown
15104 this.setValue( value
);
15106 // No longer valid, reset
15107 if ( options
.length
) {
15108 this.setValue( options
[ 0 ].data
);
15118 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
15119 this.dropdownWidget
.getMenu().toggle( true );
15126 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
15127 this.dropdownWidget
.getMenu().toggle( false );
15132 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
15133 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
15134 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
15135 * please see the [OOjs UI documentation on MediaWiki][1].
15137 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15140 * // An example of selected, unselected, and disabled radio inputs
15141 * var radio1 = new OO.ui.RadioInputWidget( {
15145 * var radio2 = new OO.ui.RadioInputWidget( {
15148 * var radio3 = new OO.ui.RadioInputWidget( {
15152 * // Create a fieldset layout with fields for each radio button.
15153 * var fieldset = new OO.ui.FieldsetLayout( {
15154 * label: 'Radio inputs'
15156 * fieldset.addItems( [
15157 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
15158 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
15159 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
15161 * $( 'body' ).append( fieldset.$element );
15163 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15166 * @extends OO.ui.InputWidget
15169 * @param {Object} [config] Configuration options
15170 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
15172 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
15173 // Configuration initialization
15174 config
= config
|| {};
15176 // Parent constructor
15177 OO
.ui
.RadioInputWidget
.parent
.call( this, config
);
15181 .addClass( 'oo-ui-radioInputWidget' )
15182 // Required for pretty styling in MediaWiki theme
15183 .append( $( '<span>' ) );
15184 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
15189 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
15197 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
15198 return $( '<input type="radio" />' );
15204 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
15205 // RadioInputWidget doesn't track its state.
15209 * Set selection state of this radio button.
15211 * @param {boolean} state `true` for selected
15214 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
15215 // RadioInputWidget doesn't track its state.
15216 this.$input
.prop( 'checked', state
);
15221 * Check if this radio button is selected.
15223 * @return {boolean} Radio is selected
15225 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
15226 return this.$input
.prop( 'checked' );
15232 OO
.ui
.RadioInputWidget
.prototype.gatherPreInfuseState = function ( node
) {
15234 state
= OO
.ui
.RadioInputWidget
.parent
.prototype.gatherPreInfuseState
.call( this, node
),
15235 $input
= $( node
).find( '.oo-ui-inputWidget-input' );
15236 state
.$input
= $input
; // shortcut for performance, used in InputWidget
15237 state
.checked
= $input
.prop( 'checked' );
15244 OO
.ui
.RadioInputWidget
.prototype.restorePreInfuseState = function ( state
) {
15245 OO
.ui
.RadioInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
15246 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
15247 this.setSelected( state
.checked
);
15252 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
15253 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
15254 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
15255 * more information about input widgets.
15257 * This and OO.ui.DropdownInputWidget support the same configuration options.
15260 * // Example: A RadioSelectInputWidget with three options
15261 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
15263 * { data: 'a', label: 'First' },
15264 * { data: 'b', label: 'Second'},
15265 * { data: 'c', label: 'Third' }
15268 * $( 'body' ).append( radioSelectInput.$element );
15270 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15273 * @extends OO.ui.InputWidget
15276 * @param {Object} [config] Configuration options
15277 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15279 OO
.ui
.RadioSelectInputWidget
= function OoUiRadioSelectInputWidget( config
) {
15280 // Configuration initialization
15281 config
= config
|| {};
15283 // Properties (must be done before parent constructor which calls #setDisabled)
15284 this.radioSelectWidget
= new OO
.ui
.RadioSelectWidget();
15286 // Parent constructor
15287 OO
.ui
.RadioSelectInputWidget
.parent
.call( this, config
);
15290 this.radioSelectWidget
.connect( this, { select
: 'onMenuSelect' } );
15293 this.setOptions( config
.options
|| [] );
15295 .addClass( 'oo-ui-radioSelectInputWidget' )
15296 .append( this.radioSelectWidget
.$element
);
15301 OO
.inheritClass( OO
.ui
.RadioSelectInputWidget
, OO
.ui
.InputWidget
);
15303 /* Static Properties */
15305 OO
.ui
.RadioSelectInputWidget
.static.supportsSimpleLabel
= false;
15313 OO
.ui
.RadioSelectInputWidget
.prototype.getInputElement = function () {
15314 return $( '<input type="hidden">' );
15318 * Handles menu select events.
15321 * @param {OO.ui.RadioOptionWidget} item Selected menu item
15323 OO
.ui
.RadioSelectInputWidget
.prototype.onMenuSelect = function ( item
) {
15324 this.setValue( item
.getData() );
15330 OO
.ui
.RadioSelectInputWidget
.prototype.setValue = function ( value
) {
15331 value
= this.cleanUpValue( value
);
15332 this.radioSelectWidget
.selectItemByData( value
);
15333 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setValue
.call( this, value
);
15340 OO
.ui
.RadioSelectInputWidget
.prototype.setDisabled = function ( state
) {
15341 this.radioSelectWidget
.setDisabled( state
);
15342 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
15347 * Set the options available for this input.
15349 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15352 OO
.ui
.RadioSelectInputWidget
.prototype.setOptions = function ( options
) {
15354 value
= this.getValue(),
15357 // Rebuild the radioSelect menu
15358 this.radioSelectWidget
15360 .addItems( options
.map( function ( opt
) {
15361 var optValue
= widget
.cleanUpValue( opt
.data
);
15362 return new OO
.ui
.RadioOptionWidget( {
15364 label
: opt
.label
!== undefined ? opt
.label
: optValue
15368 // Restore the previous value, or reset to something sensible
15369 if ( this.radioSelectWidget
.getItemFromData( value
) ) {
15370 // Previous value is still available, ensure consistency with the radioSelect
15371 this.setValue( value
);
15373 // No longer valid, reset
15374 if ( options
.length
) {
15375 this.setValue( options
[ 0 ].data
);
15385 OO
.ui
.RadioSelectInputWidget
.prototype.gatherPreInfuseState = function ( node
) {
15386 var state
= OO
.ui
.RadioSelectInputWidget
.parent
.prototype.gatherPreInfuseState
.call( this, node
);
15387 state
.value
= $( node
).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
15392 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
15393 * size of the field as well as its presentation. In addition, these widgets can be configured
15394 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
15395 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
15396 * which modifies incoming values rather than validating them.
15397 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
15399 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15402 * // Example of a text input widget
15403 * var textInput = new OO.ui.TextInputWidget( {
15404 * value: 'Text input'
15406 * $( 'body' ).append( textInput.$element );
15408 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15411 * @extends OO.ui.InputWidget
15412 * @mixins OO.ui.mixin.IconElement
15413 * @mixins OO.ui.mixin.IndicatorElement
15414 * @mixins OO.ui.mixin.PendingElement
15415 * @mixins OO.ui.mixin.LabelElement
15418 * @param {Object} [config] Configuration options
15419 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
15420 * 'email' or 'url'. Ignored if `multiline` is true.
15422 * Some values of `type` result in additional behaviors:
15424 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
15425 * empties the text field
15426 * @cfg {string} [placeholder] Placeholder text
15427 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
15428 * instruct the browser to focus this widget.
15429 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
15430 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
15431 * @cfg {boolean} [multiline=false] Allow multiple lines of text
15432 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
15433 * specifies minimum number of rows to display.
15434 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
15435 * Use the #maxRows config to specify a maximum number of displayed rows.
15436 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
15437 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
15438 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
15439 * the value or placeholder text: `'before'` or `'after'`
15440 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
15441 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
15442 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
15443 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
15444 * (the value must contain only numbers); when RegExp, a regular expression that must match the
15445 * value for it to be considered valid; when Function, a function receiving the value as parameter
15446 * that must return true, or promise resolving to true, for it to be considered valid.
15448 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
15449 // Configuration initialization
15450 config
= $.extend( {
15452 labelPosition
: 'after'
15454 if ( config
.type
=== 'search' ) {
15455 if ( config
.icon
=== undefined ) {
15456 config
.icon
= 'search';
15458 // indicator: 'clear' is set dynamically later, depending on value
15460 if ( config
.required
) {
15461 if ( config
.indicator
=== undefined ) {
15462 config
.indicator
= 'required';
15466 // Parent constructor
15467 OO
.ui
.TextInputWidget
.parent
.call( this, config
);
15469 // Mixin constructors
15470 OO
.ui
.mixin
.IconElement
.call( this, config
);
15471 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
15472 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$input
} ) );
15473 OO
.ui
.mixin
.LabelElement
.call( this, config
);
15476 this.type
= this.getSaneType( config
);
15477 this.readOnly
= false;
15478 this.multiline
= !!config
.multiline
;
15479 this.autosize
= !!config
.autosize
;
15480 this.minRows
= config
.rows
!== undefined ? config
.rows
: '';
15481 this.maxRows
= config
.maxRows
|| Math
.max( 2 * ( this.minRows
|| 0 ), 10 );
15482 this.validate
= null;
15484 // Clone for resizing
15485 if ( this.autosize
) {
15486 this.$clone
= this.$input
15488 .insertAfter( this.$input
)
15489 .attr( 'aria-hidden', 'true' )
15490 .addClass( 'oo-ui-element-hidden' );
15493 this.setValidation( config
.validate
);
15494 this.setLabelPosition( config
.labelPosition
);
15498 keypress
: this.onKeyPress
.bind( this ),
15499 blur
: this.onBlur
.bind( this )
15502 focus
: this.onElementAttach
.bind( this )
15504 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
15505 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
15506 this.on( 'labelChange', this.updatePosition
.bind( this ) );
15507 this.connect( this, {
15508 change
: 'onChange',
15509 disable
: 'onDisable'
15514 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type
)
15515 .append( this.$icon
, this.$indicator
);
15516 this.setReadOnly( !!config
.readOnly
);
15517 this.updateSearchIndicator();
15518 if ( config
.placeholder
) {
15519 this.$input
.attr( 'placeholder', config
.placeholder
);
15521 if ( config
.maxLength
!== undefined ) {
15522 this.$input
.attr( 'maxlength', config
.maxLength
);
15524 if ( config
.autofocus
) {
15525 this.$input
.attr( 'autofocus', 'autofocus' );
15527 if ( config
.required
) {
15528 this.$input
.attr( 'required', 'required' );
15529 this.$input
.attr( 'aria-required', 'true' );
15531 if ( config
.autocomplete
=== false ) {
15532 this.$input
.attr( 'autocomplete', 'off' );
15534 if ( this.multiline
&& config
.rows
) {
15535 this.$input
.attr( 'rows', config
.rows
);
15537 if ( this.label
|| config
.autosize
) {
15538 this.installParentChangeDetector();
15544 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
15545 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IconElement
);
15546 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
15547 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.PendingElement
);
15548 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.LabelElement
);
15550 /* Static Properties */
15552 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
15560 * An `enter` event is emitted when the user presses 'enter' inside the text box.
15562 * Not emitted if the input is multiline.
15570 * Handle icon mouse down events.
15573 * @param {jQuery.Event} e Mouse down event
15576 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
15577 if ( e
.which
=== 1 ) {
15578 this.$input
[ 0 ].focus();
15584 * Handle indicator mouse down events.
15587 * @param {jQuery.Event} e Mouse down event
15590 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
15591 if ( e
.which
=== 1 ) {
15592 if ( this.type
=== 'search' ) {
15593 // Clear the text field
15594 this.setValue( '' );
15596 this.$input
[ 0 ].focus();
15602 * Handle key press events.
15605 * @param {jQuery.Event} e Key press event
15606 * @fires enter If enter key is pressed and input is not multiline
15608 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
15609 if ( e
.which
=== OO
.ui
.Keys
.ENTER
&& !this.multiline
) {
15610 this.emit( 'enter', e
);
15615 * Handle blur events.
15618 * @param {jQuery.Event} e Blur event
15620 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
15621 this.setValidityFlag();
15625 * Handle element attach events.
15628 * @param {jQuery.Event} e Element attach event
15630 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
15631 // Any previously calculated size is now probably invalid if we reattached elsewhere
15632 this.valCache
= null;
15634 this.positionLabel();
15638 * Handle change events.
15640 * @param {string} value
15643 OO
.ui
.TextInputWidget
.prototype.onChange = function () {
15644 this.updateSearchIndicator();
15645 this.setValidityFlag();
15650 * Handle disable events.
15652 * @param {boolean} disabled Element is disabled
15655 OO
.ui
.TextInputWidget
.prototype.onDisable = function () {
15656 this.updateSearchIndicator();
15660 * Check if the input is {@link #readOnly read-only}.
15662 * @return {boolean}
15664 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
15665 return this.readOnly
;
15669 * Set the {@link #readOnly read-only} state of the input.
15671 * @param {boolean} state Make input read-only
15674 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
15675 this.readOnly
= !!state
;
15676 this.$input
.prop( 'readOnly', this.readOnly
);
15677 this.updateSearchIndicator();
15682 * Support function for making #onElementAttach work across browsers.
15684 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
15685 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
15687 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
15688 * first time that the element gets attached to the documented.
15690 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
15691 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
15692 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
15695 if ( MutationObserver
) {
15696 // The new way. If only it wasn't so ugly.
15698 if ( this.$element
.closest( 'html' ).length
) {
15699 // Widget is attached already, do nothing. This breaks the functionality of this function when
15700 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
15701 // would require observation of the whole document, which would hurt performance of other,
15702 // more important code.
15706 // Find topmost node in the tree
15707 topmostNode
= this.$element
[ 0 ];
15708 while ( topmostNode
.parentNode
) {
15709 topmostNode
= topmostNode
.parentNode
;
15712 // We have no way to detect the $element being attached somewhere without observing the entire
15713 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
15714 // parent node of $element, and instead detect when $element is removed from it (and thus
15715 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
15716 // doesn't get attached, we end up back here and create the parent.
15718 mutationObserver
= new MutationObserver( function ( mutations
) {
15719 var i
, j
, removedNodes
;
15720 for ( i
= 0; i
< mutations
.length
; i
++ ) {
15721 removedNodes
= mutations
[ i
].removedNodes
;
15722 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
15723 if ( removedNodes
[ j
] === topmostNode
) {
15724 setTimeout( onRemove
, 0 );
15731 onRemove = function () {
15732 // If the node was attached somewhere else, report it
15733 if ( widget
.$element
.closest( 'html' ).length
) {
15734 widget
.onElementAttach();
15736 mutationObserver
.disconnect();
15737 widget
.installParentChangeDetector();
15740 // Create a fake parent and observe it
15741 fakeParentNode
= $( '<div>' ).append( topmostNode
)[ 0 ];
15742 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
15744 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
15745 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
15746 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
15751 * Automatically adjust the size of the text input.
15753 * This only affects #multiline inputs that are {@link #autosize autosized}.
15757 OO
.ui
.TextInputWidget
.prototype.adjustSize = function () {
15758 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
, idealHeight
;
15760 if ( this.multiline
&& this.autosize
&& this.$input
.val() !== this.valCache
) {
15762 .val( this.$input
.val() )
15763 .attr( 'rows', this.minRows
)
15764 // Set inline height property to 0 to measure scroll height
15765 .css( 'height', 0 );
15767 this.$clone
.removeClass( 'oo-ui-element-hidden' );
15769 this.valCache
= this.$input
.val();
15771 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
15773 // Remove inline height property to measure natural heights
15774 this.$clone
.css( 'height', '' );
15775 innerHeight
= this.$clone
.innerHeight();
15776 outerHeight
= this.$clone
.outerHeight();
15778 // Measure max rows height
15780 .attr( 'rows', this.maxRows
)
15781 .css( 'height', 'auto' )
15783 maxInnerHeight
= this.$clone
.innerHeight();
15785 // Difference between reported innerHeight and scrollHeight with no scrollbars present
15786 // Equals 1 on Blink-based browsers and 0 everywhere else
15787 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
15788 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
15790 this.$clone
.addClass( 'oo-ui-element-hidden' );
15792 // Only apply inline height when expansion beyond natural height is needed
15793 if ( idealHeight
> innerHeight
) {
15794 // Use the difference between the inner and outer height as a buffer
15795 this.$input
.css( 'height', idealHeight
+ ( outerHeight
- innerHeight
) );
15797 this.$input
.css( 'height', '' );
15807 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
15808 return config
.multiline
?
15809 $( '<textarea>' ) :
15810 $( '<input type="' + this.getSaneType( config
) + '" />' );
15814 * Get sanitized value for 'type' for given config.
15816 * @param {Object} config Configuration options
15817 * @return {string|null}
15820 OO
.ui
.TextInputWidget
.prototype.getSaneType = function ( config
) {
15821 var type
= [ 'text', 'password', 'search', 'email', 'url' ].indexOf( config
.type
) !== -1 ?
15824 return config
.multiline
? 'multiline' : type
;
15828 * Check if the input supports multiple lines.
15830 * @return {boolean}
15832 OO
.ui
.TextInputWidget
.prototype.isMultiline = function () {
15833 return !!this.multiline
;
15837 * Check if the input automatically adjusts its size.
15839 * @return {boolean}
15841 OO
.ui
.TextInputWidget
.prototype.isAutosizing = function () {
15842 return !!this.autosize
;
15846 * Select the entire text of the input.
15850 OO
.ui
.TextInputWidget
.prototype.select = function () {
15851 this.$input
.select();
15856 * Focus the input and move the cursor to the end.
15858 OO
.ui
.TextInputWidget
.prototype.moveCursorToEnd = function () {
15860 element
= this.$input
[ 0 ];
15862 if ( element
.selectionStart
!== undefined ) {
15863 element
.selectionStart
= element
.selectionEnd
= element
.value
.length
;
15864 } else if ( element
.createTextRange
) {
15866 textRange
= element
.createTextRange();
15867 textRange
.collapse( false );
15868 textRange
.select();
15873 * Set the validation pattern.
15875 * The validation pattern is either a regular expression, a function, or the symbolic name of a
15876 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
15877 * value must contain only numbers).
15879 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
15880 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
15882 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
15883 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
15884 this.validate
= validate
;
15886 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
15891 * Sets the 'invalid' flag appropriately.
15893 * @param {boolean} [isValid] Optionally override validation result
15895 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
15897 setFlag = function ( valid
) {
15899 widget
.$input
.attr( 'aria-invalid', 'true' );
15901 widget
.$input
.removeAttr( 'aria-invalid' );
15903 widget
.setFlags( { invalid
: !valid
} );
15906 if ( isValid
!== undefined ) {
15907 setFlag( isValid
);
15909 this.getValidity().then( function () {
15918 * Check if a value is valid.
15920 * This method returns a promise that resolves with a boolean `true` if the current value is
15921 * considered valid according to the supplied {@link #validate validation pattern}.
15924 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
15926 OO
.ui
.TextInputWidget
.prototype.isValid = function () {
15929 if ( this.validate
instanceof Function
) {
15930 result
= this.validate( this.getValue() );
15931 if ( $.isFunction( result
.promise
) ) {
15932 return result
.promise();
15934 return $.Deferred().resolve( !!result
).promise();
15937 return $.Deferred().resolve( !!this.getValue().match( this.validate
) ).promise();
15942 * Get the validity of current value.
15944 * This method returns a promise that resolves if the value is valid and rejects if
15945 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
15947 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
15949 OO
.ui
.TextInputWidget
.prototype.getValidity = function () {
15950 var result
, promise
;
15952 function rejectOrResolve( valid
) {
15954 return $.Deferred().resolve().promise();
15956 return $.Deferred().reject().promise();
15960 if ( this.validate
instanceof Function
) {
15961 result
= this.validate( this.getValue() );
15963 if ( $.isFunction( result
.promise
) ) {
15964 promise
= $.Deferred();
15966 result
.then( function ( valid
) {
15976 return promise
.promise();
15978 return rejectOrResolve( result
);
15981 return rejectOrResolve( this.getValue().match( this.validate
) );
15986 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
15988 * @param {string} labelPosition Label position, 'before' or 'after'
15991 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
15992 this.labelPosition
= labelPosition
;
15993 this.updatePosition();
15998 * Deprecated alias of #setLabelPosition
16000 * @deprecated Use setLabelPosition instead.
16002 OO
.ui
.TextInputWidget
.prototype.setPosition
=
16003 OO
.ui
.TextInputWidget
.prototype.setLabelPosition
;
16006 * Update the position of the inline label.
16008 * This method is called by #setLabelPosition, and can also be called on its own if
16009 * something causes the label to be mispositioned.
16013 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
16014 var after
= this.labelPosition
=== 'after';
16017 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
16018 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
16020 this.positionLabel();
16026 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
16027 * already empty or when it's not editable.
16029 OO
.ui
.TextInputWidget
.prototype.updateSearchIndicator = function () {
16030 if ( this.type
=== 'search' ) {
16031 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
16032 this.setIndicator( null );
16034 this.setIndicator( 'clear' );
16040 * Position the label by setting the correct padding on the input.
16045 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
16046 var after
, rtl
, property
;
16047 // Clear old values
16049 // Clear old values if present
16051 'padding-right': '',
16055 if ( this.label
) {
16056 this.$element
.append( this.$label
);
16058 this.$label
.detach();
16062 after
= this.labelPosition
=== 'after';
16063 rtl
= this.$element
.css( 'direction' ) === 'rtl';
16064 property
= after
=== rtl
? 'padding-left' : 'padding-right';
16066 this.$input
.css( property
, this.$label
.outerWidth( true ) );
16074 OO
.ui
.TextInputWidget
.prototype.gatherPreInfuseState = function ( node
) {
16076 state
= OO
.ui
.TextInputWidget
.parent
.prototype.gatherPreInfuseState
.call( this, node
),
16077 $input
= $( node
).find( '.oo-ui-inputWidget-input' );
16078 state
.$input
= $input
; // shortcut for performance, used in InputWidget
16079 if ( this.multiline
) {
16080 state
.scrollTop
= $input
.scrollTop();
16088 OO
.ui
.TextInputWidget
.prototype.restorePreInfuseState = function ( state
) {
16089 OO
.ui
.TextInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
16090 if ( state
.scrollTop
!== undefined ) {
16091 this.$input
.scrollTop( state
.scrollTop
);
16096 * ComboBoxWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
16097 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
16098 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
16100 * - by typing a value in the text input field. If the value exactly matches the value of a menu
16101 * option, that option will appear to be selected.
16102 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
16105 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
16108 * // Example: A ComboBoxWidget.
16109 * var comboBox = new OO.ui.ComboBoxWidget( {
16110 * label: 'ComboBoxWidget',
16111 * input: { value: 'Option One' },
16114 * new OO.ui.MenuOptionWidget( {
16115 * data: 'Option 1',
16116 * label: 'Option One'
16118 * new OO.ui.MenuOptionWidget( {
16119 * data: 'Option 2',
16120 * label: 'Option Two'
16122 * new OO.ui.MenuOptionWidget( {
16123 * data: 'Option 3',
16124 * label: 'Option Three'
16126 * new OO.ui.MenuOptionWidget( {
16127 * data: 'Option 4',
16128 * label: 'Option Four'
16130 * new OO.ui.MenuOptionWidget( {
16131 * data: 'Option 5',
16132 * label: 'Option Five'
16137 * $( 'body' ).append( comboBox.$element );
16139 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
16142 * @extends OO.ui.Widget
16143 * @mixins OO.ui.mixin.TabIndexedElement
16146 * @param {Object} [config] Configuration options
16147 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
16148 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
16149 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
16150 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
16151 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
16153 OO
.ui
.ComboBoxWidget
= function OoUiComboBoxWidget( config
) {
16154 // Configuration initialization
16155 config
= config
|| {};
16157 // Parent constructor
16158 OO
.ui
.ComboBoxWidget
.parent
.call( this, config
);
16160 // Properties (must be set before TabIndexedElement constructor call)
16161 this.$indicator
= this.$( '<span>' );
16163 // Mixin constructors
16164 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$indicator
} ) );
16167 this.$overlay
= config
.$overlay
|| this.$element
;
16168 this.input
= new OO
.ui
.TextInputWidget( $.extend(
16171 $indicator
: this.$indicator
,
16172 disabled
: this.isDisabled()
16176 this.input
.$input
.eq( 0 ).attr( {
16178 'aria-autocomplete': 'list'
16180 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend(
16184 $container
: this.input
.$element
,
16185 disabled
: this.isDisabled()
16191 this.$indicator
.on( {
16192 click
: this.onClick
.bind( this ),
16193 keypress
: this.onKeyPress
.bind( this )
16195 this.input
.connect( this, {
16196 change
: 'onInputChange',
16197 enter
: 'onInputEnter'
16199 this.menu
.connect( this, {
16200 choose
: 'onMenuChoose',
16201 add
: 'onMenuItemsChange',
16202 remove
: 'onMenuItemsChange'
16206 this.$element
.addClass( 'oo-ui-comboBoxWidget' ).append( this.input
.$element
);
16207 this.$overlay
.append( this.menu
.$element
);
16208 this.onMenuItemsChange();
16213 OO
.inheritClass( OO
.ui
.ComboBoxWidget
, OO
.ui
.Widget
);
16214 OO
.mixinClass( OO
.ui
.ComboBoxWidget
, OO
.ui
.mixin
.TabIndexedElement
);
16219 * Get the combobox's menu.
16220 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
16222 OO
.ui
.ComboBoxWidget
.prototype.getMenu = function () {
16227 * Get the combobox's text input widget.
16228 * @return {OO.ui.TextInputWidget} Text input widget
16230 OO
.ui
.ComboBoxWidget
.prototype.getInput = function () {
16235 * Handle input change events.
16238 * @param {string} value New value
16240 OO
.ui
.ComboBoxWidget
.prototype.onInputChange = function ( value
) {
16241 var match
= this.menu
.getItemFromData( value
);
16243 this.menu
.selectItem( match
);
16244 if ( this.menu
.getHighlightedItem() ) {
16245 this.menu
.highlightItem( match
);
16248 if ( !this.isDisabled() ) {
16249 this.menu
.toggle( true );
16254 * Handle mouse click events.
16257 * @param {jQuery.Event} e Mouse click event
16259 OO
.ui
.ComboBoxWidget
.prototype.onClick = function ( e
) {
16260 if ( !this.isDisabled() && e
.which
=== 1 ) {
16261 this.menu
.toggle();
16262 this.input
.$input
[ 0 ].focus();
16268 * Handle key press events.
16271 * @param {jQuery.Event} e Key press event
16273 OO
.ui
.ComboBoxWidget
.prototype.onKeyPress = function ( e
) {
16274 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
16275 this.menu
.toggle();
16276 this.input
.$input
[ 0 ].focus();
16282 * Handle input enter events.
16286 OO
.ui
.ComboBoxWidget
.prototype.onInputEnter = function () {
16287 if ( !this.isDisabled() ) {
16288 this.menu
.toggle( false );
16293 * Handle menu choose events.
16296 * @param {OO.ui.OptionWidget} item Chosen item
16298 OO
.ui
.ComboBoxWidget
.prototype.onMenuChoose = function ( item
) {
16299 this.input
.setValue( item
.getData() );
16303 * Handle menu item change events.
16307 OO
.ui
.ComboBoxWidget
.prototype.onMenuItemsChange = function () {
16308 var match
= this.menu
.getItemFromData( this.input
.getValue() );
16309 this.menu
.selectItem( match
);
16310 if ( this.menu
.getHighlightedItem() ) {
16311 this.menu
.highlightItem( match
);
16313 this.$element
.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu
.isEmpty() );
16319 OO
.ui
.ComboBoxWidget
.prototype.setDisabled = function ( disabled
) {
16321 OO
.ui
.ComboBoxWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
16323 if ( this.input
) {
16324 this.input
.setDisabled( this.isDisabled() );
16327 this.menu
.setDisabled( this.isDisabled() );
16334 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
16335 * be configured with a `label` option that is set to a string, a label node, or a function:
16337 * - String: a plaintext string
16338 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
16339 * label that includes a link or special styling, such as a gray color or additional graphical elements.
16340 * - Function: a function that will produce a string in the future. Functions are used
16341 * in cases where the value of the label is not currently defined.
16343 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
16344 * will come into focus when the label is clicked.
16347 * // Examples of LabelWidgets
16348 * var label1 = new OO.ui.LabelWidget( {
16349 * label: 'plaintext label'
16351 * var label2 = new OO.ui.LabelWidget( {
16352 * label: $( '<a href="default.html">jQuery label</a>' )
16354 * // Create a fieldset layout with fields for each example
16355 * var fieldset = new OO.ui.FieldsetLayout();
16356 * fieldset.addItems( [
16357 * new OO.ui.FieldLayout( label1 ),
16358 * new OO.ui.FieldLayout( label2 )
16360 * $( 'body' ).append( fieldset.$element );
16363 * @extends OO.ui.Widget
16364 * @mixins OO.ui.mixin.LabelElement
16367 * @param {Object} [config] Configuration options
16368 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
16369 * Clicking the label will focus the specified input field.
16371 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
16372 // Configuration initialization
16373 config
= config
|| {};
16375 // Parent constructor
16376 OO
.ui
.LabelWidget
.parent
.call( this, config
);
16378 // Mixin constructors
16379 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
16380 OO
.ui
.mixin
.TitledElement
.call( this, config
);
16383 this.input
= config
.input
;
16386 if ( this.input
instanceof OO
.ui
.InputWidget
) {
16387 this.$element
.on( 'click', this.onClick
.bind( this ) );
16391 this.$element
.addClass( 'oo-ui-labelWidget' );
16396 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
16397 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.LabelElement
);
16398 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.TitledElement
);
16400 /* Static Properties */
16402 OO
.ui
.LabelWidget
.static.tagName
= 'span';
16407 * Handles label mouse click events.
16410 * @param {jQuery.Event} e Mouse click event
16412 OO
.ui
.LabelWidget
.prototype.onClick = function () {
16413 this.input
.simulateLabelClick();
16418 * OptionWidgets are special elements that can be selected and configured with data. The
16419 * data is often unique for each option, but it does not have to be. OptionWidgets are used
16420 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
16421 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
16423 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16426 * @extends OO.ui.Widget
16427 * @mixins OO.ui.mixin.LabelElement
16428 * @mixins OO.ui.mixin.FlaggedElement
16431 * @param {Object} [config] Configuration options
16433 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
16434 // Configuration initialization
16435 config
= config
|| {};
16437 // Parent constructor
16438 OO
.ui
.OptionWidget
.parent
.call( this, config
);
16440 // Mixin constructors
16441 OO
.ui
.mixin
.ItemWidget
.call( this );
16442 OO
.ui
.mixin
.LabelElement
.call( this, config
);
16443 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
16446 this.selected
= false;
16447 this.highlighted
= false;
16448 this.pressed
= false;
16452 .data( 'oo-ui-optionWidget', this )
16453 .attr( 'role', 'option' )
16454 .attr( 'aria-selected', 'false' )
16455 .addClass( 'oo-ui-optionWidget' )
16456 .append( this.$label
);
16461 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
16462 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.ItemWidget
);
16463 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.LabelElement
);
16464 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.FlaggedElement
);
16466 /* Static Properties */
16468 OO
.ui
.OptionWidget
.static.selectable
= true;
16470 OO
.ui
.OptionWidget
.static.highlightable
= true;
16472 OO
.ui
.OptionWidget
.static.pressable
= true;
16474 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
16479 * Check if the option can be selected.
16481 * @return {boolean} Item is selectable
16483 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
16484 return this.constructor.static.selectable
&& !this.isDisabled() && this.isVisible();
16488 * Check if the option can be highlighted. A highlight indicates that the option
16489 * may be selected when a user presses enter or clicks. Disabled items cannot
16492 * @return {boolean} Item is highlightable
16494 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
16495 return this.constructor.static.highlightable
&& !this.isDisabled() && this.isVisible();
16499 * Check if the option can be pressed. The pressed state occurs when a user mouses
16500 * down on an item, but has not yet let go of the mouse.
16502 * @return {boolean} Item is pressable
16504 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
16505 return this.constructor.static.pressable
&& !this.isDisabled() && this.isVisible();
16509 * Check if the option is selected.
16511 * @return {boolean} Item is selected
16513 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
16514 return this.selected
;
16518 * Check if the option is highlighted. A highlight indicates that the
16519 * item may be selected when a user presses enter or clicks.
16521 * @return {boolean} Item is highlighted
16523 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
16524 return this.highlighted
;
16528 * Check if the option is pressed. The pressed state occurs when a user mouses
16529 * down on an item, but has not yet let go of the mouse. The item may appear
16530 * selected, but it will not be selected until the user releases the mouse.
16532 * @return {boolean} Item is pressed
16534 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
16535 return this.pressed
;
16539 * Set the option’s selected state. In general, all modifications to the selection
16540 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
16541 * method instead of this method.
16543 * @param {boolean} [state=false] Select option
16546 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
16547 if ( this.constructor.static.selectable
) {
16548 this.selected
= !!state
;
16550 .toggleClass( 'oo-ui-optionWidget-selected', state
)
16551 .attr( 'aria-selected', state
.toString() );
16552 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
16553 this.scrollElementIntoView();
16555 this.updateThemeClasses();
16561 * Set the option’s highlighted state. In general, all programmatic
16562 * modifications to the highlight should be handled by the
16563 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
16564 * method instead of this method.
16566 * @param {boolean} [state=false] Highlight option
16569 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
16570 if ( this.constructor.static.highlightable
) {
16571 this.highlighted
= !!state
;
16572 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
16573 this.updateThemeClasses();
16579 * Set the option’s pressed state. In general, all
16580 * programmatic modifications to the pressed state should be handled by the
16581 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
16582 * method instead of this method.
16584 * @param {boolean} [state=false] Press option
16587 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
16588 if ( this.constructor.static.pressable
) {
16589 this.pressed
= !!state
;
16590 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
16591 this.updateThemeClasses();
16597 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
16598 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
16599 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
16600 * options. For more information about options and selects, please see the
16601 * [OOjs UI documentation on MediaWiki][1].
16604 * // Decorated options in a select widget
16605 * var select = new OO.ui.SelectWidget( {
16607 * new OO.ui.DecoratedOptionWidget( {
16609 * label: 'Option with icon',
16612 * new OO.ui.DecoratedOptionWidget( {
16614 * label: 'Option with indicator',
16615 * indicator: 'next'
16619 * $( 'body' ).append( select.$element );
16621 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16624 * @extends OO.ui.OptionWidget
16625 * @mixins OO.ui.mixin.IconElement
16626 * @mixins OO.ui.mixin.IndicatorElement
16629 * @param {Object} [config] Configuration options
16631 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
16632 // Parent constructor
16633 OO
.ui
.DecoratedOptionWidget
.parent
.call( this, config
);
16635 // Mixin constructors
16636 OO
.ui
.mixin
.IconElement
.call( this, config
);
16637 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
16641 .addClass( 'oo-ui-decoratedOptionWidget' )
16642 .prepend( this.$icon
)
16643 .append( this.$indicator
);
16648 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
16649 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IconElement
);
16650 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IndicatorElement
);
16653 * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that
16654 * can be selected and configured with data. The class is
16655 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
16656 * [OOjs UI documentation on MediaWiki] [1] for more information.
16658 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
16661 * @extends OO.ui.DecoratedOptionWidget
16662 * @mixins OO.ui.mixin.ButtonElement
16663 * @mixins OO.ui.mixin.TabIndexedElement
16664 * @mixins OO.ui.mixin.TitledElement
16667 * @param {Object} [config] Configuration options
16669 OO
.ui
.ButtonOptionWidget
= function OoUiButtonOptionWidget( config
) {
16670 // Configuration initialization
16671 config
= config
|| {};
16673 // Parent constructor
16674 OO
.ui
.ButtonOptionWidget
.parent
.call( this, config
);
16676 // Mixin constructors
16677 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
16678 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
16679 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, {
16680 $tabIndexed
: this.$button
,
16685 this.$element
.addClass( 'oo-ui-buttonOptionWidget' );
16686 this.$button
.append( this.$element
.contents() );
16687 this.$element
.append( this.$button
);
16692 OO
.inheritClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
16693 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.ButtonElement
);
16694 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.TitledElement
);
16695 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.TabIndexedElement
);
16697 /* Static Properties */
16699 // Allow button mouse down events to pass through so they can be handled by the parent select widget
16700 OO
.ui
.ButtonOptionWidget
.static.cancelButtonMouseDownEvents
= false;
16702 OO
.ui
.ButtonOptionWidget
.static.highlightable
= false;
16709 OO
.ui
.ButtonOptionWidget
.prototype.setSelected = function ( state
) {
16710 OO
.ui
.ButtonOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
16712 if ( this.constructor.static.selectable
) {
16713 this.setActive( state
);
16720 * RadioOptionWidget is an option widget that looks like a radio button.
16721 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
16722 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
16724 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
16727 * @extends OO.ui.OptionWidget
16730 * @param {Object} [config] Configuration options
16732 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
16733 // Configuration initialization
16734 config
= config
|| {};
16736 // Properties (must be done before parent constructor which calls #setDisabled)
16737 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
16739 // Parent constructor
16740 OO
.ui
.RadioOptionWidget
.parent
.call( this, config
);
16743 this.radio
.$input
.on( 'focus', this.onInputFocus
.bind( this ) );
16746 // Remove implicit role, we're handling it ourselves
16747 this.radio
.$input
.attr( 'role', 'presentation' );
16749 .addClass( 'oo-ui-radioOptionWidget' )
16750 .attr( 'role', 'radio' )
16751 .attr( 'aria-checked', 'false' )
16752 .removeAttr( 'aria-selected' )
16753 .prepend( this.radio
.$element
);
16758 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
16760 /* Static Properties */
16762 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
16764 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
16766 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
16768 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
16773 * @param {jQuery.Event} e Focus event
16776 OO
.ui
.RadioOptionWidget
.prototype.onInputFocus = function () {
16777 this.radio
.$input
.blur();
16778 this.$element
.parent().focus();
16784 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
16785 OO
.ui
.RadioOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
16787 this.radio
.setSelected( state
);
16789 .attr( 'aria-checked', state
.toString() )
16790 .removeAttr( 'aria-selected' );
16798 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
16799 OO
.ui
.RadioOptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
16801 this.radio
.setDisabled( this.isDisabled() );
16807 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
16808 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
16809 * the [OOjs UI documentation on MediaWiki] [1] for more information.
16811 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
16814 * @extends OO.ui.DecoratedOptionWidget
16817 * @param {Object} [config] Configuration options
16819 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
16820 // Configuration initialization
16821 config
= $.extend( { icon
: 'check' }, config
);
16823 // Parent constructor
16824 OO
.ui
.MenuOptionWidget
.parent
.call( this, config
);
16828 .attr( 'role', 'menuitem' )
16829 .addClass( 'oo-ui-menuOptionWidget' );
16834 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
16836 /* Static Properties */
16838 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
16841 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
16842 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
16845 * var myDropdown = new OO.ui.DropdownWidget( {
16848 * new OO.ui.MenuSectionOptionWidget( {
16851 * new OO.ui.MenuOptionWidget( {
16853 * label: 'Welsh Corgi'
16855 * new OO.ui.MenuOptionWidget( {
16857 * label: 'Standard Poodle'
16859 * new OO.ui.MenuSectionOptionWidget( {
16862 * new OO.ui.MenuOptionWidget( {
16869 * $( 'body' ).append( myDropdown.$element );
16872 * @extends OO.ui.DecoratedOptionWidget
16875 * @param {Object} [config] Configuration options
16877 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
16878 // Parent constructor
16879 OO
.ui
.MenuSectionOptionWidget
.parent
.call( this, config
);
16882 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' );
16887 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
16889 /* Static Properties */
16891 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
16893 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
16896 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
16898 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
16899 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
16903 * @extends OO.ui.DecoratedOptionWidget
16906 * @param {Object} [config] Configuration options
16907 * @cfg {number} [level] Indentation level
16908 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
16910 OO
.ui
.OutlineOptionWidget
= function OoUiOutlineOptionWidget( config
) {
16911 // Configuration initialization
16912 config
= config
|| {};
16914 // Parent constructor
16915 OO
.ui
.OutlineOptionWidget
.parent
.call( this, config
);
16919 this.movable
= !!config
.movable
;
16920 this.removable
= !!config
.removable
;
16923 this.$element
.addClass( 'oo-ui-outlineOptionWidget' );
16924 this.setLevel( config
.level
);
16929 OO
.inheritClass( OO
.ui
.OutlineOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
16931 /* Static Properties */
16933 OO
.ui
.OutlineOptionWidget
.static.highlightable
= false;
16935 OO
.ui
.OutlineOptionWidget
.static.scrollIntoViewOnSelect
= true;
16937 OO
.ui
.OutlineOptionWidget
.static.levelClass
= 'oo-ui-outlineOptionWidget-level-';
16939 OO
.ui
.OutlineOptionWidget
.static.levels
= 3;
16944 * Check if item is movable.
16946 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16948 * @return {boolean} Item is movable
16950 OO
.ui
.OutlineOptionWidget
.prototype.isMovable = function () {
16951 return this.movable
;
16955 * Check if item is removable.
16957 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16959 * @return {boolean} Item is removable
16961 OO
.ui
.OutlineOptionWidget
.prototype.isRemovable = function () {
16962 return this.removable
;
16966 * Get indentation level.
16968 * @return {number} Indentation level
16970 OO
.ui
.OutlineOptionWidget
.prototype.getLevel = function () {
16977 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16979 * @param {boolean} movable Item is movable
16982 OO
.ui
.OutlineOptionWidget
.prototype.setMovable = function ( movable
) {
16983 this.movable
= !!movable
;
16984 this.updateThemeClasses();
16989 * Set removability.
16991 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16993 * @param {boolean} movable Item is removable
16996 OO
.ui
.OutlineOptionWidget
.prototype.setRemovable = function ( removable
) {
16997 this.removable
= !!removable
;
16998 this.updateThemeClasses();
17003 * Set indentation level.
17005 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
17008 OO
.ui
.OutlineOptionWidget
.prototype.setLevel = function ( level
) {
17009 var levels
= this.constructor.static.levels
,
17010 levelClass
= this.constructor.static.levelClass
,
17013 this.level
= level
? Math
.max( 0, Math
.min( levels
- 1, level
) ) : 0;
17015 if ( this.level
=== i
) {
17016 this.$element
.addClass( levelClass
+ i
);
17018 this.$element
.removeClass( levelClass
+ i
);
17021 this.updateThemeClasses();
17027 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
17029 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
17030 * {@link OO.ui.CardLayout card layouts}. See {@link OO.ui.IndexLayout IndexLayout}
17034 * @extends OO.ui.OptionWidget
17037 * @param {Object} [config] Configuration options
17039 OO
.ui
.TabOptionWidget
= function OoUiTabOptionWidget( config
) {
17040 // Configuration initialization
17041 config
= config
|| {};
17043 // Parent constructor
17044 OO
.ui
.TabOptionWidget
.parent
.call( this, config
);
17047 this.$element
.addClass( 'oo-ui-tabOptionWidget' );
17052 OO
.inheritClass( OO
.ui
.TabOptionWidget
, OO
.ui
.OptionWidget
);
17054 /* Static Properties */
17056 OO
.ui
.TabOptionWidget
.static.highlightable
= false;
17059 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
17060 * By default, each popup has an anchor that points toward its origin.
17061 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
17064 * // A popup widget.
17065 * var popup = new OO.ui.PopupWidget( {
17066 * $content: $( '<p>Hi there!</p>' ),
17071 * $( 'body' ).append( popup.$element );
17072 * // To display the popup, toggle the visibility to 'true'.
17073 * popup.toggle( true );
17075 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
17078 * @extends OO.ui.Widget
17079 * @mixins OO.ui.mixin.LabelElement
17080 * @mixins OO.ui.mixin.ClippableElement
17083 * @param {Object} [config] Configuration options
17084 * @cfg {number} [width=320] Width of popup in pixels
17085 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
17086 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
17087 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
17088 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
17089 * popup is leaning towards the right of the screen.
17090 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
17091 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
17092 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
17093 * sentence in the given language.
17094 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
17095 * See the [OOjs UI docs on MediaWiki][3] for an example.
17096 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
17097 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
17098 * @cfg {jQuery} [$content] Content to append to the popup's body
17099 * @cfg {jQuery} [$footer] Content to append to the popup's footer
17100 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
17101 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
17102 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
17104 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
17105 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
17107 * @cfg {boolean} [padded] Add padding to the popup's body
17109 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
17110 // Configuration initialization
17111 config
= config
|| {};
17113 // Parent constructor
17114 OO
.ui
.PopupWidget
.parent
.call( this, config
);
17116 // Properties (must be set before ClippableElement constructor call)
17117 this.$body
= $( '<div>' );
17118 this.$popup
= $( '<div>' );
17120 // Mixin constructors
17121 OO
.ui
.mixin
.LabelElement
.call( this, config
);
17122 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, {
17123 $clippable
: this.$body
,
17124 $clippableContainer
: this.$popup
17128 this.$head
= $( '<div>' );
17129 this.$footer
= $( '<div>' );
17130 this.$anchor
= $( '<div>' );
17131 // If undefined, will be computed lazily in updateDimensions()
17132 this.$container
= config
.$container
;
17133 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
17134 this.autoClose
= !!config
.autoClose
;
17135 this.$autoCloseIgnore
= config
.$autoCloseIgnore
;
17136 this.transitionTimeout
= null;
17137 this.anchor
= null;
17138 this.width
= config
.width
!== undefined ? config
.width
: 320;
17139 this.height
= config
.height
!== undefined ? config
.height
: null;
17140 this.setAlignment( config
.align
);
17141 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
17142 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
17143 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
17146 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
17149 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
17150 this.$body
.addClass( 'oo-ui-popupWidget-body' );
17151 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
17153 .addClass( 'oo-ui-popupWidget-head' )
17154 .append( this.$label
, this.closeButton
.$element
);
17155 this.$footer
.addClass( 'oo-ui-popupWidget-footer' );
17156 if ( !config
.head
) {
17157 this.$head
.addClass( 'oo-ui-element-hidden' );
17159 if ( !config
.$footer
) {
17160 this.$footer
.addClass( 'oo-ui-element-hidden' );
17163 .addClass( 'oo-ui-popupWidget-popup' )
17164 .append( this.$head
, this.$body
, this.$footer
);
17166 .addClass( 'oo-ui-popupWidget' )
17167 .append( this.$popup
, this.$anchor
);
17168 // Move content, which was added to #$element by OO.ui.Widget, to the body
17169 if ( config
.$content
instanceof jQuery
) {
17170 this.$body
.append( config
.$content
);
17172 if ( config
.$footer
instanceof jQuery
) {
17173 this.$footer
.append( config
.$footer
);
17175 if ( config
.padded
) {
17176 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
17179 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
17180 // that reference properties not initialized at that time of parent class construction
17181 // TODO: Find a better way to handle post-constructor setup
17182 this.visible
= false;
17183 this.$element
.addClass( 'oo-ui-element-hidden' );
17188 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
17189 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.LabelElement
);
17190 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.ClippableElement
);
17195 * Handles mouse down events.
17198 * @param {MouseEvent} e Mouse down event
17200 OO
.ui
.PopupWidget
.prototype.onMouseDown = function ( e
) {
17202 this.isVisible() &&
17203 !$.contains( this.$element
[ 0 ], e
.target
) &&
17204 ( !this.$autoCloseIgnore
|| !this.$autoCloseIgnore
.has( e
.target
).length
)
17206 this.toggle( false );
17211 * Bind mouse down listener.
17215 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
17216 // Capture clicks outside popup
17217 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler
);
17221 * Handles close button click events.
17225 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
17226 if ( this.isVisible() ) {
17227 this.toggle( false );
17232 * Unbind mouse down listener.
17236 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
17237 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler
);
17241 * Handles key down events.
17244 * @param {KeyboardEvent} e Key down event
17246 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
17248 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
17251 this.toggle( false );
17252 e
.preventDefault();
17253 e
.stopPropagation();
17258 * Bind key down listener.
17262 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
17263 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler
);
17267 * Unbind key down listener.
17271 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
17272 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler
);
17276 * Show, hide, or toggle the visibility of the anchor.
17278 * @param {boolean} [show] Show anchor, omit to toggle
17280 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
17281 show
= show
=== undefined ? !this.anchored
: !!show
;
17283 if ( this.anchored
!== show
) {
17285 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
17287 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
17289 this.anchored
= show
;
17294 * Check if the anchor is visible.
17296 * @return {boolean} Anchor is visible
17298 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
17299 return this.anchor
;
17305 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
17307 show
= show
=== undefined ? !this.isVisible() : !!show
;
17309 change
= show
!== this.isVisible();
17312 OO
.ui
.PopupWidget
.parent
.prototype.toggle
.call( this, show
);
17316 if ( this.autoClose
) {
17317 this.bindMouseDownListener();
17318 this.bindKeyDownListener();
17320 this.updateDimensions();
17321 this.toggleClipping( true );
17323 this.toggleClipping( false );
17324 if ( this.autoClose
) {
17325 this.unbindMouseDownListener();
17326 this.unbindKeyDownListener();
17335 * Set the size of the popup.
17337 * Changing the size may also change the popup's position depending on the alignment.
17339 * @param {number} width Width in pixels
17340 * @param {number} height Height in pixels
17341 * @param {boolean} [transition=false] Use a smooth transition
17344 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
17345 this.width
= width
;
17346 this.height
= height
!== undefined ? height
: null;
17347 if ( this.isVisible() ) {
17348 this.updateDimensions( transition
);
17353 * Update the size and position.
17355 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
17356 * be called automatically.
17358 * @param {boolean} [transition=false] Use a smooth transition
17361 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
17362 var popupOffset
, originOffset
, containerLeft
, containerWidth
, containerRight
,
17363 popupLeft
, popupRight
, overlapLeft
, overlapRight
, anchorWidth
,
17364 align
= this.align
,
17367 if ( !this.$container
) {
17368 // Lazy-initialize $container if not specified in constructor
17369 this.$container
= $( this.getClosestScrollableElementContainer() );
17372 // Set height and width before measuring things, since it might cause our measurements
17373 // to change (e.g. due to scrollbars appearing or disappearing)
17376 height
: this.height
!== null ? this.height
: 'auto'
17379 // If we are in RTL, we need to flip the alignment, unless it is center
17380 if ( align
=== 'forwards' || align
=== 'backwards' ) {
17381 if ( this.$container
.css( 'direction' ) === 'rtl' ) {
17382 align
= ( { forwards
: 'force-left', backwards
: 'force-right' } )[ this.align
];
17384 align
= ( { forwards
: 'force-right', backwards
: 'force-left' } )[ this.align
];
17389 // Compute initial popupOffset based on alignment
17390 popupOffset
= this.width
* ( { 'force-left': -1, center
: -0.5, 'force-right': 0 } )[ align
];
17392 // Figure out if this will cause the popup to go beyond the edge of the container
17393 originOffset
= this.$element
.offset().left
;
17394 containerLeft
= this.$container
.offset().left
;
17395 containerWidth
= this.$container
.innerWidth();
17396 containerRight
= containerLeft
+ containerWidth
;
17397 popupLeft
= popupOffset
- this.containerPadding
;
17398 popupRight
= popupOffset
+ this.containerPadding
+ this.width
+ this.containerPadding
;
17399 overlapLeft
= ( originOffset
+ popupLeft
) - containerLeft
;
17400 overlapRight
= containerRight
- ( originOffset
+ popupRight
);
17402 // Adjust offset to make the popup not go beyond the edge, if needed
17403 if ( overlapRight
< 0 ) {
17404 popupOffset
+= overlapRight
;
17405 } else if ( overlapLeft
< 0 ) {
17406 popupOffset
-= overlapLeft
;
17409 // Adjust offset to avoid anchor being rendered too close to the edge
17410 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
17411 // TODO: Find a measurement that works for CSS anchors and image anchors
17412 anchorWidth
= this.$anchor
[ 0 ].scrollWidth
* 2;
17413 if ( popupOffset
+ this.width
< anchorWidth
) {
17414 popupOffset
= anchorWidth
- this.width
;
17415 } else if ( -popupOffset
< anchorWidth
) {
17416 popupOffset
= -anchorWidth
;
17419 // Prevent transition from being interrupted
17420 clearTimeout( this.transitionTimeout
);
17421 if ( transition
) {
17422 // Enable transition
17423 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
17426 // Position body relative to anchor
17427 this.$popup
.css( 'margin-left', popupOffset
);
17429 if ( transition
) {
17430 // Prevent transitioning after transition is complete
17431 this.transitionTimeout
= setTimeout( function () {
17432 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
17435 // Prevent transitioning immediately
17436 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
17439 // Reevaluate clipping state since we've relocated and resized the popup
17446 * Set popup alignment
17447 * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17448 * `backwards` or `forwards`.
17450 OO
.ui
.PopupWidget
.prototype.setAlignment = function ( align
) {
17451 // Validate alignment and transform deprecated values
17452 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align
) > -1 ) {
17453 this.align
= { left
: 'force-right', right
: 'force-left' }[ align
] || align
;
17455 this.align
= 'center';
17460 * Get popup alignment
17461 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17462 * `backwards` or `forwards`.
17464 OO
.ui
.PopupWidget
.prototype.getAlignment = function () {
17469 * Progress bars visually display the status of an operation, such as a download,
17470 * and can be either determinate or indeterminate:
17472 * - **determinate** process bars show the percent of an operation that is complete.
17474 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
17475 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
17476 * not use percentages.
17478 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
17481 * // Examples of determinate and indeterminate progress bars.
17482 * var progressBar1 = new OO.ui.ProgressBarWidget( {
17485 * var progressBar2 = new OO.ui.ProgressBarWidget();
17487 * // Create a FieldsetLayout to layout progress bars
17488 * var fieldset = new OO.ui.FieldsetLayout;
17489 * fieldset.addItems( [
17490 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
17491 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
17493 * $( 'body' ).append( fieldset.$element );
17496 * @extends OO.ui.Widget
17499 * @param {Object} [config] Configuration options
17500 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
17501 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
17502 * By default, the progress bar is indeterminate.
17504 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
17505 // Configuration initialization
17506 config
= config
|| {};
17508 // Parent constructor
17509 OO
.ui
.ProgressBarWidget
.parent
.call( this, config
);
17512 this.$bar
= $( '<div>' );
17513 this.progress
= null;
17516 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
17517 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
17520 role
: 'progressbar',
17521 'aria-valuemin': 0,
17522 'aria-valuemax': 100
17524 .addClass( 'oo-ui-progressBarWidget' )
17525 .append( this.$bar
);
17530 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
17532 /* Static Properties */
17534 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
17539 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
17541 * @return {number|boolean} Progress percent
17543 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
17544 return this.progress
;
17548 * Set the percent of the process completed or `false` for an indeterminate process.
17550 * @param {number|boolean} progress Progress percent or `false` for indeterminate
17552 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
17553 this.progress
= progress
;
17555 if ( progress
!== false ) {
17556 this.$bar
.css( 'width', this.progress
+ '%' );
17557 this.$element
.attr( 'aria-valuenow', this.progress
);
17559 this.$bar
.css( 'width', '' );
17560 this.$element
.removeAttr( 'aria-valuenow' );
17562 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress
);
17566 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
17567 * and a menu of search results, which is displayed beneath the query
17568 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
17569 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
17570 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
17572 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
17573 * the [OOjs UI demos][1] for an example.
17575 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
17578 * @extends OO.ui.Widget
17581 * @param {Object} [config] Configuration options
17582 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
17583 * @cfg {string} [value] Initial query value
17585 OO
.ui
.SearchWidget
= function OoUiSearchWidget( config
) {
17586 // Configuration initialization
17587 config
= config
|| {};
17589 // Parent constructor
17590 OO
.ui
.SearchWidget
.parent
.call( this, config
);
17593 this.query
= new OO
.ui
.TextInputWidget( {
17595 placeholder
: config
.placeholder
,
17596 value
: config
.value
17598 this.results
= new OO
.ui
.SelectWidget();
17599 this.$query
= $( '<div>' );
17600 this.$results
= $( '<div>' );
17603 this.query
.connect( this, {
17604 change
: 'onQueryChange',
17605 enter
: 'onQueryEnter'
17607 this.query
.$input
.on( 'keydown', this.onQueryKeydown
.bind( this ) );
17611 .addClass( 'oo-ui-searchWidget-query' )
17612 .append( this.query
.$element
);
17614 .addClass( 'oo-ui-searchWidget-results' )
17615 .append( this.results
.$element
);
17617 .addClass( 'oo-ui-searchWidget' )
17618 .append( this.$results
, this.$query
);
17623 OO
.inheritClass( OO
.ui
.SearchWidget
, OO
.ui
.Widget
);
17628 * Handle query key down events.
17631 * @param {jQuery.Event} e Key down event
17633 OO
.ui
.SearchWidget
.prototype.onQueryKeydown = function ( e
) {
17634 var highlightedItem
, nextItem
,
17635 dir
= e
.which
=== OO
.ui
.Keys
.DOWN
? 1 : ( e
.which
=== OO
.ui
.Keys
.UP
? -1 : 0 );
17638 highlightedItem
= this.results
.getHighlightedItem();
17639 if ( !highlightedItem
) {
17640 highlightedItem
= this.results
.getSelectedItem();
17642 nextItem
= this.results
.getRelativeSelectableItem( highlightedItem
, dir
);
17643 this.results
.highlightItem( nextItem
);
17644 nextItem
.scrollElementIntoView();
17649 * Handle select widget select events.
17651 * Clears existing results. Subclasses should repopulate items according to new query.
17654 * @param {string} value New value
17656 OO
.ui
.SearchWidget
.prototype.onQueryChange = function () {
17658 this.results
.clearItems();
17662 * Handle select widget enter key events.
17664 * Chooses highlighted item.
17667 * @param {string} value New value
17669 OO
.ui
.SearchWidget
.prototype.onQueryEnter = function () {
17670 var highlightedItem
= this.results
.getHighlightedItem();
17671 if ( highlightedItem
) {
17672 this.results
.chooseItem( highlightedItem
);
17677 * Get the query input.
17679 * @return {OO.ui.TextInputWidget} Query input
17681 OO
.ui
.SearchWidget
.prototype.getQuery = function () {
17686 * Get the search results menu.
17688 * @return {OO.ui.SelectWidget} Menu of search results
17690 OO
.ui
.SearchWidget
.prototype.getResults = function () {
17691 return this.results
;
17695 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
17696 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
17697 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
17700 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
17701 * information, please see the [OOjs UI documentation on MediaWiki][1].
17704 * // Example of a select widget with three options
17705 * var select = new OO.ui.SelectWidget( {
17707 * new OO.ui.OptionWidget( {
17709 * label: 'Option One',
17711 * new OO.ui.OptionWidget( {
17713 * label: 'Option Two',
17715 * new OO.ui.OptionWidget( {
17717 * label: 'Option Three',
17721 * $( 'body' ).append( select.$element );
17723 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17727 * @extends OO.ui.Widget
17728 * @mixins OO.ui.mixin.GroupWidget
17731 * @param {Object} [config] Configuration options
17732 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
17733 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
17734 * the [OOjs UI documentation on MediaWiki] [2] for examples.
17735 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17737 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
17738 // Configuration initialization
17739 config
= config
|| {};
17741 // Parent constructor
17742 OO
.ui
.SelectWidget
.parent
.call( this, config
);
17744 // Mixin constructors
17745 OO
.ui
.mixin
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
17748 this.pressed
= false;
17749 this.selecting
= null;
17750 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
17751 this.onMouseMoveHandler
= this.onMouseMove
.bind( this );
17752 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
17753 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
17754 this.keyPressBuffer
= '';
17755 this.keyPressBufferTimer
= null;
17758 this.connect( this, {
17761 this.$element
.on( {
17762 mousedown
: this.onMouseDown
.bind( this ),
17763 mouseover
: this.onMouseOver
.bind( this ),
17764 mouseleave
: this.onMouseLeave
.bind( this )
17769 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
17770 .attr( 'role', 'listbox' );
17771 if ( Array
.isArray( config
.items
) ) {
17772 this.addItems( config
.items
);
17778 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
17780 // Need to mixin base class as well
17781 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupElement
);
17782 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupWidget
);
17785 OO
.ui
.SelectWidget
.static.passAllFilter = function () {
17794 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
17796 * @param {OO.ui.OptionWidget|null} item Highlighted item
17802 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
17803 * pressed state of an option.
17805 * @param {OO.ui.OptionWidget|null} item Pressed item
17811 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
17813 * @param {OO.ui.OptionWidget|null} item Selected item
17818 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
17819 * @param {OO.ui.OptionWidget} item Chosen item
17825 * An `add` event is emitted when options are added to the select with the #addItems method.
17827 * @param {OO.ui.OptionWidget[]} items Added items
17828 * @param {number} index Index of insertion point
17834 * A `remove` event is emitted when options are removed from the select with the #clearItems
17835 * or #removeItems methods.
17837 * @param {OO.ui.OptionWidget[]} items Removed items
17843 * Handle mouse down events.
17846 * @param {jQuery.Event} e Mouse down event
17848 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
17851 if ( !this.isDisabled() && e
.which
=== 1 ) {
17852 this.togglePressed( true );
17853 item
= this.getTargetItem( e
);
17854 if ( item
&& item
.isSelectable() ) {
17855 this.pressItem( item
);
17856 this.selecting
= item
;
17857 OO
.ui
.addCaptureEventListener(
17858 this.getElementDocument(),
17860 this.onMouseUpHandler
17862 OO
.ui
.addCaptureEventListener(
17863 this.getElementDocument(),
17865 this.onMouseMoveHandler
17873 * Handle mouse up events.
17876 * @param {jQuery.Event} e Mouse up event
17878 OO
.ui
.SelectWidget
.prototype.onMouseUp = function ( e
) {
17881 this.togglePressed( false );
17882 if ( !this.selecting
) {
17883 item
= this.getTargetItem( e
);
17884 if ( item
&& item
.isSelectable() ) {
17885 this.selecting
= item
;
17888 if ( !this.isDisabled() && e
.which
=== 1 && this.selecting
) {
17889 this.pressItem( null );
17890 this.chooseItem( this.selecting
);
17891 this.selecting
= null;
17894 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup',
17895 this.onMouseUpHandler
);
17896 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mousemove',
17897 this.onMouseMoveHandler
);
17903 * Handle mouse move events.
17906 * @param {jQuery.Event} e Mouse move event
17908 OO
.ui
.SelectWidget
.prototype.onMouseMove = function ( e
) {
17911 if ( !this.isDisabled() && this.pressed
) {
17912 item
= this.getTargetItem( e
);
17913 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
17914 this.pressItem( item
);
17915 this.selecting
= item
;
17922 * Handle mouse over events.
17925 * @param {jQuery.Event} e Mouse over event
17927 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
17930 if ( !this.isDisabled() ) {
17931 item
= this.getTargetItem( e
);
17932 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
17938 * Handle mouse leave events.
17941 * @param {jQuery.Event} e Mouse over event
17943 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
17944 if ( !this.isDisabled() ) {
17945 this.highlightItem( null );
17951 * Handle key down events.
17954 * @param {jQuery.Event} e Key down event
17956 OO
.ui
.SelectWidget
.prototype.onKeyDown = function ( e
) {
17959 currentItem
= this.getHighlightedItem() || this.getSelectedItem();
17961 if ( !this.isDisabled() && this.isVisible() ) {
17962 switch ( e
.keyCode
) {
17963 case OO
.ui
.Keys
.ENTER
:
17964 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
17965 // Was only highlighted, now let's select it. No-op if already selected.
17966 this.chooseItem( currentItem
);
17970 case OO
.ui
.Keys
.UP
:
17971 case OO
.ui
.Keys
.LEFT
:
17972 this.clearKeyPressBuffer();
17973 nextItem
= this.getRelativeSelectableItem( currentItem
, -1 );
17976 case OO
.ui
.Keys
.DOWN
:
17977 case OO
.ui
.Keys
.RIGHT
:
17978 this.clearKeyPressBuffer();
17979 nextItem
= this.getRelativeSelectableItem( currentItem
, 1 );
17982 case OO
.ui
.Keys
.ESCAPE
:
17983 case OO
.ui
.Keys
.TAB
:
17984 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
17985 currentItem
.setHighlighted( false );
17987 this.unbindKeyDownListener();
17988 this.unbindKeyPressListener();
17989 // Don't prevent tabbing away / defocusing
17995 if ( nextItem
.constructor.static.highlightable
) {
17996 this.highlightItem( nextItem
);
17998 this.chooseItem( nextItem
);
18000 nextItem
.scrollElementIntoView();
18004 // Can't just return false, because e is not always a jQuery event
18005 e
.preventDefault();
18006 e
.stopPropagation();
18012 * Bind key down listener.
18016 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
18017 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler
);
18021 * Unbind key down listener.
18025 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
18026 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler
);
18030 * Clear the key-press buffer
18034 OO
.ui
.SelectWidget
.prototype.clearKeyPressBuffer = function () {
18035 if ( this.keyPressBufferTimer
) {
18036 clearTimeout( this.keyPressBufferTimer
);
18037 this.keyPressBufferTimer
= null;
18039 this.keyPressBuffer
= '';
18043 * Handle key press events.
18046 * @param {jQuery.Event} e Key press event
18048 OO
.ui
.SelectWidget
.prototype.onKeyPress = function ( e
) {
18049 var c
, filter
, item
;
18051 if ( !e
.charCode
) {
18052 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.keyPressBuffer
!== '' ) {
18053 this.keyPressBuffer
= this.keyPressBuffer
.substr( 0, this.keyPressBuffer
.length
- 1 );
18058 if ( String
.fromCodePoint
) {
18059 c
= String
.fromCodePoint( e
.charCode
);
18061 c
= String
.fromCharCode( e
.charCode
);
18064 if ( this.keyPressBufferTimer
) {
18065 clearTimeout( this.keyPressBufferTimer
);
18067 this.keyPressBufferTimer
= setTimeout( this.clearKeyPressBuffer
.bind( this ), 1500 );
18069 item
= this.getHighlightedItem() || this.getSelectedItem();
18071 if ( this.keyPressBuffer
=== c
) {
18072 // Common (if weird) special case: typing "xxxx" will cycle through all
18073 // the items beginning with "x".
18075 item
= this.getRelativeSelectableItem( item
, 1 );
18078 this.keyPressBuffer
+= c
;
18081 filter
= this.getItemMatcher( this.keyPressBuffer
, false );
18082 if ( !item
|| !filter( item
) ) {
18083 item
= this.getRelativeSelectableItem( item
, 1, filter
);
18086 if ( item
.constructor.static.highlightable
) {
18087 this.highlightItem( item
);
18089 this.chooseItem( item
);
18091 item
.scrollElementIntoView();
18098 * Get a matcher for the specific string
18101 * @param {string} s String to match against items
18102 * @param {boolean} [exact=false] Only accept exact matches
18103 * @return {Function} function ( OO.ui.OptionItem ) => boolean
18105 OO
.ui
.SelectWidget
.prototype.getItemMatcher = function ( s
, exact
) {
18108 if ( s
.normalize
) {
18111 s
= exact
? s
.trim() : s
.replace( /^\s+/, '' );
18112 re
= '^\\s*' + s
.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
18116 re
= new RegExp( re
, 'i' );
18117 return function ( item
) {
18118 var l
= item
.getLabel();
18119 if ( typeof l
!== 'string' ) {
18120 l
= item
.$label
.text();
18122 if ( l
.normalize
) {
18125 return re
.test( l
);
18130 * Bind key press listener.
18134 OO
.ui
.SelectWidget
.prototype.bindKeyPressListener = function () {
18135 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler
);
18139 * Unbind key down listener.
18141 * If you override this, be sure to call this.clearKeyPressBuffer() from your
18146 OO
.ui
.SelectWidget
.prototype.unbindKeyPressListener = function () {
18147 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler
);
18148 this.clearKeyPressBuffer();
18152 * Visibility change handler
18155 * @param {boolean} visible
18157 OO
.ui
.SelectWidget
.prototype.onToggle = function ( visible
) {
18159 this.clearKeyPressBuffer();
18164 * Get the closest item to a jQuery.Event.
18167 * @param {jQuery.Event} e
18168 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
18170 OO
.ui
.SelectWidget
.prototype.getTargetItem = function ( e
) {
18171 return $( e
.target
).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
18175 * Get selected item.
18177 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
18179 OO
.ui
.SelectWidget
.prototype.getSelectedItem = function () {
18182 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18183 if ( this.items
[ i
].isSelected() ) {
18184 return this.items
[ i
];
18191 * Get highlighted item.
18193 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
18195 OO
.ui
.SelectWidget
.prototype.getHighlightedItem = function () {
18198 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18199 if ( this.items
[ i
].isHighlighted() ) {
18200 return this.items
[ i
];
18207 * Toggle pressed state.
18209 * Press is a state that occurs when a user mouses down on an item, but
18210 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
18211 * until the user releases the mouse.
18213 * @param {boolean} pressed An option is being pressed
18215 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
18216 if ( pressed
=== undefined ) {
18217 pressed
= !this.pressed
;
18219 if ( pressed
!== this.pressed
) {
18221 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
18222 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
18223 this.pressed
= pressed
;
18228 * Highlight an option. If the `item` param is omitted, no options will be highlighted
18229 * and any existing highlight will be removed. The highlight is mutually exclusive.
18231 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
18235 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
18236 var i
, len
, highlighted
,
18239 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18240 highlighted
= this.items
[ i
] === item
;
18241 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
18242 this.items
[ i
].setHighlighted( highlighted
);
18247 this.emit( 'highlight', item
);
18254 * Fetch an item by its label.
18256 * @param {string} label Label of the item to select.
18257 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18258 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
18260 OO
.ui
.SelectWidget
.prototype.getItemFromLabel = function ( label
, prefix
) {
18261 var i
, item
, found
,
18262 len
= this.items
.length
,
18263 filter
= this.getItemMatcher( label
, true );
18265 for ( i
= 0; i
< len
; i
++ ) {
18266 item
= this.items
[ i
];
18267 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
18274 filter
= this.getItemMatcher( label
, false );
18275 for ( i
= 0; i
< len
; i
++ ) {
18276 item
= this.items
[ i
];
18277 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
18293 * Programmatically select an option by its label. If the item does not exist,
18294 * all options will be deselected.
18296 * @param {string} [label] Label of the item to select.
18297 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18301 OO
.ui
.SelectWidget
.prototype.selectItemByLabel = function ( label
, prefix
) {
18302 var itemFromLabel
= this.getItemFromLabel( label
, !!prefix
);
18303 if ( label
=== undefined || !itemFromLabel
) {
18304 return this.selectItem();
18306 return this.selectItem( itemFromLabel
);
18310 * Programmatically select an option by its data. If the `data` parameter is omitted,
18311 * or if the item does not exist, all options will be deselected.
18313 * @param {Object|string} [data] Value of the item to select, omit to deselect all
18317 OO
.ui
.SelectWidget
.prototype.selectItemByData = function ( data
) {
18318 var itemFromData
= this.getItemFromData( data
);
18319 if ( data
=== undefined || !itemFromData
) {
18320 return this.selectItem();
18322 return this.selectItem( itemFromData
);
18326 * Programmatically select an option by its reference. If the `item` parameter is omitted,
18327 * all options will be deselected.
18329 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
18333 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
18334 var i
, len
, selected
,
18337 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18338 selected
= this.items
[ i
] === item
;
18339 if ( this.items
[ i
].isSelected() !== selected
) {
18340 this.items
[ i
].setSelected( selected
);
18345 this.emit( 'select', item
);
18354 * Press is a state that occurs when a user mouses down on an item, but has not
18355 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
18356 * releases the mouse.
18358 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
18362 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
18363 var i
, len
, pressed
,
18366 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18367 pressed
= this.items
[ i
] === item
;
18368 if ( this.items
[ i
].isPressed() !== pressed
) {
18369 this.items
[ i
].setPressed( pressed
);
18374 this.emit( 'press', item
);
18383 * Note that ‘choose’ should never be modified programmatically. A user can choose
18384 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
18385 * use the #selectItem method.
18387 * This method is identical to #selectItem, but may vary in subclasses that take additional action
18388 * when users choose an item with the keyboard or mouse.
18390 * @param {OO.ui.OptionWidget} item Item to choose
18394 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
18396 this.selectItem( item
);
18397 this.emit( 'choose', item
);
18404 * Get an option by its position relative to the specified item (or to the start of the option array,
18405 * if item is `null`). The direction in which to search through the option array is specified with a
18406 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
18407 * `null` if there are no options in the array.
18409 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
18410 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
18411 * @param {Function} filter Only consider items for which this function returns
18412 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
18413 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
18415 OO
.ui
.SelectWidget
.prototype.getRelativeSelectableItem = function ( item
, direction
, filter
) {
18416 var currentIndex
, nextIndex
, i
,
18417 increase
= direction
> 0 ? 1 : -1,
18418 len
= this.items
.length
;
18420 if ( !$.isFunction( filter
) ) {
18421 filter
= OO
.ui
.SelectWidget
.static.passAllFilter
;
18424 if ( item
instanceof OO
.ui
.OptionWidget
) {
18425 currentIndex
= this.items
.indexOf( item
);
18426 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
18428 // If no item is selected and moving forward, start at the beginning.
18429 // If moving backward, start at the end.
18430 nextIndex
= direction
> 0 ? 0 : len
- 1;
18433 for ( i
= 0; i
< len
; i
++ ) {
18434 item
= this.items
[ nextIndex
];
18435 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
18438 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
18444 * Get the next selectable item or `null` if there are no selectable items.
18445 * Disabled options and menu-section markers and breaks are not selectable.
18447 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
18449 OO
.ui
.SelectWidget
.prototype.getFirstSelectableItem = function () {
18452 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18453 item
= this.items
[ i
];
18454 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() ) {
18463 * Add an array of options to the select. Optionally, an index number can be used to
18464 * specify an insertion point.
18466 * @param {OO.ui.OptionWidget[]} items Items to add
18467 * @param {number} [index] Index to insert items after
18471 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
18473 OO
.ui
.mixin
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
18475 // Always provide an index, even if it was omitted
18476 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
18482 * Remove the specified array of options from the select. Options will be detached
18483 * from the DOM, not removed, so they can be reused later. To remove all options from
18484 * the select, you may wish to use the #clearItems method instead.
18486 * @param {OO.ui.OptionWidget[]} items Items to remove
18490 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
18493 // Deselect items being removed
18494 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
18496 if ( item
.isSelected() ) {
18497 this.selectItem( null );
18502 OO
.ui
.mixin
.GroupWidget
.prototype.removeItems
.call( this, items
);
18504 this.emit( 'remove', items
);
18510 * Clear all options from the select. Options will be detached from the DOM, not removed,
18511 * so that they can be reused later. To remove a subset of options from the select, use
18512 * the #removeItems method.
18517 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
18518 var items
= this.items
.slice();
18521 OO
.ui
.mixin
.GroupWidget
.prototype.clearItems
.call( this );
18524 this.selectItem( null );
18526 this.emit( 'remove', items
);
18532 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
18533 * button options and is used together with
18534 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
18535 * highlighting, choosing, and selecting mutually exclusive options. Please see
18536 * the [OOjs UI documentation on MediaWiki] [1] for more information.
18539 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
18540 * var option1 = new OO.ui.ButtonOptionWidget( {
18542 * label: 'Option 1',
18543 * title: 'Button option 1'
18546 * var option2 = new OO.ui.ButtonOptionWidget( {
18548 * label: 'Option 2',
18549 * title: 'Button option 2'
18552 * var option3 = new OO.ui.ButtonOptionWidget( {
18554 * label: 'Option 3',
18555 * title: 'Button option 3'
18558 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
18559 * items: [ option1, option2, option3 ]
18561 * $( 'body' ).append( buttonSelect.$element );
18563 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18566 * @extends OO.ui.SelectWidget
18567 * @mixins OO.ui.mixin.TabIndexedElement
18570 * @param {Object} [config] Configuration options
18572 OO
.ui
.ButtonSelectWidget
= function OoUiButtonSelectWidget( config
) {
18573 // Parent constructor
18574 OO
.ui
.ButtonSelectWidget
.parent
.call( this, config
);
18576 // Mixin constructors
18577 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
18580 this.$element
.on( {
18581 focus
: this.bindKeyDownListener
.bind( this ),
18582 blur
: this.unbindKeyDownListener
.bind( this )
18586 this.$element
.addClass( 'oo-ui-buttonSelectWidget' );
18591 OO
.inheritClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.SelectWidget
);
18592 OO
.mixinClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
18595 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
18596 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
18597 * an interface for adding, removing and selecting options.
18598 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18600 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
18601 * OO.ui.RadioSelectInputWidget instead.
18604 * // A RadioSelectWidget with RadioOptions.
18605 * var option1 = new OO.ui.RadioOptionWidget( {
18607 * label: 'Selected radio option'
18610 * var option2 = new OO.ui.RadioOptionWidget( {
18612 * label: 'Unselected radio option'
18615 * var radioSelect=new OO.ui.RadioSelectWidget( {
18616 * items: [ option1, option2 ]
18619 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
18620 * radioSelect.selectItem( option1 );
18622 * $( 'body' ).append( radioSelect.$element );
18624 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18628 * @extends OO.ui.SelectWidget
18629 * @mixins OO.ui.mixin.TabIndexedElement
18632 * @param {Object} [config] Configuration options
18634 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
18635 // Parent constructor
18636 OO
.ui
.RadioSelectWidget
.parent
.call( this, config
);
18638 // Mixin constructors
18639 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
18642 this.$element
.on( {
18643 focus
: this.bindKeyDownListener
.bind( this ),
18644 blur
: this.unbindKeyDownListener
.bind( this )
18649 .addClass( 'oo-ui-radioSelectWidget' )
18650 .attr( 'role', 'radiogroup' );
18655 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
18656 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
18659 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
18660 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
18661 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxWidget ComboBoxWidget},
18662 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
18663 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
18664 * and customized to be opened, closed, and displayed as needed.
18666 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
18667 * mouse outside the menu.
18669 * Menus also have support for keyboard interaction:
18671 * - Enter/Return key: choose and select a menu option
18672 * - Up-arrow key: highlight the previous menu option
18673 * - Down-arrow key: highlight the next menu option
18674 * - Esc key: hide the menu
18676 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18677 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18680 * @extends OO.ui.SelectWidget
18681 * @mixins OO.ui.mixin.ClippableElement
18684 * @param {Object} [config] Configuration options
18685 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
18686 * the text the user types. This config is used by {@link OO.ui.ComboBoxWidget ComboBoxWidget}
18687 * and {@link OO.ui.mixin.LookupElement LookupElement}
18688 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
18689 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiSelectWidget CapsuleMultiSelectWidget}
18690 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
18691 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
18692 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
18693 * that button, unless the button (or its parent widget) is passed in here.
18694 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
18695 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
18697 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
18698 // Configuration initialization
18699 config
= config
|| {};
18701 // Parent constructor
18702 OO
.ui
.MenuSelectWidget
.parent
.call( this, config
);
18704 // Mixin constructors
18705 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
18708 this.newItems
= null;
18709 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
18710 this.filterFromInput
= !!config
.filterFromInput
;
18711 this.$input
= config
.$input
? config
.$input
: config
.input
? config
.input
.$input
: null;
18712 this.$widget
= config
.widget
? config
.widget
.$element
: null;
18713 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
18714 this.onInputEditHandler
= OO
.ui
.debounce( this.updateItemVisibility
.bind( this ), 100 );
18718 .addClass( 'oo-ui-menuSelectWidget' )
18719 .attr( 'role', 'menu' );
18721 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
18722 // that reference properties not initialized at that time of parent class construction
18723 // TODO: Find a better way to handle post-constructor setup
18724 this.visible
= false;
18725 this.$element
.addClass( 'oo-ui-element-hidden' );
18730 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
18731 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.ClippableElement
);
18736 * Handles document mouse down events.
18739 * @param {jQuery.Event} e Key down event
18741 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
18743 !OO
.ui
.contains( this.$element
[ 0 ], e
.target
, true ) &&
18744 ( !this.$widget
|| !OO
.ui
.contains( this.$widget
[ 0 ], e
.target
, true ) )
18746 this.toggle( false );
18753 OO
.ui
.MenuSelectWidget
.prototype.onKeyDown = function ( e
) {
18754 var currentItem
= this.getHighlightedItem() || this.getSelectedItem();
18756 if ( !this.isDisabled() && this.isVisible() ) {
18757 switch ( e
.keyCode
) {
18758 case OO
.ui
.Keys
.LEFT
:
18759 case OO
.ui
.Keys
.RIGHT
:
18760 // Do nothing if a text field is associated, arrow keys will be handled natively
18761 if ( !this.$input
) {
18762 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
18765 case OO
.ui
.Keys
.ESCAPE
:
18766 case OO
.ui
.Keys
.TAB
:
18767 if ( currentItem
) {
18768 currentItem
.setHighlighted( false );
18770 this.toggle( false );
18771 // Don't prevent tabbing away, prevent defocusing
18772 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
18773 e
.preventDefault();
18774 e
.stopPropagation();
18778 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
18785 * Update menu item visibility after input changes.
18788 OO
.ui
.MenuSelectWidget
.prototype.updateItemVisibility = function () {
18790 len
= this.items
.length
,
18791 showAll
= !this.isVisible(),
18792 filter
= showAll
? null : this.getItemMatcher( this.$input
.val() );
18794 for ( i
= 0; i
< len
; i
++ ) {
18795 item
= this.items
[ i
];
18796 if ( item
instanceof OO
.ui
.OptionWidget
) {
18797 item
.toggle( showAll
|| filter( item
) );
18801 // Reevaluate clipping
18808 OO
.ui
.MenuSelectWidget
.prototype.bindKeyDownListener = function () {
18809 if ( this.$input
) {
18810 this.$input
.on( 'keydown', this.onKeyDownHandler
);
18812 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyDownListener
.call( this );
18819 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyDownListener = function () {
18820 if ( this.$input
) {
18821 this.$input
.off( 'keydown', this.onKeyDownHandler
);
18823 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyDownListener
.call( this );
18830 OO
.ui
.MenuSelectWidget
.prototype.bindKeyPressListener = function () {
18831 if ( this.$input
) {
18832 if ( this.filterFromInput
) {
18833 this.$input
.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
18836 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyPressListener
.call( this );
18843 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyPressListener = function () {
18844 if ( this.$input
) {
18845 if ( this.filterFromInput
) {
18846 this.$input
.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
18847 this.updateItemVisibility();
18850 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyPressListener
.call( this );
18857 * When a user chooses an item, the menu is closed.
18859 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
18860 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
18861 * @param {OO.ui.OptionWidget} item Item to choose
18864 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
18865 OO
.ui
.MenuSelectWidget
.parent
.prototype.chooseItem
.call( this, item
);
18866 this.toggle( false );
18873 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
18877 OO
.ui
.MenuSelectWidget
.parent
.prototype.addItems
.call( this, items
, index
);
18880 if ( !this.newItems
) {
18881 this.newItems
= [];
18884 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
18886 if ( this.isVisible() ) {
18887 // Defer fitting label until item has been attached
18890 this.newItems
.push( item
);
18894 // Reevaluate clipping
18903 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
18905 OO
.ui
.MenuSelectWidget
.parent
.prototype.removeItems
.call( this, items
);
18907 // Reevaluate clipping
18916 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
18918 OO
.ui
.MenuSelectWidget
.parent
.prototype.clearItems
.call( this );
18920 // Reevaluate clipping
18929 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
18930 var i
, len
, change
;
18932 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
18933 change
= visible
!== this.isVisible();
18936 OO
.ui
.MenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
18940 this.bindKeyDownListener();
18941 this.bindKeyPressListener();
18943 if ( this.newItems
&& this.newItems
.length
) {
18944 for ( i
= 0, len
= this.newItems
.length
; i
< len
; i
++ ) {
18945 this.newItems
[ i
].fitLabel();
18947 this.newItems
= null;
18949 this.toggleClipping( true );
18952 if ( this.autoHide
) {
18953 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler
);
18956 this.unbindKeyDownListener();
18957 this.unbindKeyPressListener();
18958 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler
);
18959 this.toggleClipping( false );
18967 * FloatingMenuSelectWidget is a menu that will stick under a specified
18968 * container, even when it is inserted elsewhere in the document (for example,
18969 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
18970 * menu from being clipped too aggresively.
18972 * The menu's position is automatically calculated and maintained when the menu
18973 * is toggled or the window is resized.
18975 * See OO.ui.ComboBoxWidget for an example of a widget that uses this class.
18978 * @extends OO.ui.MenuSelectWidget
18979 * @mixins OO.ui.mixin.FloatableElement
18982 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
18983 * Deprecated, omit this parameter and specify `$container` instead.
18984 * @param {Object} [config] Configuration options
18985 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
18987 OO
.ui
.FloatingMenuSelectWidget
= function OoUiFloatingMenuSelectWidget( inputWidget
, config
) {
18988 // Allow 'inputWidget' parameter and config for backwards compatibility
18989 if ( OO
.isPlainObject( inputWidget
) && config
=== undefined ) {
18990 config
= inputWidget
;
18991 inputWidget
= config
.inputWidget
;
18994 // Configuration initialization
18995 config
= config
|| {};
18997 // Parent constructor
18998 OO
.ui
.FloatingMenuSelectWidget
.parent
.call( this, config
);
19000 // Properties (must be set before mixin constructors)
19001 this.inputWidget
= inputWidget
; // For backwards compatibility
19002 this.$container
= config
.$container
|| this.inputWidget
.$element
;
19004 // Mixins constructors
19005 OO
.ui
.mixin
.FloatableElement
.call( this, $.extend( {}, config
, { $floatableContainer
: this.$container
} ) );
19008 this.$element
.addClass( 'oo-ui-floatingMenuSelectWidget' );
19009 // For backwards compatibility
19010 this.$element
.addClass( 'oo-ui-textInputMenuSelectWidget' );
19015 OO
.inheritClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.MenuSelectWidget
);
19016 OO
.mixinClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.mixin
.FloatableElement
);
19018 // For backwards compatibility
19019 OO
.ui
.TextInputMenuSelectWidget
= OO
.ui
.FloatingMenuSelectWidget
;
19026 OO
.ui
.FloatingMenuSelectWidget
.prototype.toggle = function ( visible
) {
19028 visible
= visible
=== undefined ? !this.isVisible() : !!visible
;
19029 change
= visible
!== this.isVisible();
19031 if ( change
&& visible
) {
19032 // Make sure the width is set before the parent method runs.
19033 this.setIdealSize( this.$container
.width() );
19037 // This will call this.clip(), which is nonsensical since we're not positioned yet...
19038 OO
.ui
.FloatingMenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
19041 this.togglePositioning( this.isVisible() );
19048 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
19049 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
19051 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
19054 * @extends OO.ui.SelectWidget
19055 * @mixins OO.ui.mixin.TabIndexedElement
19058 * @param {Object} [config] Configuration options
19060 OO
.ui
.OutlineSelectWidget
= function OoUiOutlineSelectWidget( config
) {
19061 // Parent constructor
19062 OO
.ui
.OutlineSelectWidget
.parent
.call( this, config
);
19064 // Mixin constructors
19065 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
19068 this.$element
.on( {
19069 focus
: this.bindKeyDownListener
.bind( this ),
19070 blur
: this.unbindKeyDownListener
.bind( this )
19074 this.$element
.addClass( 'oo-ui-outlineSelectWidget' );
19079 OO
.inheritClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.SelectWidget
);
19080 OO
.mixinClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
19083 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
19085 * **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.**
19088 * @extends OO.ui.SelectWidget
19089 * @mixins OO.ui.mixin.TabIndexedElement
19092 * @param {Object} [config] Configuration options
19094 OO
.ui
.TabSelectWidget
= function OoUiTabSelectWidget( config
) {
19095 // Parent constructor
19096 OO
.ui
.TabSelectWidget
.parent
.call( this, config
);
19098 // Mixin constructors
19099 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
19102 this.$element
.on( {
19103 focus
: this.bindKeyDownListener
.bind( this ),
19104 blur
: this.unbindKeyDownListener
.bind( this )
19108 this.$element
.addClass( 'oo-ui-tabSelectWidget' );
19113 OO
.inheritClass( OO
.ui
.TabSelectWidget
, OO
.ui
.SelectWidget
);
19114 OO
.mixinClass( OO
.ui
.TabSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
19117 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
19118 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
19119 * (to adjust the value in increments) to allow the user to enter a number.
19122 * // Example: A NumberInputWidget.
19123 * var numberInput = new OO.ui.NumberInputWidget( {
19124 * label: 'NumberInputWidget',
19125 * input: { value: 5, min: 1, max: 10 }
19127 * $( 'body' ).append( numberInput.$element );
19130 * @extends OO.ui.Widget
19133 * @param {Object} [config] Configuration options
19134 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
19135 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
19136 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
19137 * @cfg {boolean} [isInteger=false] Whether the field accepts only integer values.
19138 * @cfg {number} [min=-Infinity] Minimum allowed value
19139 * @cfg {number} [max=Infinity] Maximum allowed value
19140 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
19141 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
19143 OO
.ui
.NumberInputWidget
= function OoUiNumberInputWidget( config
) {
19144 // Configuration initialization
19145 config
= $.extend( {
19153 // Parent constructor
19154 OO
.ui
.NumberInputWidget
.parent
.call( this, config
);
19157 this.input
= new OO
.ui
.TextInputWidget( $.extend(
19159 disabled
: this.isDisabled()
19163 this.minusButton
= new OO
.ui
.ButtonWidget( $.extend(
19165 disabled
: this.isDisabled(),
19168 config
.minusButton
,
19170 classes
: [ 'oo-ui-numberInputWidget-minusButton' ],
19174 this.plusButton
= new OO
.ui
.ButtonWidget( $.extend(
19176 disabled
: this.isDisabled(),
19181 classes
: [ 'oo-ui-numberInputWidget-plusButton' ],
19187 this.input
.connect( this, {
19188 change
: this.emit
.bind( this, 'change' ),
19189 enter
: this.emit
.bind( this, 'enter' )
19191 this.input
.$input
.on( {
19192 keydown
: this.onKeyDown
.bind( this ),
19193 'wheel mousewheel DOMMouseScroll': this.onWheel
.bind( this )
19195 this.plusButton
.connect( this, {
19196 click
: [ 'onButtonClick', +1 ]
19198 this.minusButton
.connect( this, {
19199 click
: [ 'onButtonClick', -1 ]
19203 this.setIsInteger( !!config
.isInteger
);
19204 this.setRange( config
.min
, config
.max
);
19205 this.setStep( config
.step
, config
.pageStep
);
19207 this.$field
= $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' )
19209 this.minusButton
.$element
,
19210 this.input
.$element
,
19211 this.plusButton
.$element
19213 this.$element
.addClass( 'oo-ui-numberInputWidget' ).append( this.$field
);
19214 this.input
.setValidation( this.validateNumber
.bind( this ) );
19219 OO
.inheritClass( OO
.ui
.NumberInputWidget
, OO
.ui
.Widget
);
19224 * A `change` event is emitted when the value of the input changes.
19230 * An `enter` event is emitted when the user presses 'enter' inside the text box.
19238 * Set whether only integers are allowed
19239 * @param {boolean} flag
19241 OO
.ui
.NumberInputWidget
.prototype.setIsInteger = function ( flag
) {
19242 this.isInteger
= !!flag
;
19243 this.input
.setValidityFlag();
19247 * Get whether only integers are allowed
19248 * @return {boolean} Flag value
19250 OO
.ui
.NumberInputWidget
.prototype.getIsInteger = function () {
19251 return this.isInteger
;
19255 * Set the range of allowed values
19256 * @param {number} min Minimum allowed value
19257 * @param {number} max Maximum allowed value
19259 OO
.ui
.NumberInputWidget
.prototype.setRange = function ( min
, max
) {
19261 throw new Error( 'Minimum (' + min
+ ') must not be greater than maximum (' + max
+ ')' );
19265 this.input
.setValidityFlag();
19269 * Get the current range
19270 * @return {number[]} Minimum and maximum values
19272 OO
.ui
.NumberInputWidget
.prototype.getRange = function () {
19273 return [ this.min
, this.max
];
19277 * Set the stepping deltas
19278 * @param {number} step Normal step
19279 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
19281 OO
.ui
.NumberInputWidget
.prototype.setStep = function ( step
, pageStep
) {
19283 throw new Error( 'Step value must be positive' );
19285 if ( pageStep
=== null ) {
19286 pageStep
= step
* 10;
19287 } else if ( pageStep
<= 0 ) {
19288 throw new Error( 'Page step value must be positive' );
19291 this.pageStep
= pageStep
;
19295 * Get the current stepping values
19296 * @return {number[]} Step and page step
19298 OO
.ui
.NumberInputWidget
.prototype.getStep = function () {
19299 return [ this.step
, this.pageStep
];
19303 * Get the current value of the widget
19306 OO
.ui
.NumberInputWidget
.prototype.getValue = function () {
19307 return this.input
.getValue();
19311 * Get the current value of the widget as a number
19312 * @return {number} May be NaN, or an invalid number
19314 OO
.ui
.NumberInputWidget
.prototype.getNumericValue = function () {
19315 return +this.input
.getValue();
19319 * Set the value of the widget
19320 * @param {string} value Invalid values are allowed
19322 OO
.ui
.NumberInputWidget
.prototype.setValue = function ( value
) {
19323 this.input
.setValue( value
);
19327 * Adjust the value of the widget
19328 * @param {number} delta Adjustment amount
19330 OO
.ui
.NumberInputWidget
.prototype.adjustValue = function ( delta
) {
19331 var n
, v
= this.getNumericValue();
19334 if ( isNaN( delta
) || !isFinite( delta
) ) {
19335 throw new Error( 'Delta must be a finite number' );
19338 if ( isNaN( v
) ) {
19342 n
= Math
.max( Math
.min( n
, this.max
), this.min
);
19343 if ( this.isInteger
) {
19344 n
= Math
.round( n
);
19349 this.setValue( n
);
19356 * @param {string} value Field value
19357 * @return {boolean}
19359 OO
.ui
.NumberInputWidget
.prototype.validateNumber = function ( value
) {
19361 if ( isNaN( n
) || !isFinite( n
) ) {
19365 /*jshint bitwise: false */
19366 if ( this.isInteger
&& ( n
| 0 ) !== n
) {
19369 /*jshint bitwise: true */
19371 if ( n
< this.min
|| n
> this.max
) {
19379 * Handle mouse click events.
19382 * @param {number} dir +1 or -1
19384 OO
.ui
.NumberInputWidget
.prototype.onButtonClick = function ( dir
) {
19385 this.adjustValue( dir
* this.step
);
19389 * Handle mouse wheel events.
19392 * @param {jQuery.Event} event
19394 OO
.ui
.NumberInputWidget
.prototype.onWheel = function ( event
) {
19397 // Standard 'wheel' event
19398 if ( event
.originalEvent
.deltaMode
!== undefined ) {
19399 this.sawWheelEvent
= true;
19401 if ( event
.originalEvent
.deltaY
) {
19402 delta
= -event
.originalEvent
.deltaY
;
19403 } else if ( event
.originalEvent
.deltaX
) {
19404 delta
= event
.originalEvent
.deltaX
;
19407 // Non-standard events
19408 if ( !this.sawWheelEvent
) {
19409 if ( event
.originalEvent
.wheelDeltaX
) {
19410 delta
= -event
.originalEvent
.wheelDeltaX
;
19411 } else if ( event
.originalEvent
.wheelDeltaY
) {
19412 delta
= event
.originalEvent
.wheelDeltaY
;
19413 } else if ( event
.originalEvent
.wheelDelta
) {
19414 delta
= event
.originalEvent
.wheelDelta
;
19415 } else if ( event
.originalEvent
.detail
) {
19416 delta
= -event
.originalEvent
.detail
;
19421 delta
= delta
< 0 ? -1 : 1;
19422 this.adjustValue( delta
* this.step
);
19429 * Handle key down events.
19432 * @param {jQuery.Event} e Key down event
19434 OO
.ui
.NumberInputWidget
.prototype.onKeyDown = function ( e
) {
19435 if ( !this.isDisabled() ) {
19436 switch ( e
.which
) {
19437 case OO
.ui
.Keys
.UP
:
19438 this.adjustValue( this.step
);
19440 case OO
.ui
.Keys
.DOWN
:
19441 this.adjustValue( -this.step
);
19443 case OO
.ui
.Keys
.PAGEUP
:
19444 this.adjustValue( this.pageStep
);
19446 case OO
.ui
.Keys
.PAGEDOWN
:
19447 this.adjustValue( -this.pageStep
);
19456 OO
.ui
.NumberInputWidget
.prototype.setDisabled = function ( disabled
) {
19458 OO
.ui
.NumberInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
19460 if ( this.input
) {
19461 this.input
.setDisabled( this.isDisabled() );
19463 if ( this.minusButton
) {
19464 this.minusButton
.setDisabled( this.isDisabled() );
19466 if ( this.plusButton
) {
19467 this.plusButton
.setDisabled( this.isDisabled() );
19474 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
19475 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
19476 * visually by a slider in the leftmost position.
19479 * // Toggle switches in the 'off' and 'on' position.
19480 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
19481 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
19485 * // Create a FieldsetLayout to layout and label switches
19486 * var fieldset = new OO.ui.FieldsetLayout( {
19487 * label: 'Toggle switches'
19489 * fieldset.addItems( [
19490 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
19491 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
19493 * $( 'body' ).append( fieldset.$element );
19496 * @extends OO.ui.ToggleWidget
19497 * @mixins OO.ui.mixin.TabIndexedElement
19500 * @param {Object} [config] Configuration options
19501 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
19502 * By default, the toggle switch is in the 'off' position.
19504 OO
.ui
.ToggleSwitchWidget
= function OoUiToggleSwitchWidget( config
) {
19505 // Parent constructor
19506 OO
.ui
.ToggleSwitchWidget
.parent
.call( this, config
);
19508 // Mixin constructors
19509 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
19512 this.dragging
= false;
19513 this.dragStart
= null;
19514 this.sliding
= false;
19515 this.$glow
= $( '<span>' );
19516 this.$grip
= $( '<span>' );
19519 this.$element
.on( {
19520 click
: this.onClick
.bind( this ),
19521 keypress
: this.onKeyPress
.bind( this )
19525 this.$glow
.addClass( 'oo-ui-toggleSwitchWidget-glow' );
19526 this.$grip
.addClass( 'oo-ui-toggleSwitchWidget-grip' );
19528 .addClass( 'oo-ui-toggleSwitchWidget' )
19529 .attr( 'role', 'checkbox' )
19530 .append( this.$glow
, this.$grip
);
19535 OO
.inheritClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.ToggleWidget
);
19536 OO
.mixinClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.mixin
.TabIndexedElement
);
19541 * Handle mouse click events.
19544 * @param {jQuery.Event} e Mouse click event
19546 OO
.ui
.ToggleSwitchWidget
.prototype.onClick = function ( e
) {
19547 if ( !this.isDisabled() && e
.which
=== 1 ) {
19548 this.setValue( !this.value
);
19554 * Handle key press events.
19557 * @param {jQuery.Event} e Key press event
19559 OO
.ui
.ToggleSwitchWidget
.prototype.onKeyPress = function ( e
) {
19560 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
19561 this.setValue( !this.value
);
19567 * Deprecated aliases for classes in the `OO.ui.mixin` namespace.
19571 * @inheritdoc OO.ui.mixin.ButtonElement
19572 * @deprecated Use {@link OO.ui.mixin.ButtonElement} instead.
19574 OO
.ui
.ButtonElement
= OO
.ui
.mixin
.ButtonElement
;
19577 * @inheritdoc OO.ui.mixin.ClippableElement
19578 * @deprecated Use {@link OO.ui.mixin.ClippableElement} instead.
19580 OO
.ui
.ClippableElement
= OO
.ui
.mixin
.ClippableElement
;
19583 * @inheritdoc OO.ui.mixin.DraggableElement
19584 * @deprecated Use {@link OO.ui.mixin.DraggableElement} instead.
19586 OO
.ui
.DraggableElement
= OO
.ui
.mixin
.DraggableElement
;
19589 * @inheritdoc OO.ui.mixin.DraggableGroupElement
19590 * @deprecated Use {@link OO.ui.mixin.DraggableGroupElement} instead.
19592 OO
.ui
.DraggableGroupElement
= OO
.ui
.mixin
.DraggableGroupElement
;
19595 * @inheritdoc OO.ui.mixin.FlaggedElement
19596 * @deprecated Use {@link OO.ui.mixin.FlaggedElement} instead.
19598 OO
.ui
.FlaggedElement
= OO
.ui
.mixin
.FlaggedElement
;
19601 * @inheritdoc OO.ui.mixin.GroupElement
19602 * @deprecated Use {@link OO.ui.mixin.GroupElement} instead.
19604 OO
.ui
.GroupElement
= OO
.ui
.mixin
.GroupElement
;
19607 * @inheritdoc OO.ui.mixin.GroupWidget
19608 * @deprecated Use {@link OO.ui.mixin.GroupWidget} instead.
19610 OO
.ui
.GroupWidget
= OO
.ui
.mixin
.GroupWidget
;
19613 * @inheritdoc OO.ui.mixin.IconElement
19614 * @deprecated Use {@link OO.ui.mixin.IconElement} instead.
19616 OO
.ui
.IconElement
= OO
.ui
.mixin
.IconElement
;
19619 * @inheritdoc OO.ui.mixin.IndicatorElement
19620 * @deprecated Use {@link OO.ui.mixin.IndicatorElement} instead.
19622 OO
.ui
.IndicatorElement
= OO
.ui
.mixin
.IndicatorElement
;
19625 * @inheritdoc OO.ui.mixin.ItemWidget
19626 * @deprecated Use {@link OO.ui.mixin.ItemWidget} instead.
19628 OO
.ui
.ItemWidget
= OO
.ui
.mixin
.ItemWidget
;
19631 * @inheritdoc OO.ui.mixin.LabelElement
19632 * @deprecated Use {@link OO.ui.mixin.LabelElement} instead.
19634 OO
.ui
.LabelElement
= OO
.ui
.mixin
.LabelElement
;
19637 * @inheritdoc OO.ui.mixin.LookupElement
19638 * @deprecated Use {@link OO.ui.mixin.LookupElement} instead.
19640 OO
.ui
.LookupElement
= OO
.ui
.mixin
.LookupElement
;
19643 * @inheritdoc OO.ui.mixin.PendingElement
19644 * @deprecated Use {@link OO.ui.mixin.PendingElement} instead.
19646 OO
.ui
.PendingElement
= OO
.ui
.mixin
.PendingElement
;
19649 * @inheritdoc OO.ui.mixin.PopupElement
19650 * @deprecated Use {@link OO.ui.mixin.PopupElement} instead.
19652 OO
.ui
.PopupElement
= OO
.ui
.mixin
.PopupElement
;
19655 * @inheritdoc OO.ui.mixin.TabIndexedElement
19656 * @deprecated Use {@link OO.ui.mixin.TabIndexedElement} instead.
19658 OO
.ui
.TabIndexedElement
= OO
.ui
.mixin
.TabIndexedElement
;
19661 * @inheritdoc OO.ui.mixin.TitledElement
19662 * @deprecated Use {@link OO.ui.mixin.TitledElement} instead.
19664 OO
.ui
.TitledElement
= OO
.ui
.mixin
.TitledElement
;