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-22T20:09:51Z
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 this.$floatableWindow
.off( 'resize', this.onFloatableWindowResizeHandler
);
6937 this.$floatableWindow
= null;
6939 if ( this.$floatableClosestScrollable
) {
6940 this.$floatableClosestScrollable
.off( 'scroll', this.onFloatableScrollHandler
);
6941 this.$floatableClosestScrollable
= null;
6944 this.$floatable
.css( { left
: '', top
: '' } );
6952 * Position the floatable below its container.
6954 * This should only be done when both of them are attached to the DOM and visible.
6958 OO
.ui
.mixin
.FloatableElement
.prototype.position = function () {
6961 if ( !this.positioning
) {
6965 pos
= OO
.ui
.Element
.static.getRelativePosition( this.$floatableContainer
, this.$floatable
.offsetParent() );
6967 // Position under container
6968 pos
.top
+= this.$floatableContainer
.height();
6969 this.$floatable
.css( pos
);
6971 // We updated the position, so re-evaluate the clipping state.
6972 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
6973 // will not notice the need to update itself.)
6974 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
6975 // it not listen to the right events in the right places?
6984 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
6985 * Accesskeys allow an user to go to a specific element by using
6986 * a shortcut combination of a browser specific keys + the key
6990 * // AccessKeyedElement provides an 'accesskey' attribute to the
6991 * // ButtonWidget class
6992 * var button = new OO.ui.ButtonWidget( {
6993 * label: 'Button with Accesskey',
6996 * $( 'body' ).append( button.$element );
7002 * @param {Object} [config] Configuration options
7003 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
7004 * If this config is omitted, the accesskey functionality is applied to $element, the
7005 * element created by the class.
7006 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
7007 * this config is omitted, no accesskey will be added.
7009 OO
.ui
.mixin
.AccessKeyedElement
= function OoUiMixinAccessKeyedElement( config
) {
7010 // Configuration initialization
7011 config
= config
|| {};
7014 this.$accessKeyed
= null;
7015 this.accessKey
= null;
7018 this.setAccessKey( config
.accessKey
|| null );
7019 this.setAccessKeyedElement( config
.$accessKeyed
|| this.$element
);
7024 OO
.initClass( OO
.ui
.mixin
.AccessKeyedElement
);
7026 /* Static Properties */
7029 * The access key, a function that returns a key, or `null` for no accesskey.
7033 * @property {string|Function|null}
7035 OO
.ui
.mixin
.AccessKeyedElement
.static.accessKey
= null;
7040 * Set the accesskeyed element.
7042 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
7043 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
7045 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
7047 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKeyedElement = function ( $accessKeyed
) {
7048 if ( this.$accessKeyed
) {
7049 this.$accessKeyed
.removeAttr( 'accesskey' );
7052 this.$accessKeyed
= $accessKeyed
;
7053 if ( this.accessKey
) {
7054 this.$accessKeyed
.attr( 'accesskey', this.accessKey
);
7061 * @param {string|Function|null} accesskey Key, a function that returns a key, or `null` for no accesskey
7064 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKey = function ( accessKey
) {
7065 accessKey
= typeof accessKey
=== 'string' ? OO
.ui
.resolveMsg( accessKey
) : null;
7067 if ( this.accessKey
!== accessKey
) {
7068 if ( this.$accessKeyed
) {
7069 if ( accessKey
!== null ) {
7070 this.$accessKeyed
.attr( 'accesskey', accessKey
);
7072 this.$accessKeyed
.removeAttr( 'accesskey' );
7075 this.accessKey
= accessKey
;
7084 * @return {string} accessKey string
7086 OO
.ui
.mixin
.AccessKeyedElement
.prototype.getAccessKey = function () {
7087 return this.accessKey
;
7091 * Tools, together with {@link OO.ui.ToolGroup toolgroups}, constitute {@link OO.ui.Toolbar toolbars}.
7092 * Each tool is configured with a static name, title, and icon and is customized with the command to carry
7093 * out when the tool is selected. Tools must also be registered with a {@link OO.ui.ToolFactory tool factory},
7094 * which creates the tools on demand.
7096 * Tools are added to toolgroups ({@link OO.ui.ListToolGroup ListToolGroup},
7097 * {@link OO.ui.BarToolGroup BarToolGroup}, or {@link OO.ui.MenuToolGroup MenuToolGroup}), which determine how
7098 * the tool is displayed in the toolbar. See {@link OO.ui.Toolbar toolbars} for an example.
7100 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
7101 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7105 * @extends OO.ui.Widget
7106 * @mixins OO.ui.mixin.IconElement
7107 * @mixins OO.ui.mixin.FlaggedElement
7108 * @mixins OO.ui.mixin.TabIndexedElement
7111 * @param {OO.ui.ToolGroup} toolGroup
7112 * @param {Object} [config] Configuration options
7113 * @cfg {string|Function} [title] Title text or a function that returns text. If this config is omitted, the value of
7114 * the {@link #static-title static title} property is used.
7116 * The title is used in different ways depending on the type of toolgroup that contains the tool. The
7117 * 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
7118 * part of a {@link OO.ui.ListToolGroup list} or {@link OO.ui.MenuToolGroup menu} toolgroup.
7120 * For bar toolgroups, a description of the accelerator key is appended to the title if an accelerator key
7121 * is associated with an action by the same name as the tool and accelerator functionality has been added to the application.
7122 * To add accelerator key functionality, you must subclass OO.ui.Toolbar and override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method.
7124 OO
.ui
.Tool
= function OoUiTool( toolGroup
, config
) {
7125 // Allow passing positional parameters inside the config object
7126 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
7128 toolGroup
= config
.toolGroup
;
7131 // Configuration initialization
7132 config
= config
|| {};
7134 // Parent constructor
7135 OO
.ui
.Tool
.parent
.call( this, config
);
7138 this.toolGroup
= toolGroup
;
7139 this.toolbar
= this.toolGroup
.getToolbar();
7140 this.active
= false;
7141 this.$title
= $( '<span>' );
7142 this.$accel
= $( '<span>' );
7143 this.$link
= $( '<a>' );
7146 // Mixin constructors
7147 OO
.ui
.mixin
.IconElement
.call( this, config
);
7148 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
7149 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$link
} ) );
7152 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
7155 this.$title
.addClass( 'oo-ui-tool-title' );
7157 .addClass( 'oo-ui-tool-accel' )
7159 // This may need to be changed if the key names are ever localized,
7160 // but for now they are essentially written in English
7165 .addClass( 'oo-ui-tool-link' )
7166 .append( this.$icon
, this.$title
, this.$accel
)
7167 .attr( 'role', 'button' );
7169 .data( 'oo-ui-tool', this )
7171 'oo-ui-tool ' + 'oo-ui-tool-name-' +
7172 this.constructor.static.name
.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
7174 .toggleClass( 'oo-ui-tool-with-label', this.constructor.static.displayBothIconAndLabel
)
7175 .append( this.$link
);
7176 this.setTitle( config
.title
|| this.constructor.static.title
);
7181 OO
.inheritClass( OO
.ui
.Tool
, OO
.ui
.Widget
);
7182 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.IconElement
);
7183 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.FlaggedElement
);
7184 OO
.mixinClass( OO
.ui
.Tool
, OO
.ui
.mixin
.TabIndexedElement
);
7186 /* Static Properties */
7192 OO
.ui
.Tool
.static.tagName
= 'span';
7195 * Symbolic name of tool.
7197 * The symbolic name is used internally to register the tool with a {@link OO.ui.ToolFactory ToolFactory}. It can
7198 * also be used when adding tools to toolgroups.
7203 * @property {string}
7205 OO
.ui
.Tool
.static.name
= '';
7208 * Symbolic name of the group.
7210 * The group name is used to associate tools with each other so that they can be selected later by
7211 * a {@link OO.ui.ToolGroup toolgroup}.
7216 * @property {string}
7218 OO
.ui
.Tool
.static.group
= '';
7221 * 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.
7226 * @property {string|Function}
7228 OO
.ui
.Tool
.static.title
= '';
7231 * Display both icon and label when the tool is used in a {@link OO.ui.BarToolGroup bar} toolgroup.
7232 * Normally only the icon is displayed, or only the label if no icon is given.
7236 * @property {boolean}
7238 OO
.ui
.Tool
.static.displayBothIconAndLabel
= false;
7241 * Add tool to catch-all groups automatically.
7243 * A catch-all group, which contains all tools that do not currently belong to a toolgroup,
7244 * can be included in a toolgroup using the wildcard selector, an asterisk (*).
7248 * @property {boolean}
7250 OO
.ui
.Tool
.static.autoAddToCatchall
= true;
7253 * Add tool to named groups automatically.
7255 * By default, tools that are configured with a static ‘group’ property are added
7256 * to that group and will be selected when the symbolic name of the group is specified (e.g., when
7257 * toolgroups include tools by group name).
7260 * @property {boolean}
7263 OO
.ui
.Tool
.static.autoAddToGroup
= true;
7266 * Check if this tool is compatible with given data.
7268 * This is a stub that can be overriden to provide support for filtering tools based on an
7269 * arbitrary piece of information (e.g., where the cursor is in a document). The implementation
7270 * must also call this method so that the compatibility check can be performed.
7274 * @param {Mixed} data Data to check
7275 * @return {boolean} Tool can be used with data
7277 OO
.ui
.Tool
.static.isCompatibleWith = function () {
7284 * Handle the toolbar state being updated.
7286 * This is an abstract method that must be overridden in a concrete subclass.
7291 OO
.ui
.Tool
.prototype.onUpdateState = function () {
7293 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
7298 * Handle the tool being selected.
7300 * This is an abstract method that must be overridden in a concrete subclass.
7305 OO
.ui
.Tool
.prototype.onSelect = function () {
7307 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
7312 * Check if the tool is active.
7314 * Tools become active when their #onSelect or #onUpdateState handlers change them to appear pressed
7315 * with the #setActive method. Additional CSS is applied to the tool to reflect the active state.
7317 * @return {boolean} Tool is active
7319 OO
.ui
.Tool
.prototype.isActive = function () {
7324 * Make the tool appear active or inactive.
7326 * This method should be called within #onSelect or #onUpdateState event handlers to make the tool
7327 * appear pressed or not.
7329 * @param {boolean} state Make tool appear active
7331 OO
.ui
.Tool
.prototype.setActive = function ( state
) {
7332 this.active
= !!state
;
7333 if ( this.active
) {
7334 this.$element
.addClass( 'oo-ui-tool-active' );
7336 this.$element
.removeClass( 'oo-ui-tool-active' );
7341 * Set the tool #title.
7343 * @param {string|Function} title Title text or a function that returns text
7346 OO
.ui
.Tool
.prototype.setTitle = function ( title
) {
7347 this.title
= OO
.ui
.resolveMsg( title
);
7353 * Get the tool #title.
7355 * @return {string} Title text
7357 OO
.ui
.Tool
.prototype.getTitle = function () {
7362 * Get the tool's symbolic name.
7364 * @return {string} Symbolic name of tool
7366 OO
.ui
.Tool
.prototype.getName = function () {
7367 return this.constructor.static.name
;
7373 OO
.ui
.Tool
.prototype.updateTitle = function () {
7374 var titleTooltips
= this.toolGroup
.constructor.static.titleTooltips
,
7375 accelTooltips
= this.toolGroup
.constructor.static.accelTooltips
,
7376 accel
= this.toolbar
.getToolAccelerator( this.constructor.static.name
),
7379 this.$title
.text( this.title
);
7380 this.$accel
.text( accel
);
7382 if ( titleTooltips
&& typeof this.title
=== 'string' && this.title
.length
) {
7383 tooltipParts
.push( this.title
);
7385 if ( accelTooltips
&& typeof accel
=== 'string' && accel
.length
) {
7386 tooltipParts
.push( accel
);
7388 if ( tooltipParts
.length
) {
7389 this.$link
.attr( 'title', tooltipParts
.join( ' ' ) );
7391 this.$link
.removeAttr( 'title' );
7398 * Destroying the tool removes all event handlers and the tool’s DOM elements.
7399 * Call this method whenever you are done using a tool.
7401 OO
.ui
.Tool
.prototype.destroy = function () {
7402 this.toolbar
.disconnect( this );
7403 this.$element
.remove();
7407 * Toolbars are complex interface components that permit users to easily access a variety
7408 * of {@link OO.ui.Tool tools} (e.g., formatting commands) and actions, which are additional commands that are
7409 * part of the toolbar, but not configured as tools.
7411 * Individual tools are customized and then registered with a {@link OO.ui.ToolFactory tool factory}, which creates
7412 * the tools on demand. Each tool has a symbolic name (used when registering the tool), a title (e.g., ‘Insert
7413 * picture’), and an icon.
7415 * Individual tools are organized in {@link OO.ui.ToolGroup toolgroups}, which can be {@link OO.ui.MenuToolGroup menus}
7416 * of tools, {@link OO.ui.ListToolGroup lists} of tools, or a single {@link OO.ui.BarToolGroup bar} of tools.
7417 * The arrangement and order of the toolgroups is customized when the toolbar is set up. Tools can be presented in
7418 * any order, but each can only appear once in the toolbar.
7420 * The following is an example of a basic toolbar.
7423 * // Example of a toolbar
7424 * // Create the toolbar
7425 * var toolFactory = new OO.ui.ToolFactory();
7426 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7427 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7429 * // We will be placing status text in this element when tools are used
7430 * var $area = $( '<p>' ).text( 'Toolbar example' );
7432 * // Define the tools that we're going to place in our toolbar
7434 * // Create a class inheriting from OO.ui.Tool
7435 * function PictureTool() {
7436 * PictureTool.parent.apply( this, arguments );
7438 * OO.inheritClass( PictureTool, OO.ui.Tool );
7439 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7440 * // of 'icon' and 'title' (displayed icon and text).
7441 * PictureTool.static.name = 'picture';
7442 * PictureTool.static.icon = 'picture';
7443 * PictureTool.static.title = 'Insert picture';
7444 * // Defines the action that will happen when this tool is selected (clicked).
7445 * PictureTool.prototype.onSelect = function () {
7446 * $area.text( 'Picture tool clicked!' );
7447 * // Never display this tool as "active" (selected).
7448 * this.setActive( false );
7450 * // Make this tool available in our toolFactory and thus our toolbar
7451 * toolFactory.register( PictureTool );
7453 * // Register two more tools, nothing interesting here
7454 * function SettingsTool() {
7455 * SettingsTool.parent.apply( this, arguments );
7457 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7458 * SettingsTool.static.name = 'settings';
7459 * SettingsTool.static.icon = 'settings';
7460 * SettingsTool.static.title = 'Change settings';
7461 * SettingsTool.prototype.onSelect = function () {
7462 * $area.text( 'Settings tool clicked!' );
7463 * this.setActive( false );
7465 * toolFactory.register( SettingsTool );
7467 * // Register two more tools, nothing interesting here
7468 * function StuffTool() {
7469 * StuffTool.parent.apply( this, arguments );
7471 * OO.inheritClass( StuffTool, OO.ui.Tool );
7472 * StuffTool.static.name = 'stuff';
7473 * StuffTool.static.icon = 'ellipsis';
7474 * StuffTool.static.title = 'More stuff';
7475 * StuffTool.prototype.onSelect = function () {
7476 * $area.text( 'More stuff tool clicked!' );
7477 * this.setActive( false );
7479 * toolFactory.register( StuffTool );
7481 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7482 * // little popup window (a PopupWidget).
7483 * function HelpTool( toolGroup, config ) {
7484 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7489 * this.popup.$body.append( '<p>I am helpful!</p>' );
7491 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7492 * HelpTool.static.name = 'help';
7493 * HelpTool.static.icon = 'help';
7494 * HelpTool.static.title = 'Help';
7495 * toolFactory.register( HelpTool );
7497 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7498 * // used once (but not all defined tools must be used).
7501 * // 'bar' tool groups display tools' icons only, side-by-side.
7503 * include: [ 'picture', 'help' ]
7506 * // 'list' tool groups display both the titles and icons, in a dropdown list.
7508 * indicator: 'down',
7510 * include: [ 'settings', 'stuff' ]
7512 * // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed
7513 * // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here,
7514 * // since it's more complicated to use. (See the next example snippet on this page.)
7517 * // Create some UI around the toolbar and place it in the document
7518 * var frame = new OO.ui.PanelLayout( {
7522 * var contentFrame = new OO.ui.PanelLayout( {
7526 * frame.$element.append(
7528 * contentFrame.$element.append( $area )
7530 * $( 'body' ).append( frame.$element );
7532 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7534 * toolbar.initialize();
7536 * The following example extends the previous one to illustrate 'menu' toolgroups and the usage of
7537 * 'updateState' event.
7540 * // Create the toolbar
7541 * var toolFactory = new OO.ui.ToolFactory();
7542 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
7543 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
7545 * // We will be placing status text in this element when tools are used
7546 * var $area = $( '<p>' ).text( 'Toolbar example' );
7548 * // Define the tools that we're going to place in our toolbar
7550 * // Create a class inheriting from OO.ui.Tool
7551 * function PictureTool() {
7552 * PictureTool.parent.apply( this, arguments );
7554 * OO.inheritClass( PictureTool, OO.ui.Tool );
7555 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
7556 * // of 'icon' and 'title' (displayed icon and text).
7557 * PictureTool.static.name = 'picture';
7558 * PictureTool.static.icon = 'picture';
7559 * PictureTool.static.title = 'Insert picture';
7560 * // Defines the action that will happen when this tool is selected (clicked).
7561 * PictureTool.prototype.onSelect = function () {
7562 * $area.text( 'Picture tool clicked!' );
7563 * // Never display this tool as "active" (selected).
7564 * this.setActive( false );
7566 * // The toolbar can be synchronized with the state of some external stuff, like a text
7567 * // editor's editing area, highlighting the tools (e.g. a 'bold' tool would be shown as active
7568 * // when the text cursor was inside bolded text). Here we simply disable this feature.
7569 * PictureTool.prototype.onUpdateState = function () {
7571 * // Make this tool available in our toolFactory and thus our toolbar
7572 * toolFactory.register( PictureTool );
7574 * // Register two more tools, nothing interesting here
7575 * function SettingsTool() {
7576 * SettingsTool.parent.apply( this, arguments );
7577 * this.reallyActive = false;
7579 * OO.inheritClass( SettingsTool, OO.ui.Tool );
7580 * SettingsTool.static.name = 'settings';
7581 * SettingsTool.static.icon = 'settings';
7582 * SettingsTool.static.title = 'Change settings';
7583 * SettingsTool.prototype.onSelect = function () {
7584 * $area.text( 'Settings tool clicked!' );
7585 * // Toggle the active state on each click
7586 * this.reallyActive = !this.reallyActive;
7587 * this.setActive( this.reallyActive );
7588 * // To update the menu label
7589 * this.toolbar.emit( 'updateState' );
7591 * SettingsTool.prototype.onUpdateState = function () {
7593 * toolFactory.register( SettingsTool );
7595 * // Register two more tools, nothing interesting here
7596 * function StuffTool() {
7597 * StuffTool.parent.apply( this, arguments );
7598 * this.reallyActive = false;
7600 * OO.inheritClass( StuffTool, OO.ui.Tool );
7601 * StuffTool.static.name = 'stuff';
7602 * StuffTool.static.icon = 'ellipsis';
7603 * StuffTool.static.title = 'More stuff';
7604 * StuffTool.prototype.onSelect = function () {
7605 * $area.text( 'More stuff tool clicked!' );
7606 * // Toggle the active state on each click
7607 * this.reallyActive = !this.reallyActive;
7608 * this.setActive( this.reallyActive );
7609 * // To update the menu label
7610 * this.toolbar.emit( 'updateState' );
7612 * StuffTool.prototype.onUpdateState = function () {
7614 * toolFactory.register( StuffTool );
7616 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
7617 * // little popup window (a PopupWidget). 'onUpdateState' is also already implemented.
7618 * function HelpTool( toolGroup, config ) {
7619 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
7624 * this.popup.$body.append( '<p>I am helpful!</p>' );
7626 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
7627 * HelpTool.static.name = 'help';
7628 * HelpTool.static.icon = 'help';
7629 * HelpTool.static.title = 'Help';
7630 * toolFactory.register( HelpTool );
7632 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
7633 * // used once (but not all defined tools must be used).
7636 * // 'bar' tool groups display tools' icons only, side-by-side.
7638 * include: [ 'picture', 'help' ]
7641 * // 'menu' tool groups display both the titles and icons, in a dropdown menu.
7642 * // Menu label indicates which items are selected.
7644 * indicator: 'down',
7645 * include: [ 'settings', 'stuff' ]
7649 * // Create some UI around the toolbar and place it in the document
7650 * var frame = new OO.ui.PanelLayout( {
7654 * var contentFrame = new OO.ui.PanelLayout( {
7658 * frame.$element.append(
7660 * contentFrame.$element.append( $area )
7662 * $( 'body' ).append( frame.$element );
7664 * // Here is where the toolbar is actually built. This must be done after inserting it into the
7666 * toolbar.initialize();
7667 * toolbar.emit( 'updateState' );
7670 * @extends OO.ui.Element
7671 * @mixins OO.EventEmitter
7672 * @mixins OO.ui.mixin.GroupElement
7675 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
7676 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating toolgroups
7677 * @param {Object} [config] Configuration options
7678 * @cfg {boolean} [actions] Add an actions section to the toolbar. Actions are commands that are included
7679 * in the toolbar, but are not configured as tools. By default, actions are displayed on the right side of
7681 * @cfg {boolean} [shadow] Add a shadow below the toolbar.
7683 OO
.ui
.Toolbar
= function OoUiToolbar( toolFactory
, toolGroupFactory
, config
) {
7684 // Allow passing positional parameters inside the config object
7685 if ( OO
.isPlainObject( toolFactory
) && config
=== undefined ) {
7686 config
= toolFactory
;
7687 toolFactory
= config
.toolFactory
;
7688 toolGroupFactory
= config
.toolGroupFactory
;
7691 // Configuration initialization
7692 config
= config
|| {};
7694 // Parent constructor
7695 OO
.ui
.Toolbar
.parent
.call( this, config
);
7697 // Mixin constructors
7698 OO
.EventEmitter
.call( this );
7699 OO
.ui
.mixin
.GroupElement
.call( this, config
);
7702 this.toolFactory
= toolFactory
;
7703 this.toolGroupFactory
= toolGroupFactory
;
7706 this.$bar
= $( '<div>' );
7707 this.$actions
= $( '<div>' );
7708 this.initialized
= false;
7709 this.onWindowResizeHandler
= this.onWindowResize
.bind( this );
7713 .add( this.$bar
).add( this.$group
).add( this.$actions
)
7714 .on( 'mousedown keydown', this.onPointerDown
.bind( this ) );
7717 this.$group
.addClass( 'oo-ui-toolbar-tools' );
7718 if ( config
.actions
) {
7719 this.$bar
.append( this.$actions
.addClass( 'oo-ui-toolbar-actions' ) );
7722 .addClass( 'oo-ui-toolbar-bar' )
7723 .append( this.$group
, '<div style="clear:both"></div>' );
7724 if ( config
.shadow
) {
7725 this.$bar
.append( '<div class="oo-ui-toolbar-shadow"></div>' );
7727 this.$element
.addClass( 'oo-ui-toolbar' ).append( this.$bar
);
7732 OO
.inheritClass( OO
.ui
.Toolbar
, OO
.ui
.Element
);
7733 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.EventEmitter
);
7734 OO
.mixinClass( OO
.ui
.Toolbar
, OO
.ui
.mixin
.GroupElement
);
7739 * Get the tool factory.
7741 * @return {OO.ui.ToolFactory} Tool factory
7743 OO
.ui
.Toolbar
.prototype.getToolFactory = function () {
7744 return this.toolFactory
;
7748 * Get the toolgroup factory.
7750 * @return {OO.Factory} Toolgroup factory
7752 OO
.ui
.Toolbar
.prototype.getToolGroupFactory = function () {
7753 return this.toolGroupFactory
;
7757 * Handles mouse down events.
7760 * @param {jQuery.Event} e Mouse down event
7762 OO
.ui
.Toolbar
.prototype.onPointerDown = function ( e
) {
7763 var $closestWidgetToEvent
= $( e
.target
).closest( '.oo-ui-widget' ),
7764 $closestWidgetToToolbar
= this.$element
.closest( '.oo-ui-widget' );
7765 if ( !$closestWidgetToEvent
.length
|| $closestWidgetToEvent
[ 0 ] === $closestWidgetToToolbar
[ 0 ] ) {
7771 * Handle window resize event.
7774 * @param {jQuery.Event} e Window resize event
7776 OO
.ui
.Toolbar
.prototype.onWindowResize = function () {
7777 this.$element
.toggleClass(
7778 'oo-ui-toolbar-narrow',
7779 this.$bar
.width() <= this.narrowThreshold
7784 * Sets up handles and preloads required information for the toolbar to work.
7785 * This must be called after it is attached to a visible document and before doing anything else.
7787 OO
.ui
.Toolbar
.prototype.initialize = function () {
7788 if ( !this.initialized
) {
7789 this.initialized
= true;
7790 this.narrowThreshold
= this.$group
.width() + this.$actions
.width();
7791 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler
);
7792 this.onWindowResize();
7797 * Set up the toolbar.
7799 * The toolbar is set up with a list of toolgroup configurations that specify the type of
7800 * toolgroup ({@link OO.ui.BarToolGroup bar}, {@link OO.ui.MenuToolGroup menu}, or {@link OO.ui.ListToolGroup list})
7801 * to add and which tools to include, exclude, promote, or demote within that toolgroup. Please
7802 * see {@link OO.ui.ToolGroup toolgroups} for more information about including tools in toolgroups.
7804 * @param {Object.<string,Array>} groups List of toolgroup configurations
7805 * @param {Array|string} [groups.include] Tools to include in the toolgroup
7806 * @param {Array|string} [groups.exclude] Tools to exclude from the toolgroup
7807 * @param {Array|string} [groups.promote] Tools to promote to the beginning of the toolgroup
7808 * @param {Array|string} [groups.demote] Tools to demote to the end of the toolgroup
7810 OO
.ui
.Toolbar
.prototype.setup = function ( groups
) {
7811 var i
, len
, type
, group
,
7813 defaultType
= 'bar';
7815 // Cleanup previous groups
7818 // Build out new groups
7819 for ( i
= 0, len
= groups
.length
; i
< len
; i
++ ) {
7820 group
= groups
[ i
];
7821 if ( group
.include
=== '*' ) {
7822 // Apply defaults to catch-all groups
7823 if ( group
.type
=== undefined ) {
7824 group
.type
= 'list';
7826 if ( group
.label
=== undefined ) {
7827 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
7830 // Check type has been registered
7831 type
= this.getToolGroupFactory().lookup( group
.type
) ? group
.type
: defaultType
;
7833 this.getToolGroupFactory().create( type
, this, group
)
7836 this.addItems( items
);
7840 * Remove all tools and toolgroups from the toolbar.
7842 OO
.ui
.Toolbar
.prototype.reset = function () {
7847 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
7848 this.items
[ i
].destroy();
7854 * Destroy the toolbar.
7856 * Destroying the toolbar removes all event handlers and DOM elements that constitute the toolbar. Call
7857 * this method whenever you are done using a toolbar.
7859 OO
.ui
.Toolbar
.prototype.destroy = function () {
7860 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler
);
7862 this.$element
.remove();
7866 * Check if the tool is available.
7868 * Available tools are ones that have not yet been added to the toolbar.
7870 * @param {string} name Symbolic name of tool
7871 * @return {boolean} Tool is available
7873 OO
.ui
.Toolbar
.prototype.isToolAvailable = function ( name
) {
7874 return !this.tools
[ name
];
7878 * Prevent tool from being used again.
7880 * @param {OO.ui.Tool} tool Tool to reserve
7882 OO
.ui
.Toolbar
.prototype.reserveTool = function ( tool
) {
7883 this.tools
[ tool
.getName() ] = tool
;
7887 * Allow tool to be used again.
7889 * @param {OO.ui.Tool} tool Tool to release
7891 OO
.ui
.Toolbar
.prototype.releaseTool = function ( tool
) {
7892 delete this.tools
[ tool
.getName() ];
7896 * Get accelerator label for tool.
7898 * The OOjs UI library does not contain an accelerator system, but this is the hook for one. To
7899 * use an accelerator system, subclass the toolbar and override this method, which is meant to return a label
7900 * that describes the accelerator keys for the tool passed (by symbolic name) to the method.
7902 * @param {string} name Symbolic name of tool
7903 * @return {string|undefined} Tool accelerator label if available
7905 OO
.ui
.Toolbar
.prototype.getToolAccelerator = function () {
7910 * ToolGroups are collections of {@link OO.ui.Tool tools} that are used in a {@link OO.ui.Toolbar toolbar}.
7911 * The type of toolgroup ({@link OO.ui.ListToolGroup list}, {@link OO.ui.BarToolGroup bar}, or {@link OO.ui.MenuToolGroup menu})
7912 * to which a tool belongs determines how the tool is arranged and displayed in the toolbar. Toolgroups
7913 * themselves are created on demand with a {@link OO.ui.ToolGroupFactory toolgroup factory}.
7915 * Toolgroups can contain individual tools, groups of tools, or all available tools:
7917 * To include an individual tool (or array of individual tools), specify tools by symbolic name:
7919 * include: [ 'tool-name' ] or [ { name: 'tool-name' }]
7921 * 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.)
7923 * include: [ { group: 'group-name' } ]
7925 * To include all tools that are not yet assigned to a toolgroup, use the catch-all selector, an asterisk (*):
7929 * See {@link OO.ui.Toolbar toolbars} for a full example. For more information about toolbars in general,
7930 * please see the [OOjs UI documentation on MediaWiki][1].
7932 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
7936 * @extends OO.ui.Widget
7937 * @mixins OO.ui.mixin.GroupElement
7940 * @param {OO.ui.Toolbar} toolbar
7941 * @param {Object} [config] Configuration options
7942 * @cfg {Array|string} [include=[]] List of tools to include in the toolgroup.
7943 * @cfg {Array|string} [exclude=[]] List of tools to exclude from the toolgroup.
7944 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning of the toolgroup.
7945 * @cfg {Array|string} [demote=[]] List of tools to demote to the end of the toolgroup.
7946 * This setting is particularly useful when tools have been added to the toolgroup
7947 * en masse (e.g., via the catch-all selector).
7949 OO
.ui
.ToolGroup
= function OoUiToolGroup( toolbar
, config
) {
7950 // Allow passing positional parameters inside the config object
7951 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
7953 toolbar
= config
.toolbar
;
7956 // Configuration initialization
7957 config
= config
|| {};
7959 // Parent constructor
7960 OO
.ui
.ToolGroup
.parent
.call( this, config
);
7962 // Mixin constructors
7963 OO
.ui
.mixin
.GroupElement
.call( this, config
);
7966 this.toolbar
= toolbar
;
7968 this.pressed
= null;
7969 this.autoDisabled
= false;
7970 this.include
= config
.include
|| [];
7971 this.exclude
= config
.exclude
|| [];
7972 this.promote
= config
.promote
|| [];
7973 this.demote
= config
.demote
|| [];
7974 this.onCapturedMouseKeyUpHandler
= this.onCapturedMouseKeyUp
.bind( this );
7978 mousedown
: this.onMouseKeyDown
.bind( this ),
7979 mouseup
: this.onMouseKeyUp
.bind( this ),
7980 keydown
: this.onMouseKeyDown
.bind( this ),
7981 keyup
: this.onMouseKeyUp
.bind( this ),
7982 focus
: this.onMouseOverFocus
.bind( this ),
7983 blur
: this.onMouseOutBlur
.bind( this ),
7984 mouseover
: this.onMouseOverFocus
.bind( this ),
7985 mouseout
: this.onMouseOutBlur
.bind( this )
7987 this.toolbar
.getToolFactory().connect( this, { register
: 'onToolFactoryRegister' } );
7988 this.aggregate( { disable
: 'itemDisable' } );
7989 this.connect( this, { itemDisable
: 'updateDisabled' } );
7992 this.$group
.addClass( 'oo-ui-toolGroup-tools' );
7994 .addClass( 'oo-ui-toolGroup' )
7995 .append( this.$group
);
8001 OO
.inheritClass( OO
.ui
.ToolGroup
, OO
.ui
.Widget
);
8002 OO
.mixinClass( OO
.ui
.ToolGroup
, OO
.ui
.mixin
.GroupElement
);
8010 /* Static Properties */
8013 * Show labels in tooltips.
8017 * @property {boolean}
8019 OO
.ui
.ToolGroup
.static.titleTooltips
= false;
8022 * Show acceleration labels in tooltips.
8024 * Note: The OOjs UI library does not include an accelerator system, but does contain
8025 * a hook for one. To use an accelerator system, subclass the {@link OO.ui.Toolbar toolbar} and
8026 * override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method, which is
8027 * meant to return a label that describes the accelerator keys for a given tool (e.g., 'Ctrl + M').
8031 * @property {boolean}
8033 OO
.ui
.ToolGroup
.static.accelTooltips
= false;
8036 * Automatically disable the toolgroup when all tools are disabled
8040 * @property {boolean}
8042 OO
.ui
.ToolGroup
.static.autoDisable
= true;
8049 OO
.ui
.ToolGroup
.prototype.isDisabled = function () {
8050 return this.autoDisabled
|| OO
.ui
.ToolGroup
.parent
.prototype.isDisabled
.apply( this, arguments
);
8056 OO
.ui
.ToolGroup
.prototype.updateDisabled = function () {
8057 var i
, item
, allDisabled
= true;
8059 if ( this.constructor.static.autoDisable
) {
8060 for ( i
= this.items
.length
- 1; i
>= 0; i
-- ) {
8061 item
= this.items
[ i
];
8062 if ( !item
.isDisabled() ) {
8063 allDisabled
= false;
8067 this.autoDisabled
= allDisabled
;
8069 OO
.ui
.ToolGroup
.parent
.prototype.updateDisabled
.apply( this, arguments
);
8073 * Handle mouse down and key down events.
8076 * @param {jQuery.Event} e Mouse down or key down event
8078 OO
.ui
.ToolGroup
.prototype.onMouseKeyDown = function ( e
) {
8080 !this.isDisabled() &&
8081 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
8083 this.pressed
= this.getTargetTool( e
);
8084 if ( this.pressed
) {
8085 this.pressed
.setActive( true );
8086 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler
);
8087 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler
);
8094 * Handle captured mouse up and key up events.
8097 * @param {Event} e Mouse up or key up event
8099 OO
.ui
.ToolGroup
.prototype.onCapturedMouseKeyUp = function ( e
) {
8100 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onCapturedMouseKeyUpHandler
);
8101 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onCapturedMouseKeyUpHandler
);
8102 // onMouseKeyUp may be called a second time, depending on where the mouse is when the button is
8103 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
8104 this.onMouseKeyUp( e
);
8108 * Handle mouse up and key up events.
8111 * @param {jQuery.Event} e Mouse up or key up event
8113 OO
.ui
.ToolGroup
.prototype.onMouseKeyUp = function ( e
) {
8114 var tool
= this.getTargetTool( e
);
8117 !this.isDisabled() && this.pressed
&& this.pressed
=== tool
&&
8118 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
8120 this.pressed
.onSelect();
8121 this.pressed
= null;
8125 this.pressed
= null;
8129 * Handle mouse over and focus events.
8132 * @param {jQuery.Event} e Mouse over or focus event
8134 OO
.ui
.ToolGroup
.prototype.onMouseOverFocus = function ( e
) {
8135 var tool
= this.getTargetTool( e
);
8137 if ( this.pressed
&& this.pressed
=== tool
) {
8138 this.pressed
.setActive( true );
8143 * Handle mouse out and blur events.
8146 * @param {jQuery.Event} e Mouse out or blur event
8148 OO
.ui
.ToolGroup
.prototype.onMouseOutBlur = function ( e
) {
8149 var tool
= this.getTargetTool( e
);
8151 if ( this.pressed
&& this.pressed
=== tool
) {
8152 this.pressed
.setActive( false );
8157 * Get the closest tool to a jQuery.Event.
8159 * Only tool links are considered, which prevents other elements in the tool such as popups from
8160 * triggering tool group interactions.
8163 * @param {jQuery.Event} e
8164 * @return {OO.ui.Tool|null} Tool, `null` if none was found
8166 OO
.ui
.ToolGroup
.prototype.getTargetTool = function ( e
) {
8168 $item
= $( e
.target
).closest( '.oo-ui-tool-link' );
8170 if ( $item
.length
) {
8171 tool
= $item
.parent().data( 'oo-ui-tool' );
8174 return tool
&& !tool
.isDisabled() ? tool
: null;
8178 * Handle tool registry register events.
8180 * If a tool is registered after the group is created, we must repopulate the list to account for:
8182 * - a tool being added that may be included
8183 * - a tool already included being overridden
8186 * @param {string} name Symbolic name of tool
8188 OO
.ui
.ToolGroup
.prototype.onToolFactoryRegister = function () {
8193 * Get the toolbar that contains the toolgroup.
8195 * @return {OO.ui.Toolbar} Toolbar that contains the toolgroup
8197 OO
.ui
.ToolGroup
.prototype.getToolbar = function () {
8198 return this.toolbar
;
8202 * Add and remove tools based on configuration.
8204 OO
.ui
.ToolGroup
.prototype.populate = function () {
8205 var i
, len
, name
, tool
,
8206 toolFactory
= this.toolbar
.getToolFactory(),
8210 list
= this.toolbar
.getToolFactory().getTools(
8211 this.include
, this.exclude
, this.promote
, this.demote
8214 // Build a list of needed tools
8215 for ( i
= 0, len
= list
.length
; i
< len
; i
++ ) {
8219 toolFactory
.lookup( name
) &&
8220 // Tool is available or is already in this group
8221 ( this.toolbar
.isToolAvailable( name
) || this.tools
[ name
] )
8223 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
8224 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
8225 this.toolbar
.tools
[ name
] = true;
8226 tool
= this.tools
[ name
];
8228 // Auto-initialize tools on first use
8229 this.tools
[ name
] = tool
= toolFactory
.create( name
, this );
8232 this.toolbar
.reserveTool( tool
);
8234 names
[ name
] = true;
8237 // Remove tools that are no longer needed
8238 for ( name
in this.tools
) {
8239 if ( !names
[ name
] ) {
8240 this.tools
[ name
].destroy();
8241 this.toolbar
.releaseTool( this.tools
[ name
] );
8242 remove
.push( this.tools
[ name
] );
8243 delete this.tools
[ name
];
8246 if ( remove
.length
) {
8247 this.removeItems( remove
);
8249 // Update emptiness state
8251 this.$element
.removeClass( 'oo-ui-toolGroup-empty' );
8253 this.$element
.addClass( 'oo-ui-toolGroup-empty' );
8255 // Re-add tools (moving existing ones to new locations)
8256 this.addItems( add
);
8257 // Disabled state may depend on items
8258 this.updateDisabled();
8262 * Destroy toolgroup.
8264 OO
.ui
.ToolGroup
.prototype.destroy = function () {
8268 this.toolbar
.getToolFactory().disconnect( this );
8269 for ( name
in this.tools
) {
8270 this.toolbar
.releaseTool( this.tools
[ name
] );
8271 this.tools
[ name
].disconnect( this ).destroy();
8272 delete this.tools
[ name
];
8274 this.$element
.remove();
8278 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
8279 * consists of a header that contains the dialog title, a body with the message, and a footer that
8280 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
8281 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
8283 * There are two basic types of message dialogs, confirmation and alert:
8285 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
8286 * more details about the consequences.
8287 * - **alert**: the dialog title describes which event occurred and the message provides more information
8288 * about why the event occurred.
8290 * The MessageDialog class specifies two actions: ‘accept’, the primary
8291 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
8292 * passing along the selected action.
8294 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
8297 * // Example: Creating and opening a message dialog window.
8298 * var messageDialog = new OO.ui.MessageDialog();
8300 * // Create and append a window manager.
8301 * var windowManager = new OO.ui.WindowManager();
8302 * $( 'body' ).append( windowManager.$element );
8303 * windowManager.addWindows( [ messageDialog ] );
8304 * // Open the window.
8305 * windowManager.openWindow( messageDialog, {
8306 * title: 'Basic message dialog',
8307 * message: 'This is the message'
8310 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
8313 * @extends OO.ui.Dialog
8316 * @param {Object} [config] Configuration options
8318 OO
.ui
.MessageDialog
= function OoUiMessageDialog( config
) {
8319 // Parent constructor
8320 OO
.ui
.MessageDialog
.parent
.call( this, config
);
8323 this.verticalActionLayout
= null;
8326 this.$element
.addClass( 'oo-ui-messageDialog' );
8331 OO
.inheritClass( OO
.ui
.MessageDialog
, OO
.ui
.Dialog
);
8333 /* Static Properties */
8335 OO
.ui
.MessageDialog
.static.name
= 'message';
8337 OO
.ui
.MessageDialog
.static.size
= 'small';
8339 OO
.ui
.MessageDialog
.static.verbose
= false;
8344 * The title of a confirmation dialog describes what a progressive action will do. The
8345 * title of an alert dialog describes which event occurred.
8349 * @property {jQuery|string|Function|null}
8351 OO
.ui
.MessageDialog
.static.title
= null;
8354 * The message displayed in the dialog body.
8356 * A confirmation message describes the consequences of a progressive action. An alert
8357 * message describes why an event occurred.
8361 * @property {jQuery|string|Function|null}
8363 OO
.ui
.MessageDialog
.static.message
= null;
8365 OO
.ui
.MessageDialog
.static.actions
= [
8366 { action
: 'accept', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-accept' ), flags
: 'primary' },
8367 { action
: 'reject', label
: OO
.ui
.deferMsg( 'ooui-dialog-message-reject' ), flags
: 'safe' }
8375 OO
.ui
.MessageDialog
.prototype.setManager = function ( manager
) {
8376 OO
.ui
.MessageDialog
.parent
.prototype.setManager
.call( this, manager
);
8379 this.manager
.connect( this, {
8389 OO
.ui
.MessageDialog
.prototype.onActionResize = function ( action
) {
8391 return OO
.ui
.MessageDialog
.parent
.prototype.onActionResize
.call( this, action
);
8395 * Handle window resized events.
8399 OO
.ui
.MessageDialog
.prototype.onResize = function () {
8401 dialog
.fitActions();
8402 // Wait for CSS transition to finish and do it again :(
8403 setTimeout( function () {
8404 dialog
.fitActions();
8409 * Toggle action layout between vertical and horizontal.
8412 * @param {boolean} [value] Layout actions vertically, omit to toggle
8415 OO
.ui
.MessageDialog
.prototype.toggleVerticalActionLayout = function ( value
) {
8416 value
= value
=== undefined ? !this.verticalActionLayout
: !!value
;
8418 if ( value
!== this.verticalActionLayout
) {
8419 this.verticalActionLayout
= value
;
8421 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value
)
8422 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value
);
8431 OO
.ui
.MessageDialog
.prototype.getActionProcess = function ( action
) {
8433 return new OO
.ui
.Process( function () {
8434 this.close( { action
: action
} );
8437 return OO
.ui
.MessageDialog
.parent
.prototype.getActionProcess
.call( this, action
);
8443 * @param {Object} [data] Dialog opening data
8444 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
8445 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
8446 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
8447 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
8450 OO
.ui
.MessageDialog
.prototype.getSetupProcess = function ( data
) {
8454 return OO
.ui
.MessageDialog
.parent
.prototype.getSetupProcess
.call( this, data
)
8455 .next( function () {
8456 this.title
.setLabel(
8457 data
.title
!== undefined ? data
.title
: this.constructor.static.title
8459 this.message
.setLabel(
8460 data
.message
!== undefined ? data
.message
: this.constructor.static.message
8462 this.message
.$element
.toggleClass(
8463 'oo-ui-messageDialog-message-verbose',
8464 data
.verbose
!== undefined ? data
.verbose
: this.constructor.static.verbose
8472 OO
.ui
.MessageDialog
.prototype.getReadyProcess = function ( data
) {
8476 return OO
.ui
.MessageDialog
.parent
.prototype.getReadyProcess
.call( this, data
)
8477 .next( function () {
8478 // Focus the primary action button
8479 var actions
= this.actions
.get();
8480 actions
= actions
.filter( function ( action
) {
8481 return action
.getFlags().indexOf( 'primary' ) > -1;
8483 if ( actions
.length
> 0 ) {
8484 actions
[ 0 ].$button
.focus();
8492 OO
.ui
.MessageDialog
.prototype.getBodyHeight = function () {
8493 var bodyHeight
, oldOverflow
,
8494 $scrollable
= this.container
.$element
;
8496 oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
8497 $scrollable
[ 0 ].style
.overflow
= 'hidden';
8499 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
8501 bodyHeight
= this.text
.$element
.outerHeight( true );
8502 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
8510 OO
.ui
.MessageDialog
.prototype.setDimensions = function ( dim
) {
8511 var $scrollable
= this.container
.$element
;
8512 OO
.ui
.MessageDialog
.parent
.prototype.setDimensions
.call( this, dim
);
8514 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
8515 // Need to do it after transition completes (250ms), add 50ms just in case.
8516 setTimeout( function () {
8517 var oldOverflow
= $scrollable
[ 0 ].style
.overflow
;
8518 $scrollable
[ 0 ].style
.overflow
= 'hidden';
8520 OO
.ui
.Element
.static.reconsiderScrollbars( $scrollable
[ 0 ] );
8522 $scrollable
[ 0 ].style
.overflow
= oldOverflow
;
8531 OO
.ui
.MessageDialog
.prototype.initialize = function () {
8533 OO
.ui
.MessageDialog
.parent
.prototype.initialize
.call( this );
8536 this.$actions
= $( '<div>' );
8537 this.container
= new OO
.ui
.PanelLayout( {
8538 scrollable
: true, classes
: [ 'oo-ui-messageDialog-container' ]
8540 this.text
= new OO
.ui
.PanelLayout( {
8541 padded
: true, expanded
: false, classes
: [ 'oo-ui-messageDialog-text' ]
8543 this.message
= new OO
.ui
.LabelWidget( {
8544 classes
: [ 'oo-ui-messageDialog-message' ]
8548 this.title
.$element
.addClass( 'oo-ui-messageDialog-title' );
8549 this.$content
.addClass( 'oo-ui-messageDialog-content' );
8550 this.container
.$element
.append( this.text
.$element
);
8551 this.text
.$element
.append( this.title
.$element
, this.message
.$element
);
8552 this.$body
.append( this.container
.$element
);
8553 this.$actions
.addClass( 'oo-ui-messageDialog-actions' );
8554 this.$foot
.append( this.$actions
);
8560 OO
.ui
.MessageDialog
.prototype.attachActions = function () {
8561 var i
, len
, other
, special
, others
;
8564 OO
.ui
.MessageDialog
.parent
.prototype.attachActions
.call( this );
8566 special
= this.actions
.getSpecial();
8567 others
= this.actions
.getOthers();
8569 if ( special
.safe
) {
8570 this.$actions
.append( special
.safe
.$element
);
8571 special
.safe
.toggleFramed( false );
8573 if ( others
.length
) {
8574 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
8575 other
= others
[ i
];
8576 this.$actions
.append( other
.$element
);
8577 other
.toggleFramed( false );
8580 if ( special
.primary
) {
8581 this.$actions
.append( special
.primary
.$element
);
8582 special
.primary
.toggleFramed( false );
8585 if ( !this.isOpening() ) {
8586 // If the dialog is currently opening, this will be called automatically soon.
8587 // This also calls #fitActions.
8593 * Fit action actions into columns or rows.
8595 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
8599 OO
.ui
.MessageDialog
.prototype.fitActions = function () {
8601 previous
= this.verticalActionLayout
,
8602 actions
= this.actions
.get();
8605 this.toggleVerticalActionLayout( false );
8606 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
8607 action
= actions
[ i
];
8608 if ( action
.$element
.innerWidth() < action
.$label
.outerWidth( true ) ) {
8609 this.toggleVerticalActionLayout( true );
8614 // Move the body out of the way of the foot
8615 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
8617 if ( this.verticalActionLayout
!== previous
) {
8618 // We changed the layout, window height might need to be updated.
8624 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
8625 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
8626 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
8627 * relevant. The ProcessDialog class is always extended and customized with the actions and content
8628 * required for each process.
8630 * The process dialog box consists of a header that visually represents the ‘working’ state of long
8631 * processes with an animation. The header contains the dialog title as well as
8632 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
8633 * a ‘primary’ action on the right (e.g., ‘Done’).
8635 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
8636 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
8639 * // Example: Creating and opening a process dialog window.
8640 * function MyProcessDialog( config ) {
8641 * MyProcessDialog.parent.call( this, config );
8643 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
8645 * MyProcessDialog.static.title = 'Process dialog';
8646 * MyProcessDialog.static.actions = [
8647 * { action: 'save', label: 'Done', flags: 'primary' },
8648 * { label: 'Cancel', flags: 'safe' }
8651 * MyProcessDialog.prototype.initialize = function () {
8652 * MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
8653 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
8654 * 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>' );
8655 * this.$body.append( this.content.$element );
8657 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
8658 * var dialog = this;
8660 * return new OO.ui.Process( function () {
8661 * dialog.close( { action: action } );
8664 * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
8667 * var windowManager = new OO.ui.WindowManager();
8668 * $( 'body' ).append( windowManager.$element );
8670 * var dialog = new MyProcessDialog();
8671 * windowManager.addWindows( [ dialog ] );
8672 * windowManager.openWindow( dialog );
8674 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
8678 * @extends OO.ui.Dialog
8681 * @param {Object} [config] Configuration options
8683 OO
.ui
.ProcessDialog
= function OoUiProcessDialog( config
) {
8684 // Parent constructor
8685 OO
.ui
.ProcessDialog
.parent
.call( this, config
);
8688 this.fitOnOpen
= false;
8691 this.$element
.addClass( 'oo-ui-processDialog' );
8696 OO
.inheritClass( OO
.ui
.ProcessDialog
, OO
.ui
.Dialog
);
8701 * Handle dismiss button click events.
8707 OO
.ui
.ProcessDialog
.prototype.onDismissErrorButtonClick = function () {
8712 * Handle retry button click events.
8714 * Hides errors and then tries again.
8718 OO
.ui
.ProcessDialog
.prototype.onRetryButtonClick = function () {
8720 this.executeAction( this.currentAction
);
8726 OO
.ui
.ProcessDialog
.prototype.onActionResize = function ( action
) {
8727 if ( this.actions
.isSpecial( action
) ) {
8730 return OO
.ui
.ProcessDialog
.parent
.prototype.onActionResize
.call( this, action
);
8736 OO
.ui
.ProcessDialog
.prototype.initialize = function () {
8738 OO
.ui
.ProcessDialog
.parent
.prototype.initialize
.call( this );
8741 this.$navigation
= $( '<div>' );
8742 this.$location
= $( '<div>' );
8743 this.$safeActions
= $( '<div>' );
8744 this.$primaryActions
= $( '<div>' );
8745 this.$otherActions
= $( '<div>' );
8746 this.dismissButton
= new OO
.ui
.ButtonWidget( {
8747 label
: OO
.ui
.msg( 'ooui-dialog-process-dismiss' )
8749 this.retryButton
= new OO
.ui
.ButtonWidget();
8750 this.$errors
= $( '<div>' );
8751 this.$errorsTitle
= $( '<div>' );
8754 this.dismissButton
.connect( this, { click
: 'onDismissErrorButtonClick' } );
8755 this.retryButton
.connect( this, { click
: 'onRetryButtonClick' } );
8758 this.title
.$element
.addClass( 'oo-ui-processDialog-title' );
8760 .append( this.title
.$element
)
8761 .addClass( 'oo-ui-processDialog-location' );
8762 this.$safeActions
.addClass( 'oo-ui-processDialog-actions-safe' );
8763 this.$primaryActions
.addClass( 'oo-ui-processDialog-actions-primary' );
8764 this.$otherActions
.addClass( 'oo-ui-processDialog-actions-other' );
8766 .addClass( 'oo-ui-processDialog-errors-title' )
8767 .text( OO
.ui
.msg( 'ooui-dialog-process-error' ) );
8769 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
8770 .append( this.$errorsTitle
, this.dismissButton
.$element
, this.retryButton
.$element
);
8772 .addClass( 'oo-ui-processDialog-content' )
8773 .append( this.$errors
);
8775 .addClass( 'oo-ui-processDialog-navigation' )
8776 .append( this.$safeActions
, this.$location
, this.$primaryActions
);
8777 this.$head
.append( this.$navigation
);
8778 this.$foot
.append( this.$otherActions
);
8784 OO
.ui
.ProcessDialog
.prototype.getActionWidgets = function ( actions
) {
8785 var i
, len
, widgets
= [];
8786 for ( i
= 0, len
= actions
.length
; i
< len
; i
++ ) {
8788 new OO
.ui
.ActionWidget( $.extend( { framed
: true }, actions
[ i
] ) )
8797 OO
.ui
.ProcessDialog
.prototype.attachActions = function () {
8798 var i
, len
, other
, special
, others
;
8801 OO
.ui
.ProcessDialog
.parent
.prototype.attachActions
.call( this );
8803 special
= this.actions
.getSpecial();
8804 others
= this.actions
.getOthers();
8805 if ( special
.primary
) {
8806 this.$primaryActions
.append( special
.primary
.$element
);
8808 for ( i
= 0, len
= others
.length
; i
< len
; i
++ ) {
8809 other
= others
[ i
];
8810 this.$otherActions
.append( other
.$element
);
8812 if ( special
.safe
) {
8813 this.$safeActions
.append( special
.safe
.$element
);
8817 this.$body
.css( 'bottom', this.$foot
.outerHeight( true ) );
8823 OO
.ui
.ProcessDialog
.prototype.executeAction = function ( action
) {
8825 return OO
.ui
.ProcessDialog
.parent
.prototype.executeAction
.call( this, action
)
8826 .fail( function ( errors
) {
8827 process
.showErrors( errors
|| [] );
8834 OO
.ui
.ProcessDialog
.prototype.setDimensions = function () {
8836 OO
.ui
.ProcessDialog
.parent
.prototype.setDimensions
.apply( this, arguments
);
8842 * Fit label between actions.
8847 OO
.ui
.ProcessDialog
.prototype.fitLabel = function () {
8848 var safeWidth
, primaryWidth
, biggerWidth
, labelWidth
, navigationWidth
, leftWidth
, rightWidth
,
8849 size
= this.getSizeProperties();
8851 if ( typeof size
.width
!== 'number' ) {
8852 if ( this.isOpened() ) {
8853 navigationWidth
= this.$head
.width() - 20;
8854 } else if ( this.isOpening() ) {
8855 if ( !this.fitOnOpen
) {
8856 // Size is relative and the dialog isn't open yet, so wait.
8857 this.manager
.opening
.done( this.fitLabel
.bind( this ) );
8858 this.fitOnOpen
= true;
8865 navigationWidth
= size
.width
- 20;
8868 safeWidth
= this.$safeActions
.is( ':visible' ) ? this.$safeActions
.width() : 0;
8869 primaryWidth
= this.$primaryActions
.is( ':visible' ) ? this.$primaryActions
.width() : 0;
8870 biggerWidth
= Math
.max( safeWidth
, primaryWidth
);
8872 labelWidth
= this.title
.$element
.width();
8874 if ( 2 * biggerWidth
+ labelWidth
< navigationWidth
) {
8875 // We have enough space to center the label
8876 leftWidth
= rightWidth
= biggerWidth
;
8878 // Let's hope we at least have enough space not to overlap, because we can't wrap the label…
8879 if ( this.getDir() === 'ltr' ) {
8880 leftWidth
= safeWidth
;
8881 rightWidth
= primaryWidth
;
8883 leftWidth
= primaryWidth
;
8884 rightWidth
= safeWidth
;
8888 this.$location
.css( { paddingLeft
: leftWidth
, paddingRight
: rightWidth
} );
8894 * Handle errors that occurred during accept or reject processes.
8897 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
8899 OO
.ui
.ProcessDialog
.prototype.showErrors = function ( errors
) {
8900 var i
, len
, $item
, actions
,
8906 if ( errors
instanceof OO
.ui
.Error
) {
8907 errors
= [ errors
];
8910 for ( i
= 0, len
= errors
.length
; i
< len
; i
++ ) {
8911 if ( !errors
[ i
].isRecoverable() ) {
8912 recoverable
= false;
8914 if ( errors
[ i
].isWarning() ) {
8917 $item
= $( '<div>' )
8918 .addClass( 'oo-ui-processDialog-error' )
8919 .append( errors
[ i
].getMessage() );
8920 items
.push( $item
[ 0 ] );
8922 this.$errorItems
= $( items
);
8923 if ( recoverable
) {
8924 abilities
[ this.currentAction
] = true;
8925 // Copy the flags from the first matching action
8926 actions
= this.actions
.get( { actions
: this.currentAction
} );
8927 if ( actions
.length
) {
8928 this.retryButton
.clearFlags().setFlags( actions
[ 0 ].getFlags() );
8931 abilities
[ this.currentAction
] = false;
8932 this.actions
.setAbilities( abilities
);
8935 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-continue' ) );
8937 this.retryButton
.setLabel( OO
.ui
.msg( 'ooui-dialog-process-retry' ) );
8939 this.retryButton
.toggle( recoverable
);
8940 this.$errorsTitle
.after( this.$errorItems
);
8941 this.$errors
.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
8949 OO
.ui
.ProcessDialog
.prototype.hideErrors = function () {
8950 this.$errors
.addClass( 'oo-ui-element-hidden' );
8951 if ( this.$errorItems
) {
8952 this.$errorItems
.remove();
8953 this.$errorItems
= null;
8960 OO
.ui
.ProcessDialog
.prototype.getTeardownProcess = function ( data
) {
8962 return OO
.ui
.ProcessDialog
.parent
.prototype.getTeardownProcess
.call( this, data
)
8963 .first( function () {
8964 // Make sure to hide errors
8966 this.fitOnOpen
= false;
8971 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
8972 * which is a widget that is specified by reference before any optional configuration settings.
8974 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
8976 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8977 * A left-alignment is used for forms with many fields.
8978 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8979 * A right-alignment is used for long but familiar forms which users tab through,
8980 * verifying the current field with a quick glance at the label.
8981 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8982 * that users fill out from top to bottom.
8983 * - **inline**: The label is placed after the field-widget and aligned to the left.
8984 * An inline-alignment is best used with checkboxes or radio buttons.
8986 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
8987 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
8989 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8991 * @extends OO.ui.Layout
8992 * @mixins OO.ui.mixin.LabelElement
8993 * @mixins OO.ui.mixin.TitledElement
8996 * @param {OO.ui.Widget} fieldWidget Field widget
8997 * @param {Object} [config] Configuration options
8998 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
8999 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
9000 * The array may contain strings or OO.ui.HtmlSnippet instances.
9001 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
9002 * The array may contain strings or OO.ui.HtmlSnippet instances.
9003 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
9004 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
9005 * For important messages, you are advised to use `notices`, as they are always shown.
9007 * @throws {Error} An error is thrown if no widget is specified
9009 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
9010 var hasInputWidget
, div
, i
;
9012 // Allow passing positional parameters inside the config object
9013 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
9014 config
= fieldWidget
;
9015 fieldWidget
= config
.fieldWidget
;
9018 // Make sure we have required constructor arguments
9019 if ( fieldWidget
=== undefined ) {
9020 throw new Error( 'Widget not found' );
9023 hasInputWidget
= fieldWidget
.constructor.static.supportsSimpleLabel
;
9025 // Configuration initialization
9026 config
= $.extend( { align
: 'left' }, config
);
9028 // Parent constructor
9029 OO
.ui
.FieldLayout
.parent
.call( this, config
);
9031 // Mixin constructors
9032 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9033 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
9036 this.fieldWidget
= fieldWidget
;
9037 this.errors
= config
.errors
|| [];
9038 this.notices
= config
.notices
|| [];
9039 this.$field
= $( '<div>' );
9040 this.$messages
= $( '<ul>' );
9041 this.$body
= $( '<' + ( hasInputWidget
? 'label' : 'div' ) + '>' );
9043 if ( config
.help
) {
9044 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
9045 classes
: [ 'oo-ui-fieldLayout-help' ],
9051 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
9052 div
.html( config
.help
.toString() );
9054 div
.text( config
.help
);
9056 this.popupButtonWidget
.getPopup().$body
.append(
9057 div
.addClass( 'oo-ui-fieldLayout-help-content' )
9059 this.$help
= this.popupButtonWidget
.$element
;
9061 this.$help
= $( [] );
9065 if ( hasInputWidget
) {
9066 this.$label
.on( 'click', this.onLabelClick
.bind( this ) );
9068 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
9072 .addClass( 'oo-ui-fieldLayout' )
9073 .append( this.$help
, this.$body
);
9074 if ( this.errors
.length
|| this.notices
.length
) {
9075 this.$element
.append( this.$messages
);
9077 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
9078 this.$messages
.addClass( 'oo-ui-fieldLayout-messages' );
9080 .addClass( 'oo-ui-fieldLayout-field' )
9081 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget
.isDisabled() )
9082 .append( this.fieldWidget
.$element
);
9084 for ( i
= 0; i
< this.notices
.length
; i
++ ) {
9085 this.$messages
.append( this.makeMessage( 'notice', this.notices
[ i
] ) );
9087 for ( i
= 0; i
< this.errors
.length
; i
++ ) {
9088 this.$messages
.append( this.makeMessage( 'error', this.errors
[ i
] ) );
9091 this.setAlignment( config
.align
);
9096 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
9097 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.LabelElement
);
9098 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.TitledElement
);
9103 * Handle field disable events.
9106 * @param {boolean} value Field is disabled
9108 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
9109 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
9113 * Handle label mouse click events.
9116 * @param {jQuery.Event} e Mouse click event
9118 OO
.ui
.FieldLayout
.prototype.onLabelClick = function () {
9119 this.fieldWidget
.simulateLabelClick();
9124 * Get the widget contained by the field.
9126 * @return {OO.ui.Widget} Field widget
9128 OO
.ui
.FieldLayout
.prototype.getField = function () {
9129 return this.fieldWidget
;
9133 * @param {string} kind 'error' or 'notice'
9134 * @param {string|OO.ui.HtmlSnippet} text
9137 OO
.ui
.FieldLayout
.prototype.makeMessage = function ( kind
, text
) {
9138 var $listItem
, $icon
, message
;
9139 $listItem
= $( '<li>' );
9140 if ( kind
=== 'error' ) {
9141 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'warning' ] } ).$element
;
9142 } else if ( kind
=== 'notice' ) {
9143 $icon
= new OO
.ui
.IconWidget( { icon
: 'info' } ).$element
;
9147 message
= new OO
.ui
.LabelWidget( { label
: text
} );
9149 .append( $icon
, message
.$element
)
9150 .addClass( 'oo-ui-fieldLayout-messages-' + kind
);
9155 * Set the field alignment mode.
9158 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
9161 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
9162 if ( value
!== this.align
) {
9163 // Default to 'left'
9164 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
9168 if ( value
=== 'inline' ) {
9169 this.$body
.append( this.$field
, this.$label
);
9171 this.$body
.append( this.$label
, this.$field
);
9173 // Set classes. The following classes can be used here:
9174 // * oo-ui-fieldLayout-align-left
9175 // * oo-ui-fieldLayout-align-right
9176 // * oo-ui-fieldLayout-align-top
9177 // * oo-ui-fieldLayout-align-inline
9179 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
9181 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
9189 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
9190 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
9191 * is required and is specified before any optional configuration settings.
9193 * Labels can be aligned in one of four ways:
9195 * - **left**: The label is placed before the field-widget and aligned with the left margin.
9196 * A left-alignment is used for forms with many fields.
9197 * - **right**: The label is placed before the field-widget and aligned to the right margin.
9198 * A right-alignment is used for long but familiar forms which users tab through,
9199 * verifying the current field with a quick glance at the label.
9200 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
9201 * that users fill out from top to bottom.
9202 * - **inline**: The label is placed after the field-widget and aligned to the left.
9203 * An inline-alignment is best used with checkboxes or radio buttons.
9205 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
9206 * text is specified.
9209 * // Example of an ActionFieldLayout
9210 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
9211 * new OO.ui.TextInputWidget( {
9212 * placeholder: 'Field widget'
9214 * new OO.ui.ButtonWidget( {
9218 * label: 'An ActionFieldLayout. This label is aligned top',
9220 * help: 'This is help text'
9224 * $( 'body' ).append( actionFieldLayout.$element );
9227 * @extends OO.ui.FieldLayout
9230 * @param {OO.ui.Widget} fieldWidget Field widget
9231 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
9233 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
9234 // Allow passing positional parameters inside the config object
9235 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
9236 config
= fieldWidget
;
9237 fieldWidget
= config
.fieldWidget
;
9238 buttonWidget
= config
.buttonWidget
;
9241 // Parent constructor
9242 OO
.ui
.ActionFieldLayout
.parent
.call( this, fieldWidget
, config
);
9245 this.buttonWidget
= buttonWidget
;
9246 this.$button
= $( '<div>' );
9247 this.$input
= $( '<div>' );
9251 .addClass( 'oo-ui-actionFieldLayout' );
9253 .addClass( 'oo-ui-actionFieldLayout-button' )
9254 .append( this.buttonWidget
.$element
);
9256 .addClass( 'oo-ui-actionFieldLayout-input' )
9257 .append( this.fieldWidget
.$element
);
9259 .append( this.$input
, this.$button
);
9264 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
9267 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
9268 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
9269 * configured with a label as well. For more information and examples,
9270 * please see the [OOjs UI documentation on MediaWiki][1].
9273 * // Example of a fieldset layout
9274 * var input1 = new OO.ui.TextInputWidget( {
9275 * placeholder: 'A text input field'
9278 * var input2 = new OO.ui.TextInputWidget( {
9279 * placeholder: 'A text input field'
9282 * var fieldset = new OO.ui.FieldsetLayout( {
9283 * label: 'Example of a fieldset layout'
9286 * fieldset.addItems( [
9287 * new OO.ui.FieldLayout( input1, {
9288 * label: 'Field One'
9290 * new OO.ui.FieldLayout( input2, {
9291 * label: 'Field Two'
9294 * $( 'body' ).append( fieldset.$element );
9296 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9299 * @extends OO.ui.Layout
9300 * @mixins OO.ui.mixin.IconElement
9301 * @mixins OO.ui.mixin.LabelElement
9302 * @mixins OO.ui.mixin.GroupElement
9305 * @param {Object} [config] Configuration options
9306 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
9308 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
9309 // Configuration initialization
9310 config
= config
|| {};
9312 // Parent constructor
9313 OO
.ui
.FieldsetLayout
.parent
.call( this, config
);
9315 // Mixin constructors
9316 OO
.ui
.mixin
.IconElement
.call( this, config
);
9317 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9318 OO
.ui
.mixin
.GroupElement
.call( this, config
);
9320 if ( config
.help
) {
9321 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
9322 classes
: [ 'oo-ui-fieldsetLayout-help' ],
9327 this.popupButtonWidget
.getPopup().$body
.append(
9329 .text( config
.help
)
9330 .addClass( 'oo-ui-fieldsetLayout-help-content' )
9332 this.$help
= this.popupButtonWidget
.$element
;
9334 this.$help
= $( [] );
9339 .addClass( 'oo-ui-fieldsetLayout' )
9340 .prepend( this.$help
, this.$icon
, this.$label
, this.$group
);
9341 if ( Array
.isArray( config
.items
) ) {
9342 this.addItems( config
.items
);
9348 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
9349 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.IconElement
);
9350 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.LabelElement
);
9351 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.GroupElement
);
9354 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
9355 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
9356 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
9357 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9359 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
9360 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
9361 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
9362 * some fancier controls. Some controls have both regular and InputWidget variants, for example
9363 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
9364 * often have simplified APIs to match the capabilities of HTML forms.
9365 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
9367 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
9368 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9371 * // Example of a form layout that wraps a fieldset layout
9372 * var input1 = new OO.ui.TextInputWidget( {
9373 * placeholder: 'Username'
9375 * var input2 = new OO.ui.TextInputWidget( {
9376 * placeholder: 'Password',
9379 * var submit = new OO.ui.ButtonInputWidget( {
9383 * var fieldset = new OO.ui.FieldsetLayout( {
9384 * label: 'A form layout'
9386 * fieldset.addItems( [
9387 * new OO.ui.FieldLayout( input1, {
9388 * label: 'Username',
9391 * new OO.ui.FieldLayout( input2, {
9392 * label: 'Password',
9395 * new OO.ui.FieldLayout( submit )
9397 * var form = new OO.ui.FormLayout( {
9398 * items: [ fieldset ],
9399 * action: '/api/formhandler',
9402 * $( 'body' ).append( form.$element );
9405 * @extends OO.ui.Layout
9406 * @mixins OO.ui.mixin.GroupElement
9409 * @param {Object} [config] Configuration options
9410 * @cfg {string} [method] HTML form `method` attribute
9411 * @cfg {string} [action] HTML form `action` attribute
9412 * @cfg {string} [enctype] HTML form `enctype` attribute
9413 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
9415 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
9416 // Configuration initialization
9417 config
= config
|| {};
9419 // Parent constructor
9420 OO
.ui
.FormLayout
.parent
.call( this, config
);
9422 // Mixin constructors
9423 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
9426 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
9428 // Make sure the action is safe
9429 if ( config
.action
!== undefined && !OO
.ui
.isSafeUrl( config
.action
) ) {
9430 throw new Error( 'Potentially unsafe action provided: ' + config
.action
);
9435 .addClass( 'oo-ui-formLayout' )
9437 method
: config
.method
,
9438 action
: config
.action
,
9439 enctype
: config
.enctype
9441 if ( Array
.isArray( config
.items
) ) {
9442 this.addItems( config
.items
);
9448 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
9449 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.mixin
.GroupElement
);
9454 * A 'submit' event is emitted when the form is submitted.
9459 /* Static Properties */
9461 OO
.ui
.FormLayout
.static.tagName
= 'form';
9466 * Handle form submit events.
9469 * @param {jQuery.Event} e Submit event
9472 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
9473 if ( this.emit( 'submit' ) ) {
9479 * 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)
9480 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
9483 * var menuLayout = new OO.ui.MenuLayout( {
9486 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9487 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
9488 * select = new OO.ui.SelectWidget( {
9490 * new OO.ui.OptionWidget( {
9494 * new OO.ui.OptionWidget( {
9498 * new OO.ui.OptionWidget( {
9502 * new OO.ui.OptionWidget( {
9507 * } ).on( 'select', function ( item ) {
9508 * menuLayout.setMenuPosition( item.getData() );
9511 * menuLayout.$menu.append(
9512 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
9514 * menuLayout.$content.append(
9515 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
9517 * $( 'body' ).append( menuLayout.$element );
9519 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
9520 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
9521 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
9524 * .oo-ui-menuLayout-menu {
9528 * .oo-ui-menuLayout-content {
9536 * @extends OO.ui.Layout
9539 * @param {Object} [config] Configuration options
9540 * @cfg {boolean} [showMenu=true] Show menu
9541 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
9543 OO
.ui
.MenuLayout
= function OoUiMenuLayout( config
) {
9544 // Configuration initialization
9545 config
= $.extend( {
9547 menuPosition
: 'before'
9550 // Parent constructor
9551 OO
.ui
.MenuLayout
.parent
.call( this, config
);
9556 * @property {jQuery}
9558 this.$menu
= $( '<div>' );
9562 * @property {jQuery}
9564 this.$content
= $( '<div>' );
9568 .addClass( 'oo-ui-menuLayout-menu' );
9569 this.$content
.addClass( 'oo-ui-menuLayout-content' );
9571 .addClass( 'oo-ui-menuLayout' )
9572 .append( this.$content
, this.$menu
);
9573 this.setMenuPosition( config
.menuPosition
);
9574 this.toggleMenu( config
.showMenu
);
9579 OO
.inheritClass( OO
.ui
.MenuLayout
, OO
.ui
.Layout
);
9586 * @param {boolean} showMenu Show menu, omit to toggle
9589 OO
.ui
.MenuLayout
.prototype.toggleMenu = function ( showMenu
) {
9590 showMenu
= showMenu
=== undefined ? !this.showMenu
: !!showMenu
;
9592 if ( this.showMenu
!== showMenu
) {
9593 this.showMenu
= showMenu
;
9595 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu
)
9596 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu
);
9603 * Check if menu is visible
9605 * @return {boolean} Menu is visible
9607 OO
.ui
.MenuLayout
.prototype.isMenuVisible = function () {
9608 return this.showMenu
;
9612 * Set menu position.
9614 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
9615 * @throws {Error} If position value is not supported
9618 OO
.ui
.MenuLayout
.prototype.setMenuPosition = function ( position
) {
9619 this.$element
.removeClass( 'oo-ui-menuLayout-' + this.menuPosition
);
9620 this.menuPosition
= position
;
9621 this.$element
.addClass( 'oo-ui-menuLayout-' + position
);
9627 * Get menu position.
9629 * @return {string} Menu position
9631 OO
.ui
.MenuLayout
.prototype.getMenuPosition = function () {
9632 return this.menuPosition
;
9636 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
9637 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
9638 * through the pages and select which one to display. By default, only one page is
9639 * displayed at a time and the outline is hidden. When a user navigates to a new page,
9640 * the booklet layout automatically focuses on the first focusable element, unless the
9641 * default setting is changed. Optionally, booklets can be configured to show
9642 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
9645 * // Example of a BookletLayout that contains two PageLayouts.
9647 * function PageOneLayout( name, config ) {
9648 * PageOneLayout.parent.call( this, name, config );
9649 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
9651 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
9652 * PageOneLayout.prototype.setupOutlineItem = function () {
9653 * this.outlineItem.setLabel( 'Page One' );
9656 * function PageTwoLayout( name, config ) {
9657 * PageTwoLayout.parent.call( this, name, config );
9658 * this.$element.append( '<p>Second page</p>' );
9660 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
9661 * PageTwoLayout.prototype.setupOutlineItem = function () {
9662 * this.outlineItem.setLabel( 'Page Two' );
9665 * var page1 = new PageOneLayout( 'one' ),
9666 * page2 = new PageTwoLayout( 'two' );
9668 * var booklet = new OO.ui.BookletLayout( {
9672 * booklet.addPages ( [ page1, page2 ] );
9673 * $( 'body' ).append( booklet.$element );
9676 * @extends OO.ui.MenuLayout
9679 * @param {Object} [config] Configuration options
9680 * @cfg {boolean} [continuous=false] Show all pages, one after another
9681 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
9682 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
9683 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
9685 OO
.ui
.BookletLayout
= function OoUiBookletLayout( config
) {
9686 // Configuration initialization
9687 config
= config
|| {};
9689 // Parent constructor
9690 OO
.ui
.BookletLayout
.parent
.call( this, config
);
9693 this.currentPageName
= null;
9695 this.ignoreFocus
= false;
9696 this.stackLayout
= new OO
.ui
.StackLayout( { continuous
: !!config
.continuous
} );
9697 this.$content
.append( this.stackLayout
.$element
);
9698 this.autoFocus
= config
.autoFocus
=== undefined || !!config
.autoFocus
;
9699 this.outlineVisible
= false;
9700 this.outlined
= !!config
.outlined
;
9701 if ( this.outlined
) {
9702 this.editable
= !!config
.editable
;
9703 this.outlineControlsWidget
= null;
9704 this.outlineSelectWidget
= new OO
.ui
.OutlineSelectWidget();
9705 this.outlinePanel
= new OO
.ui
.PanelLayout( { scrollable
: true } );
9706 this.$menu
.append( this.outlinePanel
.$element
);
9707 this.outlineVisible
= true;
9708 if ( this.editable
) {
9709 this.outlineControlsWidget
= new OO
.ui
.OutlineControlsWidget(
9710 this.outlineSelectWidget
9714 this.toggleMenu( this.outlined
);
9717 this.stackLayout
.connect( this, { set: 'onStackLayoutSet' } );
9718 if ( this.outlined
) {
9719 this.outlineSelectWidget
.connect( this, { select
: 'onOutlineSelectWidgetSelect' } );
9721 if ( this.autoFocus
) {
9722 // Event 'focus' does not bubble, but 'focusin' does
9723 this.stackLayout
.$element
.on( 'focusin', this.onStackLayoutFocus
.bind( this ) );
9727 this.$element
.addClass( 'oo-ui-bookletLayout' );
9728 this.stackLayout
.$element
.addClass( 'oo-ui-bookletLayout-stackLayout' );
9729 if ( this.outlined
) {
9730 this.outlinePanel
.$element
9731 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
9732 .append( this.outlineSelectWidget
.$element
);
9733 if ( this.editable
) {
9734 this.outlinePanel
.$element
9735 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
9736 .append( this.outlineControlsWidget
.$element
);
9743 OO
.inheritClass( OO
.ui
.BookletLayout
, OO
.ui
.MenuLayout
);
9748 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
9750 * @param {OO.ui.PageLayout} page Current page
9754 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
9757 * @param {OO.ui.PageLayout[]} page Added pages
9758 * @param {number} index Index pages were added at
9762 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
9763 * {@link #removePages removed} from the booklet.
9766 * @param {OO.ui.PageLayout[]} pages Removed pages
9772 * Handle stack layout focus.
9775 * @param {jQuery.Event} e Focusin event
9777 OO
.ui
.BookletLayout
.prototype.onStackLayoutFocus = function ( e
) {
9780 // Find the page that an element was focused within
9781 $target
= $( e
.target
).closest( '.oo-ui-pageLayout' );
9782 for ( name
in this.pages
) {
9783 // Check for page match, exclude current page to find only page changes
9784 if ( this.pages
[ name
].$element
[ 0 ] === $target
[ 0 ] && name
!== this.currentPageName
) {
9785 this.setPage( name
);
9792 * Handle stack layout set events.
9795 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
9797 OO
.ui
.BookletLayout
.prototype.onStackLayoutSet = function ( page
) {
9800 page
.scrollElementIntoView( { complete: function () {
9801 if ( layout
.autoFocus
) {
9809 * Focus the first input in the current page.
9811 * If no page is selected, the first selectable page will be selected.
9812 * If the focus is already in an element on the current page, nothing will happen.
9813 * @param {number} [itemIndex] A specific item to focus on
9815 OO
.ui
.BookletLayout
.prototype.focus = function ( itemIndex
) {
9817 items
= this.stackLayout
.getItems();
9819 if ( itemIndex
!== undefined && items
[ itemIndex
] ) {
9820 page
= items
[ itemIndex
];
9822 page
= this.stackLayout
.getCurrentItem();
9825 if ( !page
&& this.outlined
) {
9826 this.selectFirstSelectablePage();
9827 page
= this.stackLayout
.getCurrentItem();
9832 // Only change the focus if is not already in the current page
9833 if ( !page
.$element
.find( ':focus' ).length
) {
9834 OO
.ui
.findFocusable( page
.$element
).focus();
9839 * Find the first focusable input in the booklet layout and focus
9842 OO
.ui
.BookletLayout
.prototype.focusFirstFocusable = function () {
9843 OO
.ui
.findFocusable( this.stackLayout
.$element
).focus();
9847 * Handle outline widget select events.
9850 * @param {OO.ui.OptionWidget|null} item Selected item
9852 OO
.ui
.BookletLayout
.prototype.onOutlineSelectWidgetSelect = function ( item
) {
9854 this.setPage( item
.getData() );
9859 * Check if booklet has an outline.
9861 * @return {boolean} Booklet has an outline
9863 OO
.ui
.BookletLayout
.prototype.isOutlined = function () {
9864 return this.outlined
;
9868 * Check if booklet has editing controls.
9870 * @return {boolean} Booklet is editable
9872 OO
.ui
.BookletLayout
.prototype.isEditable = function () {
9873 return this.editable
;
9877 * Check if booklet has a visible outline.
9879 * @return {boolean} Outline is visible
9881 OO
.ui
.BookletLayout
.prototype.isOutlineVisible = function () {
9882 return this.outlined
&& this.outlineVisible
;
9886 * Hide or show the outline.
9888 * @param {boolean} [show] Show outline, omit to invert current state
9891 OO
.ui
.BookletLayout
.prototype.toggleOutline = function ( show
) {
9892 if ( this.outlined
) {
9893 show
= show
=== undefined ? !this.outlineVisible
: !!show
;
9894 this.outlineVisible
= show
;
9895 this.toggleMenu( show
);
9902 * Get the page closest to the specified page.
9904 * @param {OO.ui.PageLayout} page Page to use as a reference point
9905 * @return {OO.ui.PageLayout|null} Page closest to the specified page
9907 OO
.ui
.BookletLayout
.prototype.getClosestPage = function ( page
) {
9908 var next
, prev
, level
,
9909 pages
= this.stackLayout
.getItems(),
9910 index
= pages
.indexOf( page
);
9912 if ( index
!== -1 ) {
9913 next
= pages
[ index
+ 1 ];
9914 prev
= pages
[ index
- 1 ];
9915 // Prefer adjacent pages at the same level
9916 if ( this.outlined
) {
9917 level
= this.outlineSelectWidget
.getItemFromData( page
.getName() ).getLevel();
9920 level
=== this.outlineSelectWidget
.getItemFromData( prev
.getName() ).getLevel()
9926 level
=== this.outlineSelectWidget
.getItemFromData( next
.getName() ).getLevel()
9932 return prev
|| next
|| null;
9936 * Get the outline widget.
9938 * If the booklet is not outlined, the method will return `null`.
9940 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
9942 OO
.ui
.BookletLayout
.prototype.getOutline = function () {
9943 return this.outlineSelectWidget
;
9947 * Get the outline controls widget.
9949 * If the outline is not editable, the method will return `null`.
9951 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
9953 OO
.ui
.BookletLayout
.prototype.getOutlineControls = function () {
9954 return this.outlineControlsWidget
;
9958 * Get a page by its symbolic name.
9960 * @param {string} name Symbolic name of page
9961 * @return {OO.ui.PageLayout|undefined} Page, if found
9963 OO
.ui
.BookletLayout
.prototype.getPage = function ( name
) {
9964 return this.pages
[ name
];
9968 * Get the current page.
9970 * @return {OO.ui.PageLayout|undefined} Current page, if found
9972 OO
.ui
.BookletLayout
.prototype.getCurrentPage = function () {
9973 var name
= this.getCurrentPageName();
9974 return name
? this.getPage( name
) : undefined;
9978 * Get the symbolic name of the current page.
9980 * @return {string|null} Symbolic name of the current page
9982 OO
.ui
.BookletLayout
.prototype.getCurrentPageName = function () {
9983 return this.currentPageName
;
9987 * Add pages to the booklet layout
9989 * When pages are added with the same names as existing pages, the existing pages will be
9990 * automatically removed before the new pages are added.
9992 * @param {OO.ui.PageLayout[]} pages Pages to add
9993 * @param {number} index Index of the insertion point
9997 OO
.ui
.BookletLayout
.prototype.addPages = function ( pages
, index
) {
9998 var i
, len
, name
, page
, item
, currentIndex
,
9999 stackLayoutPages
= this.stackLayout
.getItems(),
10003 // Remove pages with same names
10004 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
10006 name
= page
.getName();
10008 if ( Object
.prototype.hasOwnProperty
.call( this.pages
, name
) ) {
10009 // Correct the insertion index
10010 currentIndex
= stackLayoutPages
.indexOf( this.pages
[ name
] );
10011 if ( currentIndex
!== -1 && currentIndex
+ 1 < index
) {
10014 remove
.push( this.pages
[ name
] );
10017 if ( remove
.length
) {
10018 this.removePages( remove
);
10022 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
10024 name
= page
.getName();
10025 this.pages
[ page
.getName() ] = page
;
10026 if ( this.outlined
) {
10027 item
= new OO
.ui
.OutlineOptionWidget( { data
: name
} );
10028 page
.setOutlineItem( item
);
10029 items
.push( item
);
10033 if ( this.outlined
&& items
.length
) {
10034 this.outlineSelectWidget
.addItems( items
, index
);
10035 this.selectFirstSelectablePage();
10037 this.stackLayout
.addItems( pages
, index
);
10038 this.emit( 'add', pages
, index
);
10044 * Remove the specified pages from the booklet layout.
10046 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
10048 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
10052 OO
.ui
.BookletLayout
.prototype.removePages = function ( pages
) {
10053 var i
, len
, name
, page
,
10056 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
10058 name
= page
.getName();
10059 delete this.pages
[ name
];
10060 if ( this.outlined
) {
10061 items
.push( this.outlineSelectWidget
.getItemFromData( name
) );
10062 page
.setOutlineItem( null );
10065 if ( this.outlined
&& items
.length
) {
10066 this.outlineSelectWidget
.removeItems( items
);
10067 this.selectFirstSelectablePage();
10069 this.stackLayout
.removeItems( pages
);
10070 this.emit( 'remove', pages
);
10076 * Clear all pages from the booklet layout.
10078 * To remove only a subset of pages from the booklet, use the #removePages method.
10083 OO
.ui
.BookletLayout
.prototype.clearPages = function () {
10085 pages
= this.stackLayout
.getItems();
10088 this.currentPageName
= null;
10089 if ( this.outlined
) {
10090 this.outlineSelectWidget
.clearItems();
10091 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
10092 pages
[ i
].setOutlineItem( null );
10095 this.stackLayout
.clearItems();
10097 this.emit( 'remove', pages
);
10103 * Set the current page by symbolic name.
10106 * @param {string} name Symbolic name of page
10108 OO
.ui
.BookletLayout
.prototype.setPage = function ( name
) {
10111 page
= this.pages
[ name
],
10112 previousPage
= this.currentPageName
&& this.pages
[ this.currentPageName
];
10114 if ( name
!== this.currentPageName
) {
10115 if ( this.outlined
) {
10116 selectedItem
= this.outlineSelectWidget
.getSelectedItem();
10117 if ( selectedItem
&& selectedItem
.getData() !== name
) {
10118 this.outlineSelectWidget
.selectItemByData( name
);
10122 if ( previousPage
) {
10123 previousPage
.setActive( false );
10124 // Blur anything focused if the next page doesn't have anything focusable.
10125 // This is not needed if the next page has something focusable (because once it is focused
10126 // this blur happens automatically). If the layout is non-continuous, this check is
10127 // meaningless because the next page is not visible yet and thus can't hold focus.
10130 this.stackLayout
.continuous
&&
10131 OO
.ui
.findFocusable( page
.$element
).length
!== 0
10133 $focused
= previousPage
.$element
.find( ':focus' );
10134 if ( $focused
.length
) {
10135 $focused
[ 0 ].blur();
10139 this.currentPageName
= name
;
10140 page
.setActive( true );
10141 this.stackLayout
.setItem( page
);
10142 if ( !this.stackLayout
.continuous
&& previousPage
) {
10143 // This should not be necessary, since any inputs on the previous page should have been
10144 // blurred when it was hidden, but browsers are not very consistent about this.
10145 $focused
= previousPage
.$element
.find( ':focus' );
10146 if ( $focused
.length
) {
10147 $focused
[ 0 ].blur();
10150 this.emit( 'set', page
);
10156 * Select the first selectable page.
10160 OO
.ui
.BookletLayout
.prototype.selectFirstSelectablePage = function () {
10161 if ( !this.outlineSelectWidget
.getSelectedItem() ) {
10162 this.outlineSelectWidget
.selectItem( this.outlineSelectWidget
.getFirstSelectableItem() );
10169 * IndexLayouts contain {@link OO.ui.CardLayout card layouts} as well as
10170 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the cards and
10171 * select which one to display. By default, only one card is displayed at a time. When a user
10172 * navigates to a new card, the index layout automatically focuses on the first focusable element,
10173 * unless the default setting is changed.
10175 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
10178 * // Example of a IndexLayout that contains two CardLayouts.
10180 * function CardOneLayout( name, config ) {
10181 * CardOneLayout.parent.call( this, name, config );
10182 * this.$element.append( '<p>First card</p>' );
10184 * OO.inheritClass( CardOneLayout, OO.ui.CardLayout );
10185 * CardOneLayout.prototype.setupTabItem = function () {
10186 * this.tabItem.setLabel( 'Card one' );
10189 * var card1 = new CardOneLayout( 'one' ),
10190 * card2 = new CardLayout( 'two', { label: 'Card two' } );
10192 * card2.$element.append( '<p>Second card</p>' );
10194 * var index = new OO.ui.IndexLayout();
10196 * index.addCards ( [ card1, card2 ] );
10197 * $( 'body' ).append( index.$element );
10200 * @extends OO.ui.MenuLayout
10203 * @param {Object} [config] Configuration options
10204 * @cfg {boolean} [continuous=false] Show all cards, one after another
10205 * @cfg {boolean} [expanded=true] Expand the content panel to fill the entire parent element.
10206 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new card is displayed.
10208 OO
.ui
.IndexLayout
= function OoUiIndexLayout( config
) {
10209 // Configuration initialization
10210 config
= $.extend( {}, config
, { menuPosition
: 'top' } );
10212 // Parent constructor
10213 OO
.ui
.IndexLayout
.parent
.call( this, config
);
10216 this.currentCardName
= null;
10218 this.ignoreFocus
= false;
10219 this.stackLayout
= new OO
.ui
.StackLayout( {
10220 continuous
: !!config
.continuous
,
10221 expanded
: config
.expanded
10223 this.$content
.append( this.stackLayout
.$element
);
10224 this.autoFocus
= config
.autoFocus
=== undefined || !!config
.autoFocus
;
10226 this.tabSelectWidget
= new OO
.ui
.TabSelectWidget();
10227 this.tabPanel
= new OO
.ui
.PanelLayout();
10228 this.$menu
.append( this.tabPanel
.$element
);
10230 this.toggleMenu( true );
10233 this.stackLayout
.connect( this, { set: 'onStackLayoutSet' } );
10234 this.tabSelectWidget
.connect( this, { select
: 'onTabSelectWidgetSelect' } );
10235 if ( this.autoFocus
) {
10236 // Event 'focus' does not bubble, but 'focusin' does
10237 this.stackLayout
.$element
.on( 'focusin', this.onStackLayoutFocus
.bind( this ) );
10241 this.$element
.addClass( 'oo-ui-indexLayout' );
10242 this.stackLayout
.$element
.addClass( 'oo-ui-indexLayout-stackLayout' );
10243 this.tabPanel
.$element
10244 .addClass( 'oo-ui-indexLayout-tabPanel' )
10245 .append( this.tabSelectWidget
.$element
);
10250 OO
.inheritClass( OO
.ui
.IndexLayout
, OO
.ui
.MenuLayout
);
10255 * A 'set' event is emitted when a card is {@link #setCard set} to be displayed by the index layout.
10257 * @param {OO.ui.CardLayout} card Current card
10261 * An 'add' event is emitted when cards are {@link #addCards added} to the index layout.
10264 * @param {OO.ui.CardLayout[]} card Added cards
10265 * @param {number} index Index cards were added at
10269 * A 'remove' event is emitted when cards are {@link #clearCards cleared} or
10270 * {@link #removeCards removed} from the index.
10273 * @param {OO.ui.CardLayout[]} cards Removed cards
10279 * Handle stack layout focus.
10282 * @param {jQuery.Event} e Focusin event
10284 OO
.ui
.IndexLayout
.prototype.onStackLayoutFocus = function ( e
) {
10287 // Find the card that an element was focused within
10288 $target
= $( e
.target
).closest( '.oo-ui-cardLayout' );
10289 for ( name
in this.cards
) {
10290 // Check for card match, exclude current card to find only card changes
10291 if ( this.cards
[ name
].$element
[ 0 ] === $target
[ 0 ] && name
!== this.currentCardName
) {
10292 this.setCard( name
);
10299 * Handle stack layout set events.
10302 * @param {OO.ui.PanelLayout|null} card The card panel that is now the current panel
10304 OO
.ui
.IndexLayout
.prototype.onStackLayoutSet = function ( card
) {
10307 card
.scrollElementIntoView( { complete: function () {
10308 if ( layout
.autoFocus
) {
10316 * Focus the first input in the current card.
10318 * If no card is selected, the first selectable card will be selected.
10319 * If the focus is already in an element on the current card, nothing will happen.
10320 * @param {number} [itemIndex] A specific item to focus on
10322 OO
.ui
.IndexLayout
.prototype.focus = function ( itemIndex
) {
10324 items
= this.stackLayout
.getItems();
10326 if ( itemIndex
!== undefined && items
[ itemIndex
] ) {
10327 card
= items
[ itemIndex
];
10329 card
= this.stackLayout
.getCurrentItem();
10333 this.selectFirstSelectableCard();
10334 card
= this.stackLayout
.getCurrentItem();
10339 // Only change the focus if is not already in the current card
10340 if ( !card
.$element
.find( ':focus' ).length
) {
10341 OO
.ui
.findFocusable( card
.$element
).focus();
10346 * Find the first focusable input in the index layout and focus
10349 OO
.ui
.IndexLayout
.prototype.focusFirstFocusable = function () {
10350 OO
.ui
.findFocusable( this.stackLayout
.$element
).focus();
10354 * Handle tab widget select events.
10357 * @param {OO.ui.OptionWidget|null} item Selected item
10359 OO
.ui
.IndexLayout
.prototype.onTabSelectWidgetSelect = function ( item
) {
10361 this.setCard( item
.getData() );
10366 * Get the card closest to the specified card.
10368 * @param {OO.ui.CardLayout} card Card to use as a reference point
10369 * @return {OO.ui.CardLayout|null} Card closest to the specified card
10371 OO
.ui
.IndexLayout
.prototype.getClosestCard = function ( card
) {
10372 var next
, prev
, level
,
10373 cards
= this.stackLayout
.getItems(),
10374 index
= cards
.indexOf( card
);
10376 if ( index
!== -1 ) {
10377 next
= cards
[ index
+ 1 ];
10378 prev
= cards
[ index
- 1 ];
10379 // Prefer adjacent cards at the same level
10380 level
= this.tabSelectWidget
.getItemFromData( card
.getName() ).getLevel();
10383 level
=== this.tabSelectWidget
.getItemFromData( prev
.getName() ).getLevel()
10389 level
=== this.tabSelectWidget
.getItemFromData( next
.getName() ).getLevel()
10394 return prev
|| next
|| null;
10398 * Get the tabs widget.
10400 * @return {OO.ui.TabSelectWidget} Tabs widget
10402 OO
.ui
.IndexLayout
.prototype.getTabs = function () {
10403 return this.tabSelectWidget
;
10407 * Get a card by its symbolic name.
10409 * @param {string} name Symbolic name of card
10410 * @return {OO.ui.CardLayout|undefined} Card, if found
10412 OO
.ui
.IndexLayout
.prototype.getCard = function ( name
) {
10413 return this.cards
[ name
];
10417 * Get the current card.
10419 * @return {OO.ui.CardLayout|undefined} Current card, if found
10421 OO
.ui
.IndexLayout
.prototype.getCurrentCard = function () {
10422 var name
= this.getCurrentCardName();
10423 return name
? this.getCard( name
) : undefined;
10427 * Get the symbolic name of the current card.
10429 * @return {string|null} Symbolic name of the current card
10431 OO
.ui
.IndexLayout
.prototype.getCurrentCardName = function () {
10432 return this.currentCardName
;
10436 * Add cards to the index layout
10438 * When cards are added with the same names as existing cards, the existing cards will be
10439 * automatically removed before the new cards are added.
10441 * @param {OO.ui.CardLayout[]} cards Cards to add
10442 * @param {number} index Index of the insertion point
10446 OO
.ui
.IndexLayout
.prototype.addCards = function ( cards
, index
) {
10447 var i
, len
, name
, card
, item
, currentIndex
,
10448 stackLayoutCards
= this.stackLayout
.getItems(),
10452 // Remove cards with same names
10453 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10455 name
= card
.getName();
10457 if ( Object
.prototype.hasOwnProperty
.call( this.cards
, name
) ) {
10458 // Correct the insertion index
10459 currentIndex
= stackLayoutCards
.indexOf( this.cards
[ name
] );
10460 if ( currentIndex
!== -1 && currentIndex
+ 1 < index
) {
10463 remove
.push( this.cards
[ name
] );
10466 if ( remove
.length
) {
10467 this.removeCards( remove
);
10471 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10473 name
= card
.getName();
10474 this.cards
[ card
.getName() ] = card
;
10475 item
= new OO
.ui
.TabOptionWidget( { data
: name
} );
10476 card
.setTabItem( item
);
10477 items
.push( item
);
10480 if ( items
.length
) {
10481 this.tabSelectWidget
.addItems( items
, index
);
10482 this.selectFirstSelectableCard();
10484 this.stackLayout
.addItems( cards
, index
);
10485 this.emit( 'add', cards
, index
);
10491 * Remove the specified cards from the index layout.
10493 * To remove all cards from the index, you may wish to use the #clearCards method instead.
10495 * @param {OO.ui.CardLayout[]} cards An array of cards to remove
10499 OO
.ui
.IndexLayout
.prototype.removeCards = function ( cards
) {
10500 var i
, len
, name
, card
,
10503 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10505 name
= card
.getName();
10506 delete this.cards
[ name
];
10507 items
.push( this.tabSelectWidget
.getItemFromData( name
) );
10508 card
.setTabItem( null );
10510 if ( items
.length
) {
10511 this.tabSelectWidget
.removeItems( items
);
10512 this.selectFirstSelectableCard();
10514 this.stackLayout
.removeItems( cards
);
10515 this.emit( 'remove', cards
);
10521 * Clear all cards from the index layout.
10523 * To remove only a subset of cards from the index, use the #removeCards method.
10528 OO
.ui
.IndexLayout
.prototype.clearCards = function () {
10530 cards
= this.stackLayout
.getItems();
10533 this.currentCardName
= null;
10534 this.tabSelectWidget
.clearItems();
10535 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
10536 cards
[ i
].setTabItem( null );
10538 this.stackLayout
.clearItems();
10540 this.emit( 'remove', cards
);
10546 * Set the current card by symbolic name.
10549 * @param {string} name Symbolic name of card
10551 OO
.ui
.IndexLayout
.prototype.setCard = function ( name
) {
10554 card
= this.cards
[ name
],
10555 previousCard
= this.currentCardName
&& this.cards
[ this.currentCardName
];
10557 if ( name
!== this.currentCardName
) {
10558 selectedItem
= this.tabSelectWidget
.getSelectedItem();
10559 if ( selectedItem
&& selectedItem
.getData() !== name
) {
10560 this.tabSelectWidget
.selectItemByData( name
);
10563 if ( previousCard
) {
10564 previousCard
.setActive( false );
10565 // Blur anything focused if the next card doesn't have anything focusable.
10566 // This is not needed if the next card has something focusable (because once it is focused
10567 // this blur happens automatically). If the layout is non-continuous, this check is
10568 // meaningless because the next card is not visible yet and thus can't hold focus.
10571 this.stackLayout
.continuous
&&
10572 OO
.ui
.findFocusable( card
.$element
).length
!== 0
10574 $focused
= previousCard
.$element
.find( ':focus' );
10575 if ( $focused
.length
) {
10576 $focused
[ 0 ].blur();
10580 this.currentCardName
= name
;
10581 card
.setActive( true );
10582 this.stackLayout
.setItem( card
);
10583 if ( !this.stackLayout
.continuous
&& previousCard
) {
10584 // This should not be necessary, since any inputs on the previous card should have been
10585 // blurred when it was hidden, but browsers are not very consistent about this.
10586 $focused
= previousCard
.$element
.find( ':focus' );
10587 if ( $focused
.length
) {
10588 $focused
[ 0 ].blur();
10591 this.emit( 'set', card
);
10597 * Select the first selectable card.
10601 OO
.ui
.IndexLayout
.prototype.selectFirstSelectableCard = function () {
10602 if ( !this.tabSelectWidget
.getSelectedItem() ) {
10603 this.tabSelectWidget
.selectItem( this.tabSelectWidget
.getFirstSelectableItem() );
10610 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
10611 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
10614 * // Example of a panel layout
10615 * var panel = new OO.ui.PanelLayout( {
10619 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
10621 * $( 'body' ).append( panel.$element );
10624 * @extends OO.ui.Layout
10627 * @param {Object} [config] Configuration options
10628 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
10629 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
10630 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
10631 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
10633 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
10634 // Configuration initialization
10635 config
= $.extend( {
10642 // Parent constructor
10643 OO
.ui
.PanelLayout
.parent
.call( this, config
);
10646 this.$element
.addClass( 'oo-ui-panelLayout' );
10647 if ( config
.scrollable
) {
10648 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
10650 if ( config
.padded
) {
10651 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
10653 if ( config
.expanded
) {
10654 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
10656 if ( config
.framed
) {
10657 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
10663 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
10666 * CardLayouts are used within {@link OO.ui.IndexLayout index layouts} to create cards that users can select and display
10667 * from the index's optional {@link OO.ui.TabSelectWidget tab} navigation. Cards are usually not instantiated directly,
10668 * rather extended to include the required content and functionality.
10670 * Each card must have a unique symbolic name, which is passed to the constructor. In addition, the card's tab
10671 * item is customized (with a label) using the #setupTabItem method. See
10672 * {@link OO.ui.IndexLayout IndexLayout} for an example.
10675 * @extends OO.ui.PanelLayout
10678 * @param {string} name Unique symbolic name of card
10679 * @param {Object} [config] Configuration options
10680 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] Label for card's tab
10682 OO
.ui
.CardLayout
= function OoUiCardLayout( name
, config
) {
10683 // Allow passing positional parameters inside the config object
10684 if ( OO
.isPlainObject( name
) && config
=== undefined ) {
10686 name
= config
.name
;
10689 // Configuration initialization
10690 config
= $.extend( { scrollable
: true }, config
);
10692 // Parent constructor
10693 OO
.ui
.CardLayout
.parent
.call( this, config
);
10697 this.label
= config
.label
;
10698 this.tabItem
= null;
10699 this.active
= false;
10702 this.$element
.addClass( 'oo-ui-cardLayout' );
10707 OO
.inheritClass( OO
.ui
.CardLayout
, OO
.ui
.PanelLayout
);
10712 * An 'active' event is emitted when the card becomes active. Cards become active when they are
10713 * shown in a index layout that is configured to display only one card at a time.
10716 * @param {boolean} active Card is active
10722 * Get the symbolic name of the card.
10724 * @return {string} Symbolic name of card
10726 OO
.ui
.CardLayout
.prototype.getName = function () {
10731 * Check if card is active.
10733 * Cards become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to display
10734 * only one card at a time. Additional CSS is applied to the card's tab item to reflect the active state.
10736 * @return {boolean} Card is active
10738 OO
.ui
.CardLayout
.prototype.isActive = function () {
10739 return this.active
;
10745 * The tab item allows users to access the card from the index's tab
10746 * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
10748 * @return {OO.ui.TabOptionWidget|null} Tab option widget
10750 OO
.ui
.CardLayout
.prototype.getTabItem = function () {
10751 return this.tabItem
;
10755 * Set or unset the tab item.
10757 * Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
10758 * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
10759 * level), use #setupTabItem instead of this method.
10761 * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
10764 OO
.ui
.CardLayout
.prototype.setTabItem = function ( tabItem
) {
10765 this.tabItem
= tabItem
|| null;
10767 this.setupTabItem();
10773 * Set up the tab item.
10775 * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
10776 * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
10777 * the #setTabItem method instead.
10779 * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
10782 OO
.ui
.CardLayout
.prototype.setupTabItem = function () {
10783 if ( this.label
) {
10784 this.tabItem
.setLabel( this.label
);
10790 * Set the card to its 'active' state.
10792 * Cards become active when they are shown in a index layout that is configured to display only one card at a time. Additional
10793 * CSS is applied to the tab item to reflect the card's active state. Outside of the index
10794 * context, setting the active state on a card does nothing.
10796 * @param {boolean} value Card is active
10799 OO
.ui
.CardLayout
.prototype.setActive = function ( active
) {
10802 if ( active
!== this.active
) {
10803 this.active
= active
;
10804 this.$element
.toggleClass( 'oo-ui-cardLayout-active', this.active
);
10805 this.emit( 'active', this.active
);
10810 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
10811 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
10812 * rather extended to include the required content and functionality.
10814 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
10815 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
10816 * {@link OO.ui.BookletLayout BookletLayout} for an example.
10819 * @extends OO.ui.PanelLayout
10822 * @param {string} name Unique symbolic name of page
10823 * @param {Object} [config] Configuration options
10825 OO
.ui
.PageLayout
= function OoUiPageLayout( name
, config
) {
10826 // Allow passing positional parameters inside the config object
10827 if ( OO
.isPlainObject( name
) && config
=== undefined ) {
10829 name
= config
.name
;
10832 // Configuration initialization
10833 config
= $.extend( { scrollable
: true }, config
);
10835 // Parent constructor
10836 OO
.ui
.PageLayout
.parent
.call( this, config
);
10840 this.outlineItem
= null;
10841 this.active
= false;
10844 this.$element
.addClass( 'oo-ui-pageLayout' );
10849 OO
.inheritClass( OO
.ui
.PageLayout
, OO
.ui
.PanelLayout
);
10854 * An 'active' event is emitted when the page becomes active. Pages become active when they are
10855 * shown in a booklet layout that is configured to display only one page at a time.
10858 * @param {boolean} active Page is active
10864 * Get the symbolic name of the page.
10866 * @return {string} Symbolic name of page
10868 OO
.ui
.PageLayout
.prototype.getName = function () {
10873 * Check if page is active.
10875 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
10876 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
10878 * @return {boolean} Page is active
10880 OO
.ui
.PageLayout
.prototype.isActive = function () {
10881 return this.active
;
10885 * Get outline item.
10887 * The outline item allows users to access the page from the booklet's outline
10888 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
10890 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
10892 OO
.ui
.PageLayout
.prototype.getOutlineItem = function () {
10893 return this.outlineItem
;
10897 * Set or unset the outline item.
10899 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
10900 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
10901 * level), use #setupOutlineItem instead of this method.
10903 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
10906 OO
.ui
.PageLayout
.prototype.setOutlineItem = function ( outlineItem
) {
10907 this.outlineItem
= outlineItem
|| null;
10908 if ( outlineItem
) {
10909 this.setupOutlineItem();
10915 * Set up the outline item.
10917 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
10918 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
10919 * the #setOutlineItem method instead.
10921 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
10924 OO
.ui
.PageLayout
.prototype.setupOutlineItem = function () {
10929 * Set the page to its 'active' state.
10931 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
10932 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
10933 * context, setting the active state on a page does nothing.
10935 * @param {boolean} value Page is active
10938 OO
.ui
.PageLayout
.prototype.setActive = function ( active
) {
10941 if ( active
!== this.active
) {
10942 this.active
= active
;
10943 this.$element
.toggleClass( 'oo-ui-pageLayout-active', active
);
10944 this.emit( 'active', this.active
);
10949 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
10950 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
10951 * by setting the #continuous option to 'true'.
10954 * // A stack layout with two panels, configured to be displayed continously
10955 * var myStack = new OO.ui.StackLayout( {
10957 * new OO.ui.PanelLayout( {
10958 * $content: $( '<p>Panel One</p>' ),
10962 * new OO.ui.PanelLayout( {
10963 * $content: $( '<p>Panel Two</p>' ),
10970 * $( 'body' ).append( myStack.$element );
10973 * @extends OO.ui.PanelLayout
10974 * @mixins OO.ui.mixin.GroupElement
10977 * @param {Object} [config] Configuration options
10978 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
10979 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
10981 OO
.ui
.StackLayout
= function OoUiStackLayout( config
) {
10982 // Configuration initialization
10983 config
= $.extend( { scrollable
: true }, config
);
10985 // Parent constructor
10986 OO
.ui
.StackLayout
.parent
.call( this, config
);
10988 // Mixin constructors
10989 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
10992 this.currentItem
= null;
10993 this.continuous
= !!config
.continuous
;
10996 this.$element
.addClass( 'oo-ui-stackLayout' );
10997 if ( this.continuous
) {
10998 this.$element
.addClass( 'oo-ui-stackLayout-continuous' );
11000 if ( Array
.isArray( config
.items
) ) {
11001 this.addItems( config
.items
);
11007 OO
.inheritClass( OO
.ui
.StackLayout
, OO
.ui
.PanelLayout
);
11008 OO
.mixinClass( OO
.ui
.StackLayout
, OO
.ui
.mixin
.GroupElement
);
11013 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
11014 * {@link #clearItems cleared} or {@link #setItem displayed}.
11017 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
11023 * Get the current panel.
11025 * @return {OO.ui.Layout|null}
11027 OO
.ui
.StackLayout
.prototype.getCurrentItem = function () {
11028 return this.currentItem
;
11032 * Unset the current item.
11035 * @param {OO.ui.StackLayout} layout
11038 OO
.ui
.StackLayout
.prototype.unsetCurrentItem = function () {
11039 var prevItem
= this.currentItem
;
11040 if ( prevItem
=== null ) {
11044 this.currentItem
= null;
11045 this.emit( 'set', null );
11049 * Add panel layouts to the stack layout.
11051 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
11052 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
11055 * @param {OO.ui.Layout[]} items Panels to add
11056 * @param {number} [index] Index of the insertion point
11059 OO
.ui
.StackLayout
.prototype.addItems = function ( items
, index
) {
11060 // Update the visibility
11061 this.updateHiddenState( items
, this.currentItem
);
11064 OO
.ui
.mixin
.GroupElement
.prototype.addItems
.call( this, items
, index
);
11066 if ( !this.currentItem
&& items
.length
) {
11067 this.setItem( items
[ 0 ] );
11074 * Remove the specified panels from the stack layout.
11076 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
11077 * you may wish to use the #clearItems method instead.
11079 * @param {OO.ui.Layout[]} items Panels to remove
11083 OO
.ui
.StackLayout
.prototype.removeItems = function ( items
) {
11085 OO
.ui
.mixin
.GroupElement
.prototype.removeItems
.call( this, items
);
11087 if ( items
.indexOf( this.currentItem
) !== -1 ) {
11088 if ( this.items
.length
) {
11089 this.setItem( this.items
[ 0 ] );
11091 this.unsetCurrentItem();
11099 * Clear all panels from the stack layout.
11101 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
11102 * a subset of panels, use the #removeItems method.
11107 OO
.ui
.StackLayout
.prototype.clearItems = function () {
11108 this.unsetCurrentItem();
11109 OO
.ui
.mixin
.GroupElement
.prototype.clearItems
.call( this );
11115 * Show the specified panel.
11117 * If another panel is currently displayed, it will be hidden.
11119 * @param {OO.ui.Layout} item Panel to show
11123 OO
.ui
.StackLayout
.prototype.setItem = function ( item
) {
11124 if ( item
!== this.currentItem
) {
11125 this.updateHiddenState( this.items
, item
);
11127 if ( this.items
.indexOf( item
) !== -1 ) {
11128 this.currentItem
= item
;
11129 this.emit( 'set', item
);
11131 this.unsetCurrentItem();
11139 * Update the visibility of all items in case of non-continuous view.
11141 * Ensure all items are hidden except for the selected one.
11142 * This method does nothing when the stack is continuous.
11145 * @param {OO.ui.Layout[]} items Item list iterate over
11146 * @param {OO.ui.Layout} [selectedItem] Selected item to show
11148 OO
.ui
.StackLayout
.prototype.updateHiddenState = function ( items
, selectedItem
) {
11151 if ( !this.continuous
) {
11152 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
11153 if ( !selectedItem
|| selectedItem
!== items
[ i
] ) {
11154 items
[ i
].$element
.addClass( 'oo-ui-element-hidden' );
11157 if ( selectedItem
) {
11158 selectedItem
.$element
.removeClass( 'oo-ui-element-hidden' );
11164 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
11165 * items), with small margins between them. Convenient when you need to put a number of block-level
11166 * widgets on a single line next to each other.
11168 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
11171 * // HorizontalLayout with a text input and a label
11172 * var layout = new OO.ui.HorizontalLayout( {
11174 * new OO.ui.LabelWidget( { label: 'Label' } ),
11175 * new OO.ui.TextInputWidget( { value: 'Text' } )
11178 * $( 'body' ).append( layout.$element );
11181 * @extends OO.ui.Layout
11182 * @mixins OO.ui.mixin.GroupElement
11185 * @param {Object} [config] Configuration options
11186 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
11188 OO
.ui
.HorizontalLayout
= function OoUiHorizontalLayout( config
) {
11189 // Configuration initialization
11190 config
= config
|| {};
11192 // Parent constructor
11193 OO
.ui
.HorizontalLayout
.parent
.call( this, config
);
11195 // Mixin constructors
11196 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
11199 this.$element
.addClass( 'oo-ui-horizontalLayout' );
11200 if ( Array
.isArray( config
.items
) ) {
11201 this.addItems( config
.items
);
11207 OO
.inheritClass( OO
.ui
.HorizontalLayout
, OO
.ui
.Layout
);
11208 OO
.mixinClass( OO
.ui
.HorizontalLayout
, OO
.ui
.mixin
.GroupElement
);
11211 * BarToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11212 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11213 * and {@link OO.ui.ListToolGroup ListToolGroup}). The {@link OO.ui.Tool tools} in a BarToolGroup are
11214 * displayed by icon in a single row. The title of the tool is displayed when users move the mouse over
11217 * BarToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar is
11221 * // Example of a BarToolGroup with two tools
11222 * var toolFactory = new OO.ui.ToolFactory();
11223 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11224 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11226 * // We will be placing status text in this element when tools are used
11227 * var $area = $( '<p>' ).text( 'Example of a BarToolGroup with two tools.' );
11229 * // Define the tools that we're going to place in our toolbar
11231 * // Create a class inheriting from OO.ui.Tool
11232 * function PictureTool() {
11233 * PictureTool.parent.apply( this, arguments );
11235 * OO.inheritClass( PictureTool, OO.ui.Tool );
11236 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
11237 * // of 'icon' and 'title' (displayed icon and text).
11238 * PictureTool.static.name = 'picture';
11239 * PictureTool.static.icon = 'picture';
11240 * PictureTool.static.title = 'Insert picture';
11241 * // Defines the action that will happen when this tool is selected (clicked).
11242 * PictureTool.prototype.onSelect = function () {
11243 * $area.text( 'Picture tool clicked!' );
11244 * // Never display this tool as "active" (selected).
11245 * this.setActive( false );
11247 * // Make this tool available in our toolFactory and thus our toolbar
11248 * toolFactory.register( PictureTool );
11250 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
11251 * // little popup window (a PopupWidget).
11252 * function HelpTool( toolGroup, config ) {
11253 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11258 * this.popup.$body.append( '<p>I am helpful!</p>' );
11260 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11261 * HelpTool.static.name = 'help';
11262 * HelpTool.static.icon = 'help';
11263 * HelpTool.static.title = 'Help';
11264 * toolFactory.register( HelpTool );
11266 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11267 * // used once (but not all defined tools must be used).
11270 * // 'bar' tool groups display tools by icon only
11272 * include: [ 'picture', 'help' ]
11276 * // Create some UI around the toolbar and place it in the document
11277 * var frame = new OO.ui.PanelLayout( {
11281 * var contentFrame = new OO.ui.PanelLayout( {
11285 * frame.$element.append(
11286 * toolbar.$element,
11287 * contentFrame.$element.append( $area )
11289 * $( 'body' ).append( frame.$element );
11291 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11293 * toolbar.initialize();
11295 * For more information about how to add tools to a bar tool group, please see {@link OO.ui.ToolGroup toolgroup}.
11296 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11298 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11301 * @extends OO.ui.ToolGroup
11304 * @param {OO.ui.Toolbar} toolbar
11305 * @param {Object} [config] Configuration options
11307 OO
.ui
.BarToolGroup
= function OoUiBarToolGroup( toolbar
, config
) {
11308 // Allow passing positional parameters inside the config object
11309 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11311 toolbar
= config
.toolbar
;
11314 // Parent constructor
11315 OO
.ui
.BarToolGroup
.parent
.call( this, toolbar
, config
);
11318 this.$element
.addClass( 'oo-ui-barToolGroup' );
11323 OO
.inheritClass( OO
.ui
.BarToolGroup
, OO
.ui
.ToolGroup
);
11325 /* Static Properties */
11327 OO
.ui
.BarToolGroup
.static.titleTooltips
= true;
11329 OO
.ui
.BarToolGroup
.static.accelTooltips
= true;
11331 OO
.ui
.BarToolGroup
.static.name
= 'bar';
11334 * PopupToolGroup is an abstract base class used by both {@link OO.ui.MenuToolGroup MenuToolGroup}
11335 * and {@link OO.ui.ListToolGroup ListToolGroup} to provide a popup--an overlaid menu or list of tools with an
11336 * optional icon and label. This class can be used for other base classes that also use this functionality.
11340 * @extends OO.ui.ToolGroup
11341 * @mixins OO.ui.mixin.IconElement
11342 * @mixins OO.ui.mixin.IndicatorElement
11343 * @mixins OO.ui.mixin.LabelElement
11344 * @mixins OO.ui.mixin.TitledElement
11345 * @mixins OO.ui.mixin.ClippableElement
11346 * @mixins OO.ui.mixin.TabIndexedElement
11349 * @param {OO.ui.Toolbar} toolbar
11350 * @param {Object} [config] Configuration options
11351 * @cfg {string} [header] Text to display at the top of the popup
11353 OO
.ui
.PopupToolGroup
= function OoUiPopupToolGroup( toolbar
, config
) {
11354 // Allow passing positional parameters inside the config object
11355 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11357 toolbar
= config
.toolbar
;
11360 // Configuration initialization
11361 config
= config
|| {};
11363 // Parent constructor
11364 OO
.ui
.PopupToolGroup
.parent
.call( this, toolbar
, config
);
11367 this.active
= false;
11368 this.dragging
= false;
11369 this.onBlurHandler
= this.onBlur
.bind( this );
11370 this.$handle
= $( '<span>' );
11372 // Mixin constructors
11373 OO
.ui
.mixin
.IconElement
.call( this, config
);
11374 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
11375 OO
.ui
.mixin
.LabelElement
.call( this, config
);
11376 OO
.ui
.mixin
.TitledElement
.call( this, config
);
11377 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
11378 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
11382 keydown
: this.onHandleMouseKeyDown
.bind( this ),
11383 keyup
: this.onHandleMouseKeyUp
.bind( this ),
11384 mousedown
: this.onHandleMouseKeyDown
.bind( this ),
11385 mouseup
: this.onHandleMouseKeyUp
.bind( this )
11390 .addClass( 'oo-ui-popupToolGroup-handle' )
11391 .append( this.$icon
, this.$label
, this.$indicator
);
11392 // If the pop-up should have a header, add it to the top of the toolGroup.
11393 // Note: If this feature is useful for other widgets, we could abstract it into an
11394 // OO.ui.HeaderedElement mixin constructor.
11395 if ( config
.header
!== undefined ) {
11397 .prepend( $( '<span>' )
11398 .addClass( 'oo-ui-popupToolGroup-header' )
11399 .text( config
.header
)
11403 .addClass( 'oo-ui-popupToolGroup' )
11404 .prepend( this.$handle
);
11409 OO
.inheritClass( OO
.ui
.PopupToolGroup
, OO
.ui
.ToolGroup
);
11410 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.IconElement
);
11411 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.IndicatorElement
);
11412 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.LabelElement
);
11413 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.TitledElement
);
11414 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.ClippableElement
);
11415 OO
.mixinClass( OO
.ui
.PopupToolGroup
, OO
.ui
.mixin
.TabIndexedElement
);
11422 OO
.ui
.PopupToolGroup
.prototype.setDisabled = function () {
11424 OO
.ui
.PopupToolGroup
.parent
.prototype.setDisabled
.apply( this, arguments
);
11426 if ( this.isDisabled() && this.isElementAttached() ) {
11427 this.setActive( false );
11432 * Handle focus being lost.
11434 * The event is actually generated from a mouseup/keyup, so it is not a normal blur event object.
11437 * @param {jQuery.Event} e Mouse up or key up event
11439 OO
.ui
.PopupToolGroup
.prototype.onBlur = function ( e
) {
11440 // Only deactivate when clicking outside the dropdown element
11441 if ( $( e
.target
).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element
[ 0 ] ) {
11442 this.setActive( false );
11449 OO
.ui
.PopupToolGroup
.prototype.onMouseKeyUp = function ( e
) {
11450 // Only close toolgroup when a tool was actually selected
11452 !this.isDisabled() && this.pressed
&& this.pressed
=== this.getTargetTool( e
) &&
11453 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11455 this.setActive( false );
11457 return OO
.ui
.PopupToolGroup
.parent
.prototype.onMouseKeyUp
.call( this, e
);
11461 * Handle mouse up and key up events.
11464 * @param {jQuery.Event} e Mouse up or key up event
11466 OO
.ui
.PopupToolGroup
.prototype.onHandleMouseKeyUp = function ( e
) {
11468 !this.isDisabled() &&
11469 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11476 * Handle mouse down and key down events.
11479 * @param {jQuery.Event} e Mouse down or key down event
11481 OO
.ui
.PopupToolGroup
.prototype.onHandleMouseKeyDown = function ( e
) {
11483 !this.isDisabled() &&
11484 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11486 this.setActive( !this.active
);
11492 * Switch into 'active' mode.
11494 * When active, the popup is visible. A mouseup event anywhere in the document will trigger
11497 OO
.ui
.PopupToolGroup
.prototype.setActive = function ( value
) {
11498 var containerWidth
, containerLeft
;
11500 if ( this.active
!== value
) {
11501 this.active
= value
;
11503 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler
);
11504 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler
);
11506 this.$clippable
.css( 'left', '' );
11507 // Try anchoring the popup to the left first
11508 this.$element
.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
11509 this.toggleClipping( true );
11510 if ( this.isClippedHorizontally() ) {
11511 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
11512 this.toggleClipping( false );
11514 .removeClass( 'oo-ui-popupToolGroup-left' )
11515 .addClass( 'oo-ui-popupToolGroup-right' );
11516 this.toggleClipping( true );
11518 if ( this.isClippedHorizontally() ) {
11519 // Anchoring to the right also caused the popup to clip, so just make it fill the container
11520 containerWidth
= this.$clippableScrollableContainer
.width();
11521 containerLeft
= this.$clippableScrollableContainer
.offset().left
;
11523 this.toggleClipping( false );
11524 this.$element
.removeClass( 'oo-ui-popupToolGroup-right' );
11526 this.$clippable
.css( {
11527 left
: -( this.$element
.offset().left
- containerLeft
),
11528 width
: containerWidth
11532 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup', this.onBlurHandler
);
11533 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'keyup', this.onBlurHandler
);
11534 this.$element
.removeClass(
11535 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
11537 this.toggleClipping( false );
11543 * ListToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11544 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup}
11545 * and {@link OO.ui.BarToolGroup BarToolGroup}). The {@link OO.ui.Tool tools} in a ListToolGroup are displayed
11546 * by label in a dropdown menu. The title of the tool is used as the label text. The menu itself can be configured
11547 * with a label, icon, indicator, header, and title.
11549 * ListToolGroups can be configured to be expanded and collapsed. Collapsed lists will have a ‘More’ option that
11550 * users can select to see the full list of tools. If a collapsed toolgroup is expanded, a ‘Fewer’ option permits
11551 * users to collapse the list again.
11553 * ListToolGroups are created by a {@link OO.ui.ToolGroupFactory toolgroup factory} when the toolbar is set up. The factory
11554 * requires the ListToolGroup's symbolic name, 'list', which is specified along with the other configurations. For more
11555 * information about how to add tools to a ListToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11558 * // Example of a ListToolGroup
11559 * var toolFactory = new OO.ui.ToolFactory();
11560 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11561 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11563 * // Configure and register two tools
11564 * function SettingsTool() {
11565 * SettingsTool.parent.apply( this, arguments );
11567 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11568 * SettingsTool.static.name = 'settings';
11569 * SettingsTool.static.icon = 'settings';
11570 * SettingsTool.static.title = 'Change settings';
11571 * SettingsTool.prototype.onSelect = function () {
11572 * this.setActive( false );
11574 * toolFactory.register( SettingsTool );
11575 * // Register two more tools, nothing interesting here
11576 * function StuffTool() {
11577 * StuffTool.parent.apply( this, arguments );
11579 * OO.inheritClass( StuffTool, OO.ui.Tool );
11580 * StuffTool.static.name = 'stuff';
11581 * StuffTool.static.icon = 'ellipsis';
11582 * StuffTool.static.title = 'Change the world';
11583 * StuffTool.prototype.onSelect = function () {
11584 * this.setActive( false );
11586 * toolFactory.register( StuffTool );
11589 * // Configurations for list toolgroup.
11591 * label: 'ListToolGroup',
11592 * indicator: 'down',
11594 * title: 'This is the title, displayed when user moves the mouse over the list toolgroup',
11595 * header: 'This is the header',
11596 * include: [ 'settings', 'stuff' ],
11597 * allowCollapse: ['stuff']
11601 * // Create some UI around the toolbar and place it in the document
11602 * var frame = new OO.ui.PanelLayout( {
11606 * frame.$element.append(
11609 * $( 'body' ).append( frame.$element );
11610 * // Build the toolbar. This must be done after the toolbar has been appended to the document.
11611 * toolbar.initialize();
11613 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1].
11615 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11618 * @extends OO.ui.PopupToolGroup
11621 * @param {OO.ui.Toolbar} toolbar
11622 * @param {Object} [config] Configuration options
11623 * @cfg {Array} [allowCollapse] Allow the specified tools to be collapsed. By default, collapsible tools
11624 * will only be displayed if users click the ‘More’ option displayed at the bottom of the list. If
11625 * the list is expanded, a ‘Fewer’ option permits users to collapse the list again. Any tools that
11626 * are included in the toolgroup, but are not designated as collapsible, will always be displayed.
11627 * To open a collapsible list in its expanded state, set #expanded to 'true'.
11628 * @cfg {Array} [forceExpand] Expand the specified tools. All other tools will be designated as collapsible.
11629 * Unless #expanded is set to true, the collapsible tools will be collapsed when the list is first opened.
11630 * @cfg {boolean} [expanded=false] Expand collapsible tools. This config is only relevant if tools have
11631 * been designated as collapsible. When expanded is set to true, all tools in the group will be displayed
11632 * when the list is first opened. Users can collapse the list with a ‘Fewer’ option at the bottom.
11634 OO
.ui
.ListToolGroup
= function OoUiListToolGroup( toolbar
, config
) {
11635 // Allow passing positional parameters inside the config object
11636 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11638 toolbar
= config
.toolbar
;
11641 // Configuration initialization
11642 config
= config
|| {};
11644 // Properties (must be set before parent constructor, which calls #populate)
11645 this.allowCollapse
= config
.allowCollapse
;
11646 this.forceExpand
= config
.forceExpand
;
11647 this.expanded
= config
.expanded
!== undefined ? config
.expanded
: false;
11648 this.collapsibleTools
= [];
11650 // Parent constructor
11651 OO
.ui
.ListToolGroup
.parent
.call( this, toolbar
, config
);
11654 this.$element
.addClass( 'oo-ui-listToolGroup' );
11659 OO
.inheritClass( OO
.ui
.ListToolGroup
, OO
.ui
.PopupToolGroup
);
11661 /* Static Properties */
11663 OO
.ui
.ListToolGroup
.static.name
= 'list';
11670 OO
.ui
.ListToolGroup
.prototype.populate = function () {
11671 var i
, len
, allowCollapse
= [];
11673 OO
.ui
.ListToolGroup
.parent
.prototype.populate
.call( this );
11675 // Update the list of collapsible tools
11676 if ( this.allowCollapse
!== undefined ) {
11677 allowCollapse
= this.allowCollapse
;
11678 } else if ( this.forceExpand
!== undefined ) {
11679 allowCollapse
= OO
.simpleArrayDifference( Object
.keys( this.tools
), this.forceExpand
);
11682 this.collapsibleTools
= [];
11683 for ( i
= 0, len
= allowCollapse
.length
; i
< len
; i
++ ) {
11684 if ( this.tools
[ allowCollapse
[ i
] ] !== undefined ) {
11685 this.collapsibleTools
.push( this.tools
[ allowCollapse
[ i
] ] );
11689 // Keep at the end, even when tools are added
11690 this.$group
.append( this.getExpandCollapseTool().$element
);
11692 this.getExpandCollapseTool().toggle( this.collapsibleTools
.length
!== 0 );
11693 this.updateCollapsibleState();
11696 OO
.ui
.ListToolGroup
.prototype.getExpandCollapseTool = function () {
11697 var ExpandCollapseTool
;
11698 if ( this.expandCollapseTool
=== undefined ) {
11699 ExpandCollapseTool = function () {
11700 ExpandCollapseTool
.parent
.apply( this, arguments
);
11703 OO
.inheritClass( ExpandCollapseTool
, OO
.ui
.Tool
);
11705 ExpandCollapseTool
.prototype.onSelect = function () {
11706 this.toolGroup
.expanded
= !this.toolGroup
.expanded
;
11707 this.toolGroup
.updateCollapsibleState();
11708 this.setActive( false );
11710 ExpandCollapseTool
.prototype.onUpdateState = function () {
11711 // Do nothing. Tool interface requires an implementation of this function.
11714 ExpandCollapseTool
.static.name
= 'more-fewer';
11716 this.expandCollapseTool
= new ExpandCollapseTool( this );
11718 return this.expandCollapseTool
;
11724 OO
.ui
.ListToolGroup
.prototype.onMouseKeyUp = function ( e
) {
11725 // Do not close the popup when the user wants to show more/fewer tools
11727 $( e
.target
).closest( '.oo-ui-tool-name-more-fewer' ).length
&&
11728 ( e
.which
=== 1 || e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
11730 // HACK: Prevent the popup list from being hidden. Skip the PopupToolGroup implementation (which
11731 // hides the popup list when a tool is selected) and call ToolGroup's implementation directly.
11732 return OO
.ui
.ListToolGroup
.parent
.parent
.prototype.onMouseKeyUp
.call( this, e
);
11734 return OO
.ui
.ListToolGroup
.parent
.prototype.onMouseKeyUp
.call( this, e
);
11738 OO
.ui
.ListToolGroup
.prototype.updateCollapsibleState = function () {
11741 this.getExpandCollapseTool()
11742 .setIcon( this.expanded
? 'collapse' : 'expand' )
11743 .setTitle( OO
.ui
.msg( this.expanded
? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
11745 for ( i
= 0, len
= this.collapsibleTools
.length
; i
< len
; i
++ ) {
11746 this.collapsibleTools
[ i
].toggle( this.expanded
);
11751 * MenuToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to
11752 * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.BarToolGroup BarToolGroup}
11753 * and {@link OO.ui.ListToolGroup ListToolGroup}). MenuToolGroups contain selectable {@link OO.ui.Tool tools},
11754 * which are displayed by label in a dropdown menu. The tool's title is used as the label text, and the
11755 * menu label is updated to reflect which tool or tools are currently selected. If no tools are selected,
11756 * the menu label is empty. The menu can be configured with an indicator, icon, title, and/or header.
11758 * MenuToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar
11759 * is set up. Note that all tools must define an {@link OO.ui.Tool#onUpdateState onUpdateState} method if
11760 * a MenuToolGroup is used.
11763 * // Example of a MenuToolGroup
11764 * var toolFactory = new OO.ui.ToolFactory();
11765 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
11766 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
11768 * // We will be placing status text in this element when tools are used
11769 * var $area = $( '<p>' ).text( 'An example of a MenuToolGroup. Select a tool from the dropdown menu.' );
11771 * // Define the tools that we're going to place in our toolbar
11773 * function SettingsTool() {
11774 * SettingsTool.parent.apply( this, arguments );
11775 * this.reallyActive = false;
11777 * OO.inheritClass( SettingsTool, OO.ui.Tool );
11778 * SettingsTool.static.name = 'settings';
11779 * SettingsTool.static.icon = 'settings';
11780 * SettingsTool.static.title = 'Change settings';
11781 * SettingsTool.prototype.onSelect = function () {
11782 * $area.text( 'Settings tool clicked!' );
11783 * // Toggle the active state on each click
11784 * this.reallyActive = !this.reallyActive;
11785 * this.setActive( this.reallyActive );
11786 * // To update the menu label
11787 * this.toolbar.emit( 'updateState' );
11789 * SettingsTool.prototype.onUpdateState = function () {
11791 * toolFactory.register( SettingsTool );
11793 * function StuffTool() {
11794 * StuffTool.parent.apply( this, arguments );
11795 * this.reallyActive = false;
11797 * OO.inheritClass( StuffTool, OO.ui.Tool );
11798 * StuffTool.static.name = 'stuff';
11799 * StuffTool.static.icon = 'ellipsis';
11800 * StuffTool.static.title = 'More stuff';
11801 * StuffTool.prototype.onSelect = function () {
11802 * $area.text( 'More stuff tool clicked!' );
11803 * // Toggle the active state on each click
11804 * this.reallyActive = !this.reallyActive;
11805 * this.setActive( this.reallyActive );
11806 * // To update the menu label
11807 * this.toolbar.emit( 'updateState' );
11809 * StuffTool.prototype.onUpdateState = function () {
11811 * toolFactory.register( StuffTool );
11813 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
11814 * // used once (but not all defined tools must be used).
11818 * header: 'This is the (optional) header',
11819 * title: 'This is the (optional) title',
11820 * indicator: 'down',
11821 * include: [ 'settings', 'stuff' ]
11825 * // Create some UI around the toolbar and place it in the document
11826 * var frame = new OO.ui.PanelLayout( {
11830 * var contentFrame = new OO.ui.PanelLayout( {
11834 * frame.$element.append(
11835 * toolbar.$element,
11836 * contentFrame.$element.append( $area )
11838 * $( 'body' ).append( frame.$element );
11840 * // Here is where the toolbar is actually built. This must be done after inserting it into the
11842 * toolbar.initialize();
11843 * toolbar.emit( 'updateState' );
11845 * For more information about how to add tools to a MenuToolGroup, please see {@link OO.ui.ToolGroup toolgroup}.
11846 * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki] [1].
11848 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11851 * @extends OO.ui.PopupToolGroup
11854 * @param {OO.ui.Toolbar} toolbar
11855 * @param {Object} [config] Configuration options
11857 OO
.ui
.MenuToolGroup
= function OoUiMenuToolGroup( toolbar
, config
) {
11858 // Allow passing positional parameters inside the config object
11859 if ( OO
.isPlainObject( toolbar
) && config
=== undefined ) {
11861 toolbar
= config
.toolbar
;
11864 // Configuration initialization
11865 config
= config
|| {};
11867 // Parent constructor
11868 OO
.ui
.MenuToolGroup
.parent
.call( this, toolbar
, config
);
11871 this.toolbar
.connect( this, { updateState
: 'onUpdateState' } );
11874 this.$element
.addClass( 'oo-ui-menuToolGroup' );
11879 OO
.inheritClass( OO
.ui
.MenuToolGroup
, OO
.ui
.PopupToolGroup
);
11881 /* Static Properties */
11883 OO
.ui
.MenuToolGroup
.static.name
= 'menu';
11888 * Handle the toolbar state being updated.
11890 * When the state changes, the title of each active item in the menu will be joined together and
11891 * used as a label for the group. The label will be empty if none of the items are active.
11895 OO
.ui
.MenuToolGroup
.prototype.onUpdateState = function () {
11899 for ( name
in this.tools
) {
11900 if ( this.tools
[ name
].isActive() ) {
11901 labelTexts
.push( this.tools
[ name
].getTitle() );
11905 this.setLabel( labelTexts
.join( ', ' ) || ' ' );
11909 * Popup tools open a popup window when they are selected from the {@link OO.ui.Toolbar toolbar}. Each popup tool is configured
11910 * 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
11911 * an #onSelect or #onUpdateState method, as these methods have been implemented already.
11913 * // Example of a popup tool. When selected, a popup tool displays
11914 * // a popup window.
11915 * function HelpTool( toolGroup, config ) {
11916 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
11921 * this.popup.$body.append( '<p>I am helpful!</p>' );
11923 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
11924 * HelpTool.static.name = 'help';
11925 * HelpTool.static.icon = 'help';
11926 * HelpTool.static.title = 'Help';
11927 * toolFactory.register( HelpTool );
11929 * For an example of a toolbar that contains a popup tool, see {@link OO.ui.Toolbar toolbars}. For more information about
11930 * toolbars in genreral, please see the [OOjs UI documentation on MediaWiki][1].
11932 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars
11936 * @extends OO.ui.Tool
11937 * @mixins OO.ui.mixin.PopupElement
11940 * @param {OO.ui.ToolGroup} toolGroup
11941 * @param {Object} [config] Configuration options
11943 OO
.ui
.PopupTool
= function OoUiPopupTool( toolGroup
, config
) {
11944 // Allow passing positional parameters inside the config object
11945 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
11946 config
= toolGroup
;
11947 toolGroup
= config
.toolGroup
;
11950 // Parent constructor
11951 OO
.ui
.PopupTool
.parent
.call( this, toolGroup
, config
);
11953 // Mixin constructors
11954 OO
.ui
.mixin
.PopupElement
.call( this, config
);
11958 .addClass( 'oo-ui-popupTool' )
11959 .append( this.popup
.$element
);
11964 OO
.inheritClass( OO
.ui
.PopupTool
, OO
.ui
.Tool
);
11965 OO
.mixinClass( OO
.ui
.PopupTool
, OO
.ui
.mixin
.PopupElement
);
11970 * Handle the tool being selected.
11974 OO
.ui
.PopupTool
.prototype.onSelect = function () {
11975 if ( !this.isDisabled() ) {
11976 this.popup
.toggle();
11978 this.setActive( false );
11983 * Handle the toolbar state being updated.
11987 OO
.ui
.PopupTool
.prototype.onUpdateState = function () {
11988 this.setActive( false );
11992 * A ToolGroupTool is a special sort of tool that can contain other {@link OO.ui.Tool tools}
11993 * and {@link OO.ui.ToolGroup toolgroups}. The ToolGroupTool was specifically designed to be used
11994 * inside a {@link OO.ui.BarToolGroup bar} toolgroup to provide access to additional tools from
11995 * the bar item. Included tools will be displayed in a dropdown {@link OO.ui.ListToolGroup list}
11996 * when the ToolGroupTool is selected.
11998 * // Example: ToolGroupTool with two nested tools, 'setting1' and 'setting2', defined elsewhere.
12000 * function SettingsTool() {
12001 * SettingsTool.parent.apply( this, arguments );
12003 * OO.inheritClass( SettingsTool, OO.ui.ToolGroupTool );
12004 * SettingsTool.static.name = 'settings';
12005 * SettingsTool.static.title = 'Change settings';
12006 * SettingsTool.static.groupConfig = {
12007 * icon: 'settings',
12008 * label: 'ToolGroupTool',
12009 * include: [ 'setting1', 'setting2' ]
12011 * toolFactory.register( SettingsTool );
12013 * For more information, please see the [OOjs UI documentation on MediaWiki][1].
12015 * Please note that this implementation is subject to change per [T74159] [2].
12017 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars#ToolGroupTool
12018 * [2]: https://phabricator.wikimedia.org/T74159
12022 * @extends OO.ui.Tool
12025 * @param {OO.ui.ToolGroup} toolGroup
12026 * @param {Object} [config] Configuration options
12028 OO
.ui
.ToolGroupTool
= function OoUiToolGroupTool( toolGroup
, config
) {
12029 // Allow passing positional parameters inside the config object
12030 if ( OO
.isPlainObject( toolGroup
) && config
=== undefined ) {
12031 config
= toolGroup
;
12032 toolGroup
= config
.toolGroup
;
12035 // Parent constructor
12036 OO
.ui
.ToolGroupTool
.parent
.call( this, toolGroup
, config
);
12039 this.innerToolGroup
= this.createGroup( this.constructor.static.groupConfig
);
12042 this.innerToolGroup
.connect( this, { disable
: 'onToolGroupDisable' } );
12045 this.$link
.remove();
12047 .addClass( 'oo-ui-toolGroupTool' )
12048 .append( this.innerToolGroup
.$element
);
12053 OO
.inheritClass( OO
.ui
.ToolGroupTool
, OO
.ui
.Tool
);
12055 /* Static Properties */
12058 * Toolgroup configuration.
12060 * The toolgroup configuration consists of the tools to include, as well as an icon and label
12061 * to use for the bar item. Tools can be included by symbolic name, group, or with the
12062 * wildcard selector. Please see {@link OO.ui.ToolGroup toolgroup} for more information.
12064 * @property {Object.<string,Array>}
12066 OO
.ui
.ToolGroupTool
.static.groupConfig
= {};
12071 * Handle the tool being selected.
12075 OO
.ui
.ToolGroupTool
.prototype.onSelect = function () {
12076 this.innerToolGroup
.setActive( !this.innerToolGroup
.active
);
12081 * Synchronize disabledness state of the tool with the inner toolgroup.
12084 * @param {boolean} disabled Element is disabled
12086 OO
.ui
.ToolGroupTool
.prototype.onToolGroupDisable = function ( disabled
) {
12087 this.setDisabled( disabled
);
12091 * Handle the toolbar state being updated.
12095 OO
.ui
.ToolGroupTool
.prototype.onUpdateState = function () {
12096 this.setActive( false );
12100 * Build a {@link OO.ui.ToolGroup toolgroup} from the specified configuration.
12102 * @param {Object.<string,Array>} group Toolgroup configuration. Please see {@link OO.ui.ToolGroup toolgroup} for
12103 * more information.
12104 * @return {OO.ui.ListToolGroup}
12106 OO
.ui
.ToolGroupTool
.prototype.createGroup = function ( group
) {
12107 if ( group
.include
=== '*' ) {
12108 // Apply defaults to catch-all groups
12109 if ( group
.label
=== undefined ) {
12110 group
.label
= OO
.ui
.msg( 'ooui-toolbar-more' );
12114 return this.toolbar
.getToolGroupFactory().create( 'list', this.toolbar
, group
);
12118 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
12120 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
12125 * @extends OO.ui.mixin.GroupElement
12128 * @param {Object} [config] Configuration options
12130 OO
.ui
.mixin
.GroupWidget
= function OoUiMixinGroupWidget( config
) {
12131 // Parent constructor
12132 OO
.ui
.mixin
.GroupWidget
.parent
.call( this, config
);
12137 OO
.inheritClass( OO
.ui
.mixin
.GroupWidget
, OO
.ui
.mixin
.GroupElement
);
12142 * Set the disabled state of the widget.
12144 * This will also update the disabled state of child widgets.
12146 * @param {boolean} disabled Disable widget
12149 OO
.ui
.mixin
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
12153 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
12154 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
12156 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
12157 if ( this.items
) {
12158 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
12159 this.items
[ i
].updateDisabled();
12167 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
12169 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
12170 * allows bidirectional communication.
12172 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
12180 OO
.ui
.mixin
.ItemWidget
= function OoUiMixinItemWidget() {
12187 * Check if widget is disabled.
12189 * Checks parent if present, making disabled state inheritable.
12191 * @return {boolean} Widget is disabled
12193 OO
.ui
.mixin
.ItemWidget
.prototype.isDisabled = function () {
12194 return this.disabled
||
12195 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
12199 * Set group element is in.
12201 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
12204 OO
.ui
.mixin
.ItemWidget
.prototype.setElementGroup = function ( group
) {
12206 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
12207 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
12209 // Initialize item disabled states
12210 this.updateDisabled();
12216 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
12217 * Controls include moving items up and down, removing items, and adding different kinds of items.
12219 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
12222 * @extends OO.ui.Widget
12223 * @mixins OO.ui.mixin.GroupElement
12224 * @mixins OO.ui.mixin.IconElement
12227 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
12228 * @param {Object} [config] Configuration options
12229 * @cfg {Object} [abilities] List of abilties
12230 * @cfg {boolean} [abilities.move=true] Allow moving movable items
12231 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
12233 OO
.ui
.OutlineControlsWidget
= function OoUiOutlineControlsWidget( outline
, config
) {
12234 // Allow passing positional parameters inside the config object
12235 if ( OO
.isPlainObject( outline
) && config
=== undefined ) {
12237 outline
= config
.outline
;
12240 // Configuration initialization
12241 config
= $.extend( { icon
: 'add' }, config
);
12243 // Parent constructor
12244 OO
.ui
.OutlineControlsWidget
.parent
.call( this, config
);
12246 // Mixin constructors
12247 OO
.ui
.mixin
.GroupElement
.call( this, config
);
12248 OO
.ui
.mixin
.IconElement
.call( this, config
);
12251 this.outline
= outline
;
12252 this.$movers
= $( '<div>' );
12253 this.upButton
= new OO
.ui
.ButtonWidget( {
12256 title
: OO
.ui
.msg( 'ooui-outline-control-move-up' )
12258 this.downButton
= new OO
.ui
.ButtonWidget( {
12261 title
: OO
.ui
.msg( 'ooui-outline-control-move-down' )
12263 this.removeButton
= new OO
.ui
.ButtonWidget( {
12266 title
: OO
.ui
.msg( 'ooui-outline-control-remove' )
12268 this.abilities
= { move: true, remove
: true };
12271 outline
.connect( this, {
12272 select
: 'onOutlineChange',
12273 add
: 'onOutlineChange',
12274 remove
: 'onOutlineChange'
12276 this.upButton
.connect( this, { click
: [ 'emit', 'move', -1 ] } );
12277 this.downButton
.connect( this, { click
: [ 'emit', 'move', 1 ] } );
12278 this.removeButton
.connect( this, { click
: [ 'emit', 'remove' ] } );
12281 this.$element
.addClass( 'oo-ui-outlineControlsWidget' );
12282 this.$group
.addClass( 'oo-ui-outlineControlsWidget-items' );
12284 .addClass( 'oo-ui-outlineControlsWidget-movers' )
12285 .append( this.removeButton
.$element
, this.upButton
.$element
, this.downButton
.$element
);
12286 this.$element
.append( this.$icon
, this.$group
, this.$movers
);
12287 this.setAbilities( config
.abilities
|| {} );
12292 OO
.inheritClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.Widget
);
12293 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.mixin
.GroupElement
);
12294 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.mixin
.IconElement
);
12300 * @param {number} places Number of places to move
12312 * @param {Object} abilities List of abilties
12313 * @param {boolean} [abilities.move] Allow moving movable items
12314 * @param {boolean} [abilities.remove] Allow removing removable items
12316 OO
.ui
.OutlineControlsWidget
.prototype.setAbilities = function ( abilities
) {
12319 for ( ability
in this.abilities
) {
12320 if ( abilities
[ ability
] !== undefined ) {
12321 this.abilities
[ ability
] = !!abilities
[ ability
];
12325 this.onOutlineChange();
12330 * Handle outline change events.
12332 OO
.ui
.OutlineControlsWidget
.prototype.onOutlineChange = function () {
12333 var i
, len
, firstMovable
, lastMovable
,
12334 items
= this.outline
.getItems(),
12335 selectedItem
= this.outline
.getSelectedItem(),
12336 movable
= this.abilities
.move && selectedItem
&& selectedItem
.isMovable(),
12337 removable
= this.abilities
.remove
&& selectedItem
&& selectedItem
.isRemovable();
12341 len
= items
.length
;
12342 while ( ++i
< len
) {
12343 if ( items
[ i
].isMovable() ) {
12344 firstMovable
= items
[ i
];
12350 if ( items
[ i
].isMovable() ) {
12351 lastMovable
= items
[ i
];
12356 this.upButton
.setDisabled( !movable
|| selectedItem
=== firstMovable
);
12357 this.downButton
.setDisabled( !movable
|| selectedItem
=== lastMovable
);
12358 this.removeButton
.setDisabled( !removable
);
12362 * ToggleWidget implements basic behavior of widgets with an on/off state.
12363 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
12367 * @extends OO.ui.Widget
12370 * @param {Object} [config] Configuration options
12371 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
12372 * By default, the toggle is in the 'off' state.
12374 OO
.ui
.ToggleWidget
= function OoUiToggleWidget( config
) {
12375 // Configuration initialization
12376 config
= config
|| {};
12378 // Parent constructor
12379 OO
.ui
.ToggleWidget
.parent
.call( this, config
);
12385 this.$element
.addClass( 'oo-ui-toggleWidget' );
12386 this.setValue( !!config
.value
);
12391 OO
.inheritClass( OO
.ui
.ToggleWidget
, OO
.ui
.Widget
);
12398 * A change event is emitted when the on/off state of the toggle changes.
12400 * @param {boolean} value Value representing the new state of the toggle
12406 * Get the value representing the toggle’s state.
12408 * @return {boolean} The on/off state of the toggle
12410 OO
.ui
.ToggleWidget
.prototype.getValue = function () {
12415 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
12417 * @param {boolean} value The state of the toggle
12421 OO
.ui
.ToggleWidget
.prototype.setValue = function ( value
) {
12423 if ( this.value
!== value
) {
12424 this.value
= value
;
12425 this.emit( 'change', value
);
12426 this.$element
.toggleClass( 'oo-ui-toggleWidget-on', value
);
12427 this.$element
.toggleClass( 'oo-ui-toggleWidget-off', !value
);
12428 this.$element
.attr( 'aria-checked', value
.toString() );
12434 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
12435 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
12436 * removed, and cleared from the group.
12439 * // Example: A ButtonGroupWidget with two buttons
12440 * var button1 = new OO.ui.PopupButtonWidget( {
12441 * label: 'Select a category',
12444 * $content: $( '<p>List of categories...</p>' ),
12449 * var button2 = new OO.ui.ButtonWidget( {
12450 * label: 'Add item'
12452 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
12453 * items: [button1, button2]
12455 * $( 'body' ).append( buttonGroup.$element );
12458 * @extends OO.ui.Widget
12459 * @mixins OO.ui.mixin.GroupElement
12462 * @param {Object} [config] Configuration options
12463 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
12465 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
12466 // Configuration initialization
12467 config
= config
|| {};
12469 // Parent constructor
12470 OO
.ui
.ButtonGroupWidget
.parent
.call( this, config
);
12472 // Mixin constructors
12473 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
12476 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
12477 if ( Array
.isArray( config
.items
) ) {
12478 this.addItems( config
.items
);
12484 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
12485 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.GroupElement
);
12488 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
12489 * feels, and functionality can be customized via the class’s configuration options
12490 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12493 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
12496 * // A button widget
12497 * var button = new OO.ui.ButtonWidget( {
12498 * label: 'Button with Icon',
12500 * iconTitle: 'Remove'
12502 * $( 'body' ).append( button.$element );
12504 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
12507 * @extends OO.ui.Widget
12508 * @mixins OO.ui.mixin.ButtonElement
12509 * @mixins OO.ui.mixin.IconElement
12510 * @mixins OO.ui.mixin.IndicatorElement
12511 * @mixins OO.ui.mixin.LabelElement
12512 * @mixins OO.ui.mixin.TitledElement
12513 * @mixins OO.ui.mixin.FlaggedElement
12514 * @mixins OO.ui.mixin.TabIndexedElement
12515 * @mixins OO.ui.mixin.AccessKeyedElement
12518 * @param {Object} [config] Configuration options
12519 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
12520 * @cfg {string} [target] The frame or window in which to open the hyperlink.
12521 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
12523 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
12524 // Configuration initialization
12525 config
= config
|| {};
12527 // Parent constructor
12528 OO
.ui
.ButtonWidget
.parent
.call( this, config
);
12530 // Mixin constructors
12531 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
12532 OO
.ui
.mixin
.IconElement
.call( this, config
);
12533 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
12534 OO
.ui
.mixin
.LabelElement
.call( this, config
);
12535 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
12536 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
12537 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
12538 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$button
} ) );
12542 this.target
= null;
12543 this.noFollow
= false;
12546 this.connect( this, { disable
: 'onDisable' } );
12549 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
12551 .addClass( 'oo-ui-buttonWidget' )
12552 .append( this.$button
);
12553 this.setHref( config
.href
);
12554 this.setTarget( config
.target
);
12555 this.setNoFollow( config
.noFollow
);
12560 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
12561 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
12562 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IconElement
);
12563 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
12564 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.LabelElement
);
12565 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TitledElement
);
12566 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
12567 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
12568 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
12575 OO
.ui
.ButtonWidget
.prototype.onMouseDown = function ( e
) {
12576 if ( !this.isDisabled() ) {
12577 // Remove the tab-index while the button is down to prevent the button from stealing focus
12578 this.$button
.removeAttr( 'tabindex' );
12581 return OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown
.call( this, e
);
12587 OO
.ui
.ButtonWidget
.prototype.onMouseUp = function ( e
) {
12588 if ( !this.isDisabled() ) {
12589 // Restore the tab-index after the button is up to restore the button's accessibility
12590 this.$button
.attr( 'tabindex', this.tabIndex
);
12593 return OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp
.call( this, e
);
12597 * Get hyperlink location.
12599 * @return {string} Hyperlink location
12601 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
12606 * Get hyperlink target.
12608 * @return {string} Hyperlink target
12610 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
12611 return this.target
;
12615 * Get search engine traversal hint.
12617 * @return {boolean} Whether search engines should avoid traversing this hyperlink
12619 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
12620 return this.noFollow
;
12624 * Set hyperlink location.
12626 * @param {string|null} href Hyperlink location, null to remove
12628 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
12629 href
= typeof href
=== 'string' ? href
: null;
12630 if ( href
!== null ) {
12631 if ( !OO
.ui
.isSafeUrl( href
) ) {
12632 throw new Error( 'Potentially unsafe href provided: ' + href
);
12637 if ( href
!== this.href
) {
12646 * Update the `href` attribute, in case of changes to href or
12652 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
12653 if ( this.href
!== null && !this.isDisabled() ) {
12654 this.$button
.attr( 'href', this.href
);
12656 this.$button
.removeAttr( 'href' );
12663 * Handle disable events.
12666 * @param {boolean} disabled Element is disabled
12668 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
12673 * Set hyperlink target.
12675 * @param {string|null} target Hyperlink target, null to remove
12677 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
12678 target
= typeof target
=== 'string' ? target
: null;
12680 if ( target
!== this.target
) {
12681 this.target
= target
;
12682 if ( target
!== null ) {
12683 this.$button
.attr( 'target', target
);
12685 this.$button
.removeAttr( 'target' );
12693 * Set search engine traversal hint.
12695 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
12697 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
12698 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
12700 if ( noFollow
!== this.noFollow
) {
12701 this.noFollow
= noFollow
;
12703 this.$button
.attr( 'rel', 'nofollow' );
12705 this.$button
.removeAttr( 'rel' );
12713 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
12714 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
12717 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
12718 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
12721 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
12724 * @extends OO.ui.ButtonWidget
12725 * @mixins OO.ui.mixin.PendingElement
12728 * @param {Object} [config] Configuration options
12729 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12730 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
12731 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
12732 * for more information about setting modes.
12733 * @cfg {boolean} [framed=false] Render the action button with a frame
12735 OO
.ui
.ActionWidget
= function OoUiActionWidget( config
) {
12736 // Configuration initialization
12737 config
= $.extend( { framed
: false }, config
);
12739 // Parent constructor
12740 OO
.ui
.ActionWidget
.parent
.call( this, config
);
12742 // Mixin constructors
12743 OO
.ui
.mixin
.PendingElement
.call( this, config
);
12746 this.action
= config
.action
|| '';
12747 this.modes
= config
.modes
|| [];
12752 this.$element
.addClass( 'oo-ui-actionWidget' );
12757 OO
.inheritClass( OO
.ui
.ActionWidget
, OO
.ui
.ButtonWidget
);
12758 OO
.mixinClass( OO
.ui
.ActionWidget
, OO
.ui
.mixin
.PendingElement
);
12763 * A resize event is emitted when the size of the widget changes.
12771 * Check if the action is configured to be available in the specified `mode`.
12773 * @param {string} mode Name of mode
12774 * @return {boolean} The action is configured with the mode
12776 OO
.ui
.ActionWidget
.prototype.hasMode = function ( mode
) {
12777 return this.modes
.indexOf( mode
) !== -1;
12781 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
12785 OO
.ui
.ActionWidget
.prototype.getAction = function () {
12786 return this.action
;
12790 * Get the symbolic name of the mode or modes for which the action is configured to be available.
12792 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
12793 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
12796 * @return {string[]}
12798 OO
.ui
.ActionWidget
.prototype.getModes = function () {
12799 return this.modes
.slice();
12803 * Emit a resize event if the size has changed.
12808 OO
.ui
.ActionWidget
.prototype.propagateResize = function () {
12811 if ( this.isElementAttached() ) {
12812 width
= this.$element
.width();
12813 height
= this.$element
.height();
12815 if ( width
!== this.width
|| height
!== this.height
) {
12816 this.width
= width
;
12817 this.height
= height
;
12818 this.emit( 'resize' );
12828 OO
.ui
.ActionWidget
.prototype.setIcon = function () {
12830 OO
.ui
.mixin
.IconElement
.prototype.setIcon
.apply( this, arguments
);
12831 this.propagateResize();
12839 OO
.ui
.ActionWidget
.prototype.setLabel = function () {
12841 OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.apply( this, arguments
);
12842 this.propagateResize();
12850 OO
.ui
.ActionWidget
.prototype.setFlags = function () {
12852 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags
.apply( this, arguments
);
12853 this.propagateResize();
12861 OO
.ui
.ActionWidget
.prototype.clearFlags = function () {
12863 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags
.apply( this, arguments
);
12864 this.propagateResize();
12870 * Toggle the visibility of the action button.
12872 * @param {boolean} [show] Show button, omit to toggle visibility
12875 OO
.ui
.ActionWidget
.prototype.toggle = function () {
12877 OO
.ui
.ActionWidget
.parent
.prototype.toggle
.apply( this, arguments
);
12878 this.propagateResize();
12884 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
12885 * which is used to display additional information or options.
12888 * // Example of a popup button.
12889 * var popupButton = new OO.ui.PopupButtonWidget( {
12890 * label: 'Popup button with options',
12893 * $content: $( '<p>Additional options here.</p>' ),
12895 * align: 'force-left'
12898 * // Append the button to the DOM.
12899 * $( 'body' ).append( popupButton.$element );
12902 * @extends OO.ui.ButtonWidget
12903 * @mixins OO.ui.mixin.PopupElement
12906 * @param {Object} [config] Configuration options
12908 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
12909 // Parent constructor
12910 OO
.ui
.PopupButtonWidget
.parent
.call( this, config
);
12912 // Mixin constructors
12913 OO
.ui
.mixin
.PopupElement
.call( this, config
);
12916 this.connect( this, { click
: 'onAction' } );
12920 .addClass( 'oo-ui-popupButtonWidget' )
12921 .attr( 'aria-haspopup', 'true' )
12922 .append( this.popup
.$element
);
12927 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
12928 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.mixin
.PopupElement
);
12933 * Handle the button action being triggered.
12937 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
12938 this.popup
.toggle();
12942 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
12943 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
12944 * configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators},
12945 * {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags},
12946 * and {@link OO.ui.mixin.LabelElement labels}. Please see
12947 * the [OOjs UI documentation][1] on MediaWiki for more information.
12950 * // Toggle buttons in the 'off' and 'on' state.
12951 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
12952 * label: 'Toggle Button off'
12954 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
12955 * label: 'Toggle Button on',
12958 * // Append the buttons to the DOM.
12959 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
12961 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
12964 * @extends OO.ui.ToggleWidget
12965 * @mixins OO.ui.mixin.ButtonElement
12966 * @mixins OO.ui.mixin.IconElement
12967 * @mixins OO.ui.mixin.IndicatorElement
12968 * @mixins OO.ui.mixin.LabelElement
12969 * @mixins OO.ui.mixin.TitledElement
12970 * @mixins OO.ui.mixin.FlaggedElement
12971 * @mixins OO.ui.mixin.TabIndexedElement
12974 * @param {Object} [config] Configuration options
12975 * @cfg {boolean} [value=false] The toggle button’s initial on/off
12976 * state. By default, the button is in the 'off' state.
12978 OO
.ui
.ToggleButtonWidget
= function OoUiToggleButtonWidget( config
) {
12979 // Configuration initialization
12980 config
= config
|| {};
12982 // Parent constructor
12983 OO
.ui
.ToggleButtonWidget
.parent
.call( this, config
);
12985 // Mixin constructors
12986 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
12987 OO
.ui
.mixin
.IconElement
.call( this, config
);
12988 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
12989 OO
.ui
.mixin
.LabelElement
.call( this, config
);
12990 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
12991 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
12992 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
12995 this.connect( this, { click
: 'onAction' } );
12998 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
13000 .addClass( 'oo-ui-toggleButtonWidget' )
13001 .append( this.$button
);
13006 OO
.inheritClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.ToggleWidget
);
13007 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
13008 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.IconElement
);
13009 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
13010 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.LabelElement
);
13011 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.TitledElement
);
13012 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
13013 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
13018 * Handle the button action being triggered.
13022 OO
.ui
.ToggleButtonWidget
.prototype.onAction = function () {
13023 this.setValue( !this.value
);
13029 OO
.ui
.ToggleButtonWidget
.prototype.setValue = function ( value
) {
13031 if ( value
!== this.value
) {
13032 // Might be called from parent constructor before ButtonElement constructor
13033 if ( this.$button
) {
13034 this.$button
.attr( 'aria-pressed', value
.toString() );
13036 this.setActive( value
);
13040 OO
.ui
.ToggleButtonWidget
.parent
.prototype.setValue
.call( this, value
);
13048 OO
.ui
.ToggleButtonWidget
.prototype.setButtonElement = function ( $button
) {
13049 if ( this.$button
) {
13050 this.$button
.removeAttr( 'aria-pressed' );
13052 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement
.call( this, $button
);
13053 this.$button
.attr( 'aria-pressed', this.value
.toString() );
13057 * CapsuleMultiSelectWidgets are something like a {@link OO.ui.ComboBoxWidget combo box widget}
13058 * that allows for selecting multiple values.
13060 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
13063 * // Example: A CapsuleMultiSelectWidget.
13064 * var capsule = new OO.ui.CapsuleMultiSelectWidget( {
13065 * label: 'CapsuleMultiSelectWidget',
13066 * selected: [ 'Option 1', 'Option 3' ],
13069 * new OO.ui.MenuOptionWidget( {
13070 * data: 'Option 1',
13071 * label: 'Option One'
13073 * new OO.ui.MenuOptionWidget( {
13074 * data: 'Option 2',
13075 * label: 'Option Two'
13077 * new OO.ui.MenuOptionWidget( {
13078 * data: 'Option 3',
13079 * label: 'Option Three'
13081 * new OO.ui.MenuOptionWidget( {
13082 * data: 'Option 4',
13083 * label: 'Option Four'
13085 * new OO.ui.MenuOptionWidget( {
13086 * data: 'Option 5',
13087 * label: 'Option Five'
13092 * $( 'body' ).append( capsule.$element );
13094 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13097 * @extends OO.ui.Widget
13098 * @mixins OO.ui.mixin.TabIndexedElement
13099 * @mixins OO.ui.mixin.GroupElement
13102 * @param {Object} [config] Configuration options
13103 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if not present in the menu.
13104 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
13105 * @cfg {Object} [popup] Configuration options to pass to the {@link OO.ui.PopupWidget popup widget}.
13106 * If specified, this popup will be shown instead of the menu (but the menu
13107 * will still be used for item labels and allowArbitrary=false). The widgets
13108 * in the popup should use this.addItemsFromData() or this.addItems() as necessary.
13109 * @cfg {jQuery} [$overlay] Render the menu or popup into a separate layer.
13110 * This configuration is useful in cases where the expanded menu is larger than
13111 * its containing `<div>`. The specified overlay layer is usually on top of
13112 * the containing `<div>` and has a larger area. By default, the menu uses
13113 * relative positioning.
13115 OO
.ui
.CapsuleMultiSelectWidget
= function OoUiCapsuleMultiSelectWidget( config
) {
13118 // Configuration initialization
13119 config
= config
|| {};
13121 // Parent constructor
13122 OO
.ui
.CapsuleMultiSelectWidget
.parent
.call( this, config
);
13124 // Properties (must be set before mixin constructor calls)
13125 this.$input
= config
.popup
? null : $( '<input>' );
13126 this.$handle
= $( '<div>' );
13128 // Mixin constructors
13129 OO
.ui
.mixin
.GroupElement
.call( this, config
);
13130 if ( config
.popup
) {
13131 config
.popup
= $.extend( {}, config
.popup
, {
13135 OO
.ui
.mixin
.PopupElement
.call( this, config
);
13136 $tabFocus
= $( '<span>' );
13137 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: $tabFocus
} ) );
13141 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
13143 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
13144 OO
.ui
.mixin
.IconElement
.call( this, config
);
13147 this.allowArbitrary
= !!config
.allowArbitrary
;
13148 this.$overlay
= config
.$overlay
|| this.$element
;
13149 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend(
13152 $input
: this.$input
,
13153 $container
: this.$element
,
13154 filterFromInput
: true,
13155 disabled
: this.isDisabled()
13161 if ( this.popup
) {
13163 focus
: this.onFocusForPopup
.bind( this )
13165 this.popup
.$element
.on( 'focusout', this.onPopupFocusOut
.bind( this ) );
13166 if ( this.popup
.$autoCloseIgnore
) {
13167 this.popup
.$autoCloseIgnore
.on( 'focusout', this.onPopupFocusOut
.bind( this ) );
13169 this.popup
.connect( this, {
13170 toggle: function ( visible
) {
13171 $tabFocus
.toggle( !visible
);
13176 focus
: this.onInputFocus
.bind( this ),
13177 blur
: this.onInputBlur
.bind( this ),
13178 'propertychange change click mouseup keydown keyup input cut paste select': this.onInputChange
.bind( this ),
13179 keydown
: this.onKeyDown
.bind( this ),
13180 keypress
: this.onKeyPress
.bind( this )
13183 this.menu
.connect( this, {
13184 choose
: 'onMenuChoose',
13185 add
: 'onMenuItemsChange',
13186 remove
: 'onMenuItemsChange'
13189 click
: this.onClick
.bind( this )
13193 if ( this.$input
) {
13194 this.$input
.prop( 'disabled', this.isDisabled() );
13195 this.$input
.attr( {
13197 'aria-autocomplete': 'list'
13199 this.$input
.width( '1em' );
13201 if ( config
.data
) {
13202 this.setItemsFromData( config
.data
);
13204 this.$group
.addClass( 'oo-ui-capsuleMultiSelectWidget-group' );
13205 this.$handle
.addClass( 'oo-ui-capsuleMultiSelectWidget-handle' )
13206 .append( this.$indicator
, this.$icon
, this.$group
);
13207 this.$element
.addClass( 'oo-ui-capsuleMultiSelectWidget' )
13208 .append( this.$handle
);
13209 if ( this.popup
) {
13210 this.$handle
.append( $tabFocus
);
13211 this.$overlay
.append( this.popup
.$element
);
13213 this.$handle
.append( this.$input
);
13214 this.$overlay
.append( this.menu
.$element
);
13216 this.onMenuItemsChange();
13221 OO
.inheritClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.Widget
);
13222 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.GroupElement
);
13223 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.PopupElement
);
13224 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
13225 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.IndicatorElement
);
13226 OO
.mixinClass( OO
.ui
.CapsuleMultiSelectWidget
, OO
.ui
.mixin
.IconElement
);
13233 * A change event is emitted when the set of selected items changes.
13235 * @param {Mixed[]} datas Data of the now-selected items
13241 * Construct a OO.ui.CapsuleItemWidget (or a subclass thereof) from given label and data.
13244 * @param {Mixed} data Custom data of any type.
13245 * @param {string} label The label text.
13246 * @return {OO.ui.CapsuleItemWidget}
13248 OO
.ui
.CapsuleMultiSelectWidget
.prototype.createItemWidget = function ( data
, label
) {
13249 return new OO
.ui
.CapsuleItemWidget( { data
: data
, label
: label
} );
13253 * Get the data of the items in the capsule
13254 * @return {Mixed[]}
13256 OO
.ui
.CapsuleMultiSelectWidget
.prototype.getItemsData = function () {
13257 return $.map( this.getItems(), function ( e
) { return e
.data
; } );
13261 * Set the items in the capsule by providing data
13263 * @param {Mixed[]} datas
13264 * @return {OO.ui.CapsuleMultiSelectWidget}
13266 OO
.ui
.CapsuleMultiSelectWidget
.prototype.setItemsFromData = function ( datas
) {
13269 items
= this.getItems();
13271 $.each( datas
, function ( i
, data
) {
13273 item
= menu
.getItemFromData( data
);
13276 label
= item
.label
;
13277 } else if ( widget
.allowArbitrary
) {
13278 label
= String( data
);
13284 for ( j
= 0; j
< items
.length
; j
++ ) {
13285 if ( items
[ j
].data
=== data
&& items
[ j
].label
=== label
) {
13287 items
.splice( j
, 1 );
13292 item
= widget
.createItemWidget( data
, label
);
13294 widget
.addItems( [ item
], i
);
13297 if ( items
.length
) {
13298 widget
.removeItems( items
);
13305 * Add items to the capsule by providing their data
13307 * @param {Mixed[]} datas
13308 * @return {OO.ui.CapsuleMultiSelectWidget}
13310 OO
.ui
.CapsuleMultiSelectWidget
.prototype.addItemsFromData = function ( datas
) {
13315 $.each( datas
, function ( i
, data
) {
13318 if ( !widget
.getItemFromData( data
) ) {
13319 item
= menu
.getItemFromData( data
);
13321 items
.push( widget
.createItemWidget( data
, item
.label
) );
13322 } else if ( widget
.allowArbitrary
) {
13323 items
.push( widget
.createItemWidget( data
, String( data
) ) );
13328 if ( items
.length
) {
13329 this.addItems( items
);
13336 * Remove items by data
13338 * @param {Mixed[]} datas
13339 * @return {OO.ui.CapsuleMultiSelectWidget}
13341 OO
.ui
.CapsuleMultiSelectWidget
.prototype.removeItemsFromData = function ( datas
) {
13345 $.each( datas
, function ( i
, data
) {
13346 var item
= widget
.getItemFromData( data
);
13348 items
.push( item
);
13352 if ( items
.length
) {
13353 this.removeItems( items
);
13362 OO
.ui
.CapsuleMultiSelectWidget
.prototype.addItems = function ( items
) {
13364 oldItems
= this.items
.slice();
13366 OO
.ui
.mixin
.GroupElement
.prototype.addItems
.call( this, items
);
13368 if ( this.items
.length
!== oldItems
.length
) {
13372 for ( i
= 0, l
= oldItems
.length
; same
&& i
< l
; i
++ ) {
13373 same
= same
&& this.items
[ i
] === oldItems
[ i
];
13377 this.emit( 'change', this.getItemsData() );
13386 OO
.ui
.CapsuleMultiSelectWidget
.prototype.removeItems = function ( items
) {
13388 oldItems
= this.items
.slice();
13390 OO
.ui
.mixin
.GroupElement
.prototype.removeItems
.call( this, items
);
13392 if ( this.items
.length
!== oldItems
.length
) {
13396 for ( i
= 0, l
= oldItems
.length
; same
&& i
< l
; i
++ ) {
13397 same
= same
&& this.items
[ i
] === oldItems
[ i
];
13401 this.emit( 'change', this.getItemsData() );
13410 OO
.ui
.CapsuleMultiSelectWidget
.prototype.clearItems = function () {
13411 if ( this.items
.length
) {
13412 OO
.ui
.mixin
.GroupElement
.prototype.clearItems
.call( this );
13413 this.emit( 'change', this.getItemsData() );
13419 * Get the capsule widget's menu.
13420 * @return {OO.ui.MenuSelectWidget} Menu widget
13422 OO
.ui
.CapsuleMultiSelectWidget
.prototype.getMenu = function () {
13427 * Handle focus events
13430 * @param {jQuery.Event} event
13432 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onInputFocus = function () {
13433 if ( !this.isDisabled() ) {
13434 this.menu
.toggle( true );
13439 * Handle blur events
13442 * @param {jQuery.Event} event
13444 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onInputBlur = function () {
13449 * Handle focus events
13452 * @param {jQuery.Event} event
13454 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onFocusForPopup = function () {
13455 if ( !this.isDisabled() ) {
13456 this.popup
.setSize( this.$handle
.width() );
13457 this.popup
.toggle( true );
13458 this.popup
.$element
.find( '*' )
13459 .filter( function () { return OO
.ui
.isFocusableElement( $( this ), true ); } )
13466 * Handles popup focus out events.
13469 * @param {Event} e Focus out event
13471 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onPopupFocusOut = function () {
13472 var widget
= this.popup
;
13474 setTimeout( function () {
13476 widget
.isVisible() &&
13477 !OO
.ui
.contains( widget
.$element
[ 0 ], document
.activeElement
, true ) &&
13478 ( !widget
.$autoCloseIgnore
|| !widget
.$autoCloseIgnore
.has( document
.activeElement
).length
)
13480 widget
.toggle( false );
13486 * Handle mouse click events.
13489 * @param {jQuery.Event} e Mouse click event
13491 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onClick = function ( e
) {
13492 if ( e
.which
=== 1 ) {
13499 * Handle key press events.
13502 * @param {jQuery.Event} e Key press event
13504 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onKeyPress = function ( e
) {
13507 if ( !this.isDisabled() ) {
13508 if ( e
.which
=== OO
.ui
.Keys
.ESCAPE
) {
13513 if ( !this.popup
) {
13514 this.menu
.toggle( true );
13515 if ( e
.which
=== OO
.ui
.Keys
.ENTER
) {
13516 item
= this.menu
.getItemFromLabel( this.$input
.val(), true );
13518 this.addItemsFromData( [ item
.data
] );
13520 } else if ( this.allowArbitrary
&& this.$input
.val().trim() !== '' ) {
13521 this.addItemsFromData( [ this.$input
.val() ] );
13527 // Make sure the input gets resized.
13528 setTimeout( this.onInputChange
.bind( this ), 0 );
13534 * Handle key down events.
13537 * @param {jQuery.Event} e Key down event
13539 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onKeyDown = function ( e
) {
13540 if ( !this.isDisabled() ) {
13541 // 'keypress' event is not triggered for Backspace
13542 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.$input
.val() === '' ) {
13543 if ( this.items
.length
) {
13544 this.removeItems( this.items
.slice( -1 ) );
13552 * Handle input change events.
13555 * @param {jQuery.Event} e Event of some sort
13557 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onInputChange = function () {
13558 if ( !this.isDisabled() ) {
13559 this.$input
.width( this.$input
.val().length
+ 'em' );
13564 * Handle menu choose events.
13567 * @param {OO.ui.OptionWidget} item Chosen item
13569 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onMenuChoose = function ( item
) {
13570 if ( item
&& item
.isVisible() ) {
13571 this.addItemsFromData( [ item
.getData() ] );
13577 * Handle menu item change events.
13581 OO
.ui
.CapsuleMultiSelectWidget
.prototype.onMenuItemsChange = function () {
13582 this.setItemsFromData( this.getItemsData() );
13583 this.$element
.toggleClass( 'oo-ui-capsuleMultiSelectWidget-empty', this.menu
.isEmpty() );
13587 * Clear the input field
13590 OO
.ui
.CapsuleMultiSelectWidget
.prototype.clearInput = function () {
13591 if ( this.$input
) {
13592 this.$input
.val( '' );
13593 this.$input
.width( '1em' );
13595 if ( this.popup
) {
13596 this.popup
.toggle( false );
13598 this.menu
.toggle( false );
13599 this.menu
.selectItem();
13600 this.menu
.highlightItem();
13606 OO
.ui
.CapsuleMultiSelectWidget
.prototype.setDisabled = function ( disabled
) {
13610 OO
.ui
.CapsuleMultiSelectWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
13612 if ( this.$input
) {
13613 this.$input
.prop( 'disabled', this.isDisabled() );
13616 this.menu
.setDisabled( this.isDisabled() );
13618 if ( this.popup
) {
13619 this.popup
.setDisabled( this.isDisabled() );
13622 if ( this.items
) {
13623 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
13624 this.items
[ i
].updateDisabled();
13634 * @return {OO.ui.CapsuleMultiSelectWidget}
13636 OO
.ui
.CapsuleMultiSelectWidget
.prototype.focus = function () {
13637 if ( !this.isDisabled() ) {
13638 if ( this.popup
) {
13639 this.popup
.setSize( this.$handle
.width() );
13640 this.popup
.toggle( true );
13641 this.popup
.$element
.find( '*' )
13642 .filter( function () { return OO
.ui
.isFocusableElement( $( this ), true ); } )
13646 this.menu
.toggle( true );
13647 this.$input
.focus();
13654 * CapsuleItemWidgets are used within a {@link OO.ui.CapsuleMultiSelectWidget
13655 * CapsuleMultiSelectWidget} to display the selected items.
13658 * @extends OO.ui.Widget
13659 * @mixins OO.ui.mixin.ItemWidget
13660 * @mixins OO.ui.mixin.IndicatorElement
13661 * @mixins OO.ui.mixin.LabelElement
13662 * @mixins OO.ui.mixin.FlaggedElement
13663 * @mixins OO.ui.mixin.TabIndexedElement
13666 * @param {Object} [config] Configuration options
13668 OO
.ui
.CapsuleItemWidget
= function OoUiCapsuleItemWidget( config
) {
13669 // Configuration initialization
13670 config
= config
|| {};
13672 // Parent constructor
13673 OO
.ui
.CapsuleItemWidget
.parent
.call( this, config
);
13675 // Properties (must be set before mixin constructor calls)
13676 this.$indicator
= $( '<span>' );
13678 // Mixin constructors
13679 OO
.ui
.mixin
.ItemWidget
.call( this );
13680 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$indicator
, indicator
: 'clear' } ) );
13681 OO
.ui
.mixin
.LabelElement
.call( this, config
);
13682 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
13683 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$indicator
} ) );
13686 this.$indicator
.on( {
13687 keydown
: this.onCloseKeyDown
.bind( this ),
13688 click
: this.onCloseClick
.bind( this )
13690 this.$element
.on( 'click', false );
13694 .addClass( 'oo-ui-capsuleItemWidget' )
13695 .append( this.$indicator
, this.$label
);
13700 OO
.inheritClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.Widget
);
13701 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.ItemWidget
);
13702 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.IndicatorElement
);
13703 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.LabelElement
);
13704 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.FlaggedElement
);
13705 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.TabIndexedElement
);
13710 * Handle close icon clicks
13711 * @param {jQuery.Event} event
13713 OO
.ui
.CapsuleItemWidget
.prototype.onCloseClick = function () {
13714 var element
= this.getElementGroup();
13716 if ( !this.isDisabled() && element
&& $.isFunction( element
.removeItems
) ) {
13717 element
.removeItems( [ this ] );
13723 * Handle close keyboard events
13724 * @param {jQuery.Event} event Key down event
13726 OO
.ui
.CapsuleItemWidget
.prototype.onCloseKeyDown = function ( e
) {
13727 if ( !this.isDisabled() && $.isFunction( this.getElementGroup().removeItems
) ) {
13728 switch ( e
.which
) {
13729 case OO
.ui
.Keys
.ENTER
:
13730 case OO
.ui
.Keys
.BACKSPACE
:
13731 case OO
.ui
.Keys
.SPACE
:
13732 this.getElementGroup().removeItems( [ this ] );
13739 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
13740 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
13741 * users can interact with it.
13743 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
13744 * OO.ui.DropdownInputWidget instead.
13747 * // Example: A DropdownWidget with a menu that contains three options
13748 * var dropDown = new OO.ui.DropdownWidget( {
13749 * label: 'Dropdown menu: Select a menu option',
13752 * new OO.ui.MenuOptionWidget( {
13756 * new OO.ui.MenuOptionWidget( {
13760 * new OO.ui.MenuOptionWidget( {
13768 * $( 'body' ).append( dropDown.$element );
13770 * dropDown.getMenu().selectItemByData( 'b' );
13772 * dropDown.getMenu().getSelectedItem().getData(); // returns 'b'
13774 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
13776 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13779 * @extends OO.ui.Widget
13780 * @mixins OO.ui.mixin.IconElement
13781 * @mixins OO.ui.mixin.IndicatorElement
13782 * @mixins OO.ui.mixin.LabelElement
13783 * @mixins OO.ui.mixin.TitledElement
13784 * @mixins OO.ui.mixin.TabIndexedElement
13787 * @param {Object} [config] Configuration options
13788 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
13789 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
13790 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
13791 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
13793 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
13794 // Configuration initialization
13795 config
= $.extend( { indicator
: 'down' }, config
);
13797 // Parent constructor
13798 OO
.ui
.DropdownWidget
.parent
.call( this, config
);
13800 // Properties (must be set before TabIndexedElement constructor call)
13801 this.$handle
= this.$( '<span>' );
13802 this.$overlay
= config
.$overlay
|| this.$element
;
13804 // Mixin constructors
13805 OO
.ui
.mixin
.IconElement
.call( this, config
);
13806 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
13807 OO
.ui
.mixin
.LabelElement
.call( this, config
);
13808 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
13809 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
13812 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend( {
13814 $container
: this.$element
13815 }, config
.menu
) );
13819 click
: this.onClick
.bind( this ),
13820 keypress
: this.onKeyPress
.bind( this )
13822 this.menu
.connect( this, { select
: 'onMenuSelect' } );
13826 .addClass( 'oo-ui-dropdownWidget-handle' )
13827 .append( this.$icon
, this.$label
, this.$indicator
);
13829 .addClass( 'oo-ui-dropdownWidget' )
13830 .append( this.$handle
);
13831 this.$overlay
.append( this.menu
.$element
);
13836 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
13837 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IconElement
);
13838 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IndicatorElement
);
13839 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.LabelElement
);
13840 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TitledElement
);
13841 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TabIndexedElement
);
13848 * @return {OO.ui.MenuSelectWidget} Menu of widget
13850 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
13855 * Handles menu select events.
13858 * @param {OO.ui.MenuOptionWidget} item Selected menu item
13860 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
13864 this.setLabel( null );
13868 selectedLabel
= item
.getLabel();
13870 // If the label is a DOM element, clone it, because setLabel will append() it
13871 if ( selectedLabel
instanceof jQuery
) {
13872 selectedLabel
= selectedLabel
.clone();
13875 this.setLabel( selectedLabel
);
13879 * Handle mouse click events.
13882 * @param {jQuery.Event} e Mouse click event
13884 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
13885 if ( !this.isDisabled() && e
.which
=== 1 ) {
13886 this.menu
.toggle();
13892 * Handle key press events.
13895 * @param {jQuery.Event} e Key press event
13897 OO
.ui
.DropdownWidget
.prototype.onKeyPress = function ( e
) {
13898 if ( !this.isDisabled() &&
13899 ( ( e
.which
=== OO
.ui
.Keys
.SPACE
&& !this.menu
.isVisible() ) || e
.which
=== OO
.ui
.Keys
.ENTER
)
13901 this.menu
.toggle();
13907 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
13908 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
13909 * OO.ui.mixin.IndicatorElement indicators}.
13910 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
13913 * // Example of a file select widget
13914 * var selectFile = new OO.ui.SelectFileWidget();
13915 * $( 'body' ).append( selectFile.$element );
13917 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets
13920 * @extends OO.ui.Widget
13921 * @mixins OO.ui.mixin.IconElement
13922 * @mixins OO.ui.mixin.IndicatorElement
13923 * @mixins OO.ui.mixin.PendingElement
13924 * @mixins OO.ui.mixin.LabelElement
13927 * @param {Object} [config] Configuration options
13928 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
13929 * @cfg {string} [placeholder] Text to display when no file is selected.
13930 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
13931 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
13932 * @cfg {boolean} [showDropTarget=false] Whether to show a drop target. Requires droppable to be true.
13933 * @cfg {boolean} [dragDropUI=false] Deprecated alias for showDropTarget
13935 OO
.ui
.SelectFileWidget
= function OoUiSelectFileWidget( config
) {
13938 // TODO: Remove in next release
13939 if ( config
&& config
.dragDropUI
) {
13940 config
.showDropTarget
= true;
13943 // Configuration initialization
13944 config
= $.extend( {
13946 placeholder
: OO
.ui
.msg( 'ooui-selectfile-placeholder' ),
13947 notsupported
: OO
.ui
.msg( 'ooui-selectfile-not-supported' ),
13949 showDropTarget
: false
13952 // Parent constructor
13953 OO
.ui
.SelectFileWidget
.parent
.call( this, config
);
13955 // Mixin constructors
13956 OO
.ui
.mixin
.IconElement
.call( this, config
);
13957 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
13958 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$info
} ) );
13959 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { autoFitLabel
: true } ) );
13962 this.$info
= $( '<span>' );
13965 this.showDropTarget
= config
.showDropTarget
;
13966 this.isSupported
= this.constructor.static.isSupported();
13967 this.currentFile
= null;
13968 if ( Array
.isArray( config
.accept
) ) {
13969 this.accept
= config
.accept
;
13971 this.accept
= null;
13973 this.placeholder
= config
.placeholder
;
13974 this.notsupported
= config
.notsupported
;
13975 this.onFileSelectedHandler
= this.onFileSelected
.bind( this );
13977 this.selectButton
= new OO
.ui
.ButtonWidget( {
13978 classes
: [ 'oo-ui-selectFileWidget-selectButton' ],
13979 label
: 'Select a file',
13980 disabled
: this.disabled
|| !this.isSupported
13983 this.clearButton
= new OO
.ui
.ButtonWidget( {
13984 classes
: [ 'oo-ui-selectFileWidget-clearButton' ],
13987 disabled
: this.disabled
13991 this.selectButton
.$button
.on( {
13992 keypress
: this.onKeyPress
.bind( this )
13994 this.clearButton
.connect( this, {
13995 click
: 'onClearClick'
13997 if ( config
.droppable
) {
13998 dragHandler
= this.onDragEnterOrOver
.bind( this );
13999 this.$element
.on( {
14000 dragenter
: dragHandler
,
14001 dragover
: dragHandler
,
14002 dragleave
: this.onDragLeave
.bind( this ),
14003 drop
: this.onDrop
.bind( this )
14010 this.$label
.addClass( 'oo-ui-selectFileWidget-label' );
14012 .addClass( 'oo-ui-selectFileWidget-info' )
14013 .append( this.$icon
, this.$label
, this.clearButton
.$element
, this.$indicator
);
14015 .addClass( 'oo-ui-selectFileWidget' )
14016 .append( this.$info
, this.selectButton
.$element
);
14017 if ( config
.droppable
&& config
.showDropTarget
) {
14018 this.$dropTarget
= $( '<div>' )
14019 .addClass( 'oo-ui-selectFileWidget-dropTarget' )
14020 .text( OO
.ui
.msg( 'ooui-selectfile-dragdrop-placeholder' ) )
14022 click
: this.onDropTargetClick
.bind( this )
14024 this.$element
.prepend( this.$dropTarget
);
14030 OO
.inheritClass( OO
.ui
.SelectFileWidget
, OO
.ui
.Widget
);
14031 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.IconElement
);
14032 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.IndicatorElement
);
14033 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.PendingElement
);
14034 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.LabelElement
);
14036 /* Static Properties */
14039 * Check if this widget is supported
14042 * @return {boolean}
14044 OO
.ui
.SelectFileWidget
.static.isSupported = function () {
14046 if ( OO
.ui
.SelectFileWidget
.static.isSupportedCache
=== null ) {
14047 $input
= $( '<input type="file">' );
14048 OO
.ui
.SelectFileWidget
.static.isSupportedCache
= $input
[ 0 ].files
!== undefined;
14050 return OO
.ui
.SelectFileWidget
.static.isSupportedCache
;
14053 OO
.ui
.SelectFileWidget
.static.isSupportedCache
= null;
14060 * A change event is emitted when the on/off state of the toggle changes.
14062 * @param {File|null} value New value
14068 * Get the current value of the field
14070 * @return {File|null}
14072 OO
.ui
.SelectFileWidget
.prototype.getValue = function () {
14073 return this.currentFile
;
14077 * Set the current value of the field
14079 * @param {File|null} file File to select
14081 OO
.ui
.SelectFileWidget
.prototype.setValue = function ( file
) {
14082 if ( this.currentFile
!== file
) {
14083 this.currentFile
= file
;
14085 this.emit( 'change', this.currentFile
);
14090 * Update the user interface when a file is selected or unselected
14094 OO
.ui
.SelectFileWidget
.prototype.updateUI = function () {
14096 if ( !this.isSupported
) {
14097 this.$element
.addClass( 'oo-ui-selectFileWidget-notsupported' );
14098 this.$element
.removeClass( 'oo-ui-selectFileWidget-empty' );
14099 this.setLabel( this.notsupported
);
14101 this.$element
.addClass( 'oo-ui-selectFileWidget-supported' );
14102 if ( this.currentFile
) {
14103 this.$element
.removeClass( 'oo-ui-selectFileWidget-empty' );
14105 if ( this.currentFile
.type
!== '' ) {
14106 $label
= $label
.add( $( '<span>' ).addClass( 'oo-ui-selectFileWidget-fileType' ).text( this.currentFile
.type
) );
14108 $label
= $label
.add( $( '<span>' ).text( this.currentFile
.name
) );
14109 this.setLabel( $label
);
14111 this.$element
.addClass( 'oo-ui-selectFileWidget-empty' );
14112 this.setLabel( this.placeholder
);
14116 if ( this.$input
) {
14117 this.$input
.attr( 'title', this.getLabel() );
14122 * Add the input to the widget
14126 OO
.ui
.SelectFileWidget
.prototype.addInput = function () {
14127 if ( this.$input
) {
14128 this.$input
.remove();
14131 if ( !this.isSupported
) {
14132 this.$input
= null;
14136 this.$input
= $( '<input type="file">' );
14137 this.$input
.on( 'change', this.onFileSelectedHandler
);
14138 this.$input
.attr( {
14140 title
: this.getLabel()
14142 if ( this.accept
) {
14143 this.$input
.attr( 'accept', this.accept
.join( ', ' ) );
14145 this.selectButton
.$button
.append( this.$input
);
14149 * Determine if we should accept this file
14152 * @param {string} File MIME type
14153 * @return {boolean}
14155 OO
.ui
.SelectFileWidget
.prototype.isAllowedType = function ( mimeType
) {
14158 if ( !this.accept
|| !mimeType
) {
14162 for ( i
= 0; i
< this.accept
.length
; i
++ ) {
14163 mimeTest
= this.accept
[ i
];
14164 if ( mimeTest
=== mimeType
) {
14166 } else if ( mimeTest
.substr( -2 ) === '/*' ) {
14167 mimeTest
= mimeTest
.substr( 0, mimeTest
.length
- 1 );
14168 if ( mimeType
.substr( 0, mimeTest
.length
) === mimeTest
) {
14178 * Handle file selection from the input
14181 * @param {jQuery.Event} e
14183 OO
.ui
.SelectFileWidget
.prototype.onFileSelected = function ( e
) {
14184 var file
= OO
.getProp( e
.target
, 'files', 0 ) || null;
14186 if ( file
&& !this.isAllowedType( file
.type
) ) {
14190 this.setValue( file
);
14195 * Handle clear button click events.
14199 OO
.ui
.SelectFileWidget
.prototype.onClearClick = function () {
14200 this.setValue( null );
14205 * Handle key press events.
14208 * @param {jQuery.Event} e Key press event
14210 OO
.ui
.SelectFileWidget
.prototype.onKeyPress = function ( e
) {
14211 if ( this.isSupported
&& !this.isDisabled() && this.$input
&&
14212 ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
14214 this.$input
.click();
14220 * Handle drop target click events.
14223 * @param {jQuery.Event} e Key press event
14225 OO
.ui
.SelectFileWidget
.prototype.onDropTargetClick = function () {
14226 if ( this.isSupported
&& !this.isDisabled() && this.$input
) {
14227 this.$input
.click();
14233 * Handle drag enter and over events
14236 * @param {jQuery.Event} e Drag event
14238 OO
.ui
.SelectFileWidget
.prototype.onDragEnterOrOver = function ( e
) {
14240 droppableFile
= false,
14241 dt
= e
.originalEvent
.dataTransfer
;
14243 e
.preventDefault();
14244 e
.stopPropagation();
14246 if ( this.isDisabled() || !this.isSupported
) {
14247 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14248 dt
.dropEffect
= 'none';
14252 // DataTransferItem and File both have a type property, but in Chrome files
14253 // have no information at this point.
14254 itemOrFile
= OO
.getProp( dt
, 'items', 0 ) || OO
.getProp( dt
, 'files', 0 );
14255 if ( itemOrFile
) {
14256 if ( this.isAllowedType( itemOrFile
.type
) ) {
14257 droppableFile
= true;
14259 // dt.types is Array-like, but not an Array
14260 } else if ( Array
.prototype.indexOf
.call( OO
.getProp( dt
, 'types' ) || [], 'Files' ) !== -1 ) {
14261 // File information is not available at this point for security so just assume
14262 // it is acceptable for now.
14263 // https://bugzilla.mozilla.org/show_bug.cgi?id=640534
14264 droppableFile
= true;
14267 this.$element
.toggleClass( 'oo-ui-selectFileWidget-canDrop', droppableFile
);
14268 if ( !droppableFile
) {
14269 dt
.dropEffect
= 'none';
14276 * Handle drag leave events
14279 * @param {jQuery.Event} e Drag event
14281 OO
.ui
.SelectFileWidget
.prototype.onDragLeave = function () {
14282 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14286 * Handle drop events
14289 * @param {jQuery.Event} e Drop event
14291 OO
.ui
.SelectFileWidget
.prototype.onDrop = function ( e
) {
14293 dt
= e
.originalEvent
.dataTransfer
;
14295 e
.preventDefault();
14296 e
.stopPropagation();
14297 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
14299 if ( this.isDisabled() || !this.isSupported
) {
14303 file
= OO
.getProp( dt
, 'files', 0 );
14304 if ( file
&& !this.isAllowedType( file
.type
) ) {
14308 this.setValue( file
);
14317 OO
.ui
.SelectFileWidget
.prototype.setDisabled = function ( disabled
) {
14318 OO
.ui
.SelectFileWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
14319 if ( this.selectButton
) {
14320 this.selectButton
.setDisabled( disabled
);
14322 if ( this.clearButton
) {
14323 this.clearButton
.setDisabled( disabled
);
14329 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
14330 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
14331 * for a list of icons included in the library.
14334 * // An icon widget with a label
14335 * var myIcon = new OO.ui.IconWidget( {
14337 * iconTitle: 'Help'
14339 * // Create a label.
14340 * var iconLabel = new OO.ui.LabelWidget( {
14343 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
14345 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
14348 * @extends OO.ui.Widget
14349 * @mixins OO.ui.mixin.IconElement
14350 * @mixins OO.ui.mixin.TitledElement
14351 * @mixins OO.ui.mixin.FlaggedElement
14354 * @param {Object} [config] Configuration options
14356 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
14357 // Configuration initialization
14358 config
= config
|| {};
14360 // Parent constructor
14361 OO
.ui
.IconWidget
.parent
.call( this, config
);
14363 // Mixin constructors
14364 OO
.ui
.mixin
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
14365 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
14366 OO
.ui
.mixin
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
14369 this.$element
.addClass( 'oo-ui-iconWidget' );
14374 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
14375 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.IconElement
);
14376 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.TitledElement
);
14377 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.FlaggedElement
);
14379 /* Static Properties */
14381 OO
.ui
.IconWidget
.static.tagName
= 'span';
14384 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
14385 * attention to the status of an item or to clarify the function of a control. For a list of
14386 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
14389 * // Example of an indicator widget
14390 * var indicator1 = new OO.ui.IndicatorWidget( {
14391 * indicator: 'alert'
14394 * // Create a fieldset layout to add a label
14395 * var fieldset = new OO.ui.FieldsetLayout();
14396 * fieldset.addItems( [
14397 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
14399 * $( 'body' ).append( fieldset.$element );
14401 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
14404 * @extends OO.ui.Widget
14405 * @mixins OO.ui.mixin.IndicatorElement
14406 * @mixins OO.ui.mixin.TitledElement
14409 * @param {Object} [config] Configuration options
14411 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
14412 // Configuration initialization
14413 config
= config
|| {};
14415 // Parent constructor
14416 OO
.ui
.IndicatorWidget
.parent
.call( this, config
);
14418 // Mixin constructors
14419 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
14420 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
14423 this.$element
.addClass( 'oo-ui-indicatorWidget' );
14428 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
14429 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.IndicatorElement
);
14430 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.TitledElement
);
14432 /* Static Properties */
14434 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
14437 * InputWidget is the base class for all input widgets, which
14438 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
14439 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
14440 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
14442 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14446 * @extends OO.ui.Widget
14447 * @mixins OO.ui.mixin.FlaggedElement
14448 * @mixins OO.ui.mixin.TabIndexedElement
14449 * @mixins OO.ui.mixin.TitledElement
14450 * @mixins OO.ui.mixin.AccessKeyedElement
14453 * @param {Object} [config] Configuration options
14454 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
14455 * @cfg {string} [value=''] The value of the input.
14456 * @cfg {string} [accessKey=''] The access key of the input.
14457 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
14458 * before it is accepted.
14460 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
14461 // Configuration initialization
14462 config
= config
|| {};
14464 // Parent constructor
14465 OO
.ui
.InputWidget
.parent
.call( this, config
);
14468 this.$input
= this.getInputElement( config
);
14470 this.inputFilter
= config
.inputFilter
;
14472 // Mixin constructors
14473 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
14474 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
14475 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
14476 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$input
} ) );
14479 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
14483 .addClass( 'oo-ui-inputWidget-input' )
14484 .attr( 'name', config
.name
)
14485 .prop( 'disabled', this.isDisabled() );
14487 .addClass( 'oo-ui-inputWidget' )
14488 .append( this.$input
);
14489 this.setValue( config
.value
);
14490 this.setAccessKey( config
.accessKey
);
14495 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
14496 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.FlaggedElement
);
14497 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TabIndexedElement
);
14498 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TitledElement
);
14499 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
14501 /* Static Properties */
14503 OO
.ui
.InputWidget
.static.supportsSimpleLabel
= true;
14510 * A change event is emitted when the value of the input changes.
14512 * @param {string} value
14518 * Get input element.
14520 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
14521 * different circumstances. The element must have a `value` property (like form elements).
14524 * @param {Object} config Configuration options
14525 * @return {jQuery} Input element
14527 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
14528 return $( '<input>' );
14532 * Handle potentially value-changing events.
14535 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
14537 OO
.ui
.InputWidget
.prototype.onEdit = function () {
14539 if ( !this.isDisabled() ) {
14540 // Allow the stack to clear so the value will be updated
14541 setTimeout( function () {
14542 widget
.setValue( widget
.$input
.val() );
14548 * Get the value of the input.
14550 * @return {string} Input value
14552 OO
.ui
.InputWidget
.prototype.getValue = function () {
14553 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14554 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14555 var value
= this.$input
.val();
14556 if ( this.value
!== value
) {
14557 this.setValue( value
);
14563 * Set the direction of the input, either RTL (right-to-left) or LTR (left-to-right).
14565 * @param {boolean} isRTL
14566 * Direction is right-to-left
14568 OO
.ui
.InputWidget
.prototype.setRTL = function ( isRTL
) {
14569 this.$input
.prop( 'dir', isRTL
? 'rtl' : 'ltr' );
14573 * Set the value of the input.
14575 * @param {string} value New value
14579 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
14580 value
= this.cleanUpValue( value
);
14581 // Update the DOM if it has changed. Note that with cleanUpValue, it
14582 // is possible for the DOM value to change without this.value changing.
14583 if ( this.$input
.val() !== value
) {
14584 this.$input
.val( value
);
14586 if ( this.value
!== value
) {
14587 this.value
= value
;
14588 this.emit( 'change', this.value
);
14594 * Set the input's access key.
14595 * FIXME: This is the same code as in OO.ui.mixin.ButtonElement, maybe find a better place for it?
14597 * @param {string} accessKey Input's access key, use empty string to remove
14600 OO
.ui
.InputWidget
.prototype.setAccessKey = function ( accessKey
) {
14601 accessKey
= typeof accessKey
=== 'string' && accessKey
.length
? accessKey
: null;
14603 if ( this.accessKey
!== accessKey
) {
14604 if ( this.$input
) {
14605 if ( accessKey
!== null ) {
14606 this.$input
.attr( 'accesskey', accessKey
);
14608 this.$input
.removeAttr( 'accesskey' );
14611 this.accessKey
= accessKey
;
14618 * Clean up incoming value.
14620 * Ensures value is a string, and converts undefined and null to empty string.
14623 * @param {string} value Original value
14624 * @return {string} Cleaned up value
14626 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
14627 if ( value
=== undefined || value
=== null ) {
14629 } else if ( this.inputFilter
) {
14630 return this.inputFilter( String( value
) );
14632 return String( value
);
14637 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
14638 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
14641 OO
.ui
.InputWidget
.prototype.simulateLabelClick = function () {
14642 if ( !this.isDisabled() ) {
14643 if ( this.$input
.is( ':checkbox, :radio' ) ) {
14644 this.$input
.click();
14646 if ( this.$input
.is( ':input' ) ) {
14647 this.$input
[ 0 ].focus();
14655 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
14656 OO
.ui
.InputWidget
.parent
.prototype.setDisabled
.call( this, state
);
14657 if ( this.$input
) {
14658 this.$input
.prop( 'disabled', this.isDisabled() );
14668 OO
.ui
.InputWidget
.prototype.focus = function () {
14669 this.$input
[ 0 ].focus();
14678 OO
.ui
.InputWidget
.prototype.blur = function () {
14679 this.$input
[ 0 ].blur();
14686 OO
.ui
.InputWidget
.prototype.gatherPreInfuseState = function ( node
) {
14688 state
= OO
.ui
.InputWidget
.parent
.prototype.gatherPreInfuseState
.call( this, node
),
14689 $input
= state
.$input
|| $( node
).find( '.oo-ui-inputWidget-input' );
14690 state
.value
= $input
.val();
14691 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
14692 state
.focus
= $input
.is( ':focus' );
14699 OO
.ui
.InputWidget
.prototype.restorePreInfuseState = function ( state
) {
14700 OO
.ui
.InputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
14701 if ( state
.value
!== undefined && state
.value
!== this.getValue() ) {
14702 this.setValue( state
.value
);
14704 if ( state
.focus
) {
14710 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
14711 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
14712 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
14713 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
14714 * [OOjs UI documentation on MediaWiki] [1] for more information.
14717 * // A ButtonInputWidget rendered as an HTML button, the default.
14718 * var button = new OO.ui.ButtonInputWidget( {
14719 * label: 'Input button',
14723 * $( 'body' ).append( button.$element );
14725 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
14728 * @extends OO.ui.InputWidget
14729 * @mixins OO.ui.mixin.ButtonElement
14730 * @mixins OO.ui.mixin.IconElement
14731 * @mixins OO.ui.mixin.IndicatorElement
14732 * @mixins OO.ui.mixin.LabelElement
14733 * @mixins OO.ui.mixin.TitledElement
14736 * @param {Object} [config] Configuration options
14737 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
14738 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
14739 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
14740 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
14741 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
14743 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
14744 // Configuration initialization
14745 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
14747 // Properties (must be set before parent constructor, which calls #setValue)
14748 this.useInputTag
= config
.useInputTag
;
14750 // Parent constructor
14751 OO
.ui
.ButtonInputWidget
.parent
.call( this, config
);
14753 // Mixin constructors
14754 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
14755 OO
.ui
.mixin
.IconElement
.call( this, config
);
14756 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
14757 OO
.ui
.mixin
.LabelElement
.call( this, config
);
14758 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
14761 if ( !config
.useInputTag
) {
14762 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
14764 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
14769 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
14770 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.ButtonElement
);
14771 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IconElement
);
14772 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
14773 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.LabelElement
);
14774 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.TitledElement
);
14776 /* Static Properties */
14779 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
14780 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
14782 OO
.ui
.ButtonInputWidget
.static.supportsSimpleLabel
= false;
14790 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
14791 var type
= [ 'button', 'submit', 'reset' ].indexOf( config
.type
) !== -1 ?
14794 return $( '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + type
+ '">' );
14800 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
14802 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
14803 * text, or `null` for no label
14806 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
14807 OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.call( this, label
);
14809 if ( this.useInputTag
) {
14810 if ( typeof label
=== 'function' ) {
14811 label
= OO
.ui
.resolveMsg( label
);
14813 if ( label
instanceof jQuery
) {
14814 label
= label
.text();
14819 this.$input
.val( label
);
14826 * Set the value of the input.
14828 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
14829 * they do not support {@link #value values}.
14831 * @param {string} value New value
14834 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
14835 if ( !this.useInputTag
) {
14836 OO
.ui
.ButtonInputWidget
.parent
.prototype.setValue
.call( this, value
);
14842 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
14843 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
14844 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
14845 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
14847 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
14850 * // An example of selected, unselected, and disabled checkbox inputs
14851 * var checkbox1=new OO.ui.CheckboxInputWidget( {
14855 * var checkbox2=new OO.ui.CheckboxInputWidget( {
14858 * var checkbox3=new OO.ui.CheckboxInputWidget( {
14862 * // Create a fieldset layout with fields for each checkbox.
14863 * var fieldset = new OO.ui.FieldsetLayout( {
14864 * label: 'Checkboxes'
14866 * fieldset.addItems( [
14867 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
14868 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
14869 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
14871 * $( 'body' ).append( fieldset.$element );
14873 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
14876 * @extends OO.ui.InputWidget
14879 * @param {Object} [config] Configuration options
14880 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
14882 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
14883 // Configuration initialization
14884 config
= config
|| {};
14886 // Parent constructor
14887 OO
.ui
.CheckboxInputWidget
.parent
.call( this, config
);
14891 .addClass( 'oo-ui-checkboxInputWidget' )
14892 // Required for pretty styling in MediaWiki theme
14893 .append( $( '<span>' ) );
14894 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
14899 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
14907 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
14908 return $( '<input type="checkbox" />' );
14914 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
14916 if ( !this.isDisabled() ) {
14917 // Allow the stack to clear so the value will be updated
14918 setTimeout( function () {
14919 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
14925 * Set selection state of this checkbox.
14927 * @param {boolean} state `true` for selected
14930 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
14932 if ( this.selected
!== state
) {
14933 this.selected
= state
;
14934 this.$input
.prop( 'checked', this.selected
);
14935 this.emit( 'change', this.selected
);
14941 * Check if this checkbox is selected.
14943 * @return {boolean} Checkbox is selected
14945 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
14946 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
14947 // it, and we won't know unless they're kind enough to trigger a 'change' event.
14948 var selected
= this.$input
.prop( 'checked' );
14949 if ( this.selected
!== selected
) {
14950 this.setSelected( selected
);
14952 return this.selected
;
14958 OO
.ui
.CheckboxInputWidget
.prototype.gatherPreInfuseState = function ( node
) {
14960 state
= OO
.ui
.CheckboxInputWidget
.parent
.prototype.gatherPreInfuseState
.call( this, node
),
14961 $input
= $( node
).find( '.oo-ui-inputWidget-input' );
14962 state
.$input
= $input
; // shortcut for performance, used in InputWidget
14963 state
.checked
= $input
.prop( 'checked' );
14970 OO
.ui
.CheckboxInputWidget
.prototype.restorePreInfuseState = function ( state
) {
14971 OO
.ui
.CheckboxInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
14972 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
14973 this.setSelected( state
.checked
);
14978 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
14979 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
14980 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
14981 * more information about input widgets.
14983 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
14984 * are no options. If no `value` configuration option is provided, the first option is selected.
14985 * If you need a state representing no value (no option being selected), use a DropdownWidget.
14987 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
14990 * // Example: A DropdownInputWidget with three options
14991 * var dropdownInput = new OO.ui.DropdownInputWidget( {
14993 * { data: 'a', label: 'First' },
14994 * { data: 'b', label: 'Second'},
14995 * { data: 'c', label: 'Third' }
14998 * $( 'body' ).append( dropdownInput.$element );
15000 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15003 * @extends OO.ui.InputWidget
15004 * @mixins OO.ui.mixin.TitledElement
15007 * @param {Object} [config] Configuration options
15008 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15009 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
15011 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
15012 // Configuration initialization
15013 config
= config
|| {};
15015 // Properties (must be done before parent constructor which calls #setDisabled)
15016 this.dropdownWidget
= new OO
.ui
.DropdownWidget( config
.dropdown
);
15018 // Parent constructor
15019 OO
.ui
.DropdownInputWidget
.parent
.call( this, config
);
15021 // Mixin constructors
15022 OO
.ui
.mixin
.TitledElement
.call( this, config
);
15025 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
15028 this.setOptions( config
.options
|| [] );
15030 .addClass( 'oo-ui-dropdownInputWidget' )
15031 .append( this.dropdownWidget
.$element
);
15036 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
15037 OO
.mixinClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.mixin
.TitledElement
);
15045 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
15046 return $( '<input type="hidden">' );
15050 * Handles menu select events.
15053 * @param {OO.ui.MenuOptionWidget} item Selected menu item
15055 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
15056 this.setValue( item
.getData() );
15062 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
15063 value
= this.cleanUpValue( value
);
15064 this.dropdownWidget
.getMenu().selectItemByData( value
);
15065 OO
.ui
.DropdownInputWidget
.parent
.prototype.setValue
.call( this, value
);
15072 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
15073 this.dropdownWidget
.setDisabled( state
);
15074 OO
.ui
.DropdownInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
15079 * Set the options available for this input.
15081 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15084 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
15086 value
= this.getValue(),
15089 // Rebuild the dropdown menu
15090 this.dropdownWidget
.getMenu()
15092 .addItems( options
.map( function ( opt
) {
15093 var optValue
= widget
.cleanUpValue( opt
.data
);
15094 return new OO
.ui
.MenuOptionWidget( {
15096 label
: opt
.label
!== undefined ? opt
.label
: optValue
15100 // Restore the previous value, or reset to something sensible
15101 if ( this.dropdownWidget
.getMenu().getItemFromData( value
) ) {
15102 // Previous value is still available, ensure consistency with the dropdown
15103 this.setValue( value
);
15105 // No longer valid, reset
15106 if ( options
.length
) {
15107 this.setValue( options
[ 0 ].data
);
15117 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
15118 this.dropdownWidget
.getMenu().toggle( true );
15125 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
15126 this.dropdownWidget
.getMenu().toggle( false );
15131 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
15132 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
15133 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
15134 * please see the [OOjs UI documentation on MediaWiki][1].
15136 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15139 * // An example of selected, unselected, and disabled radio inputs
15140 * var radio1 = new OO.ui.RadioInputWidget( {
15144 * var radio2 = new OO.ui.RadioInputWidget( {
15147 * var radio3 = new OO.ui.RadioInputWidget( {
15151 * // Create a fieldset layout with fields for each radio button.
15152 * var fieldset = new OO.ui.FieldsetLayout( {
15153 * label: 'Radio inputs'
15155 * fieldset.addItems( [
15156 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
15157 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
15158 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
15160 * $( 'body' ).append( fieldset.$element );
15162 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15165 * @extends OO.ui.InputWidget
15168 * @param {Object} [config] Configuration options
15169 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
15171 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
15172 // Configuration initialization
15173 config
= config
|| {};
15175 // Parent constructor
15176 OO
.ui
.RadioInputWidget
.parent
.call( this, config
);
15180 .addClass( 'oo-ui-radioInputWidget' )
15181 // Required for pretty styling in MediaWiki theme
15182 .append( $( '<span>' ) );
15183 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
15188 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
15196 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
15197 return $( '<input type="radio" />' );
15203 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
15204 // RadioInputWidget doesn't track its state.
15208 * Set selection state of this radio button.
15210 * @param {boolean} state `true` for selected
15213 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
15214 // RadioInputWidget doesn't track its state.
15215 this.$input
.prop( 'checked', state
);
15220 * Check if this radio button is selected.
15222 * @return {boolean} Radio is selected
15224 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
15225 return this.$input
.prop( 'checked' );
15231 OO
.ui
.RadioInputWidget
.prototype.gatherPreInfuseState = function ( node
) {
15233 state
= OO
.ui
.RadioInputWidget
.parent
.prototype.gatherPreInfuseState
.call( this, node
),
15234 $input
= $( node
).find( '.oo-ui-inputWidget-input' );
15235 state
.$input
= $input
; // shortcut for performance, used in InputWidget
15236 state
.checked
= $input
.prop( 'checked' );
15243 OO
.ui
.RadioInputWidget
.prototype.restorePreInfuseState = function ( state
) {
15244 OO
.ui
.RadioInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
15245 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
15246 this.setSelected( state
.checked
);
15251 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
15252 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
15253 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
15254 * more information about input widgets.
15256 * This and OO.ui.DropdownInputWidget support the same configuration options.
15259 * // Example: A RadioSelectInputWidget with three options
15260 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
15262 * { data: 'a', label: 'First' },
15263 * { data: 'b', label: 'Second'},
15264 * { data: 'c', label: 'Third' }
15267 * $( 'body' ).append( radioSelectInput.$element );
15269 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15272 * @extends OO.ui.InputWidget
15275 * @param {Object} [config] Configuration options
15276 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
15278 OO
.ui
.RadioSelectInputWidget
= function OoUiRadioSelectInputWidget( config
) {
15279 // Configuration initialization
15280 config
= config
|| {};
15282 // Properties (must be done before parent constructor which calls #setDisabled)
15283 this.radioSelectWidget
= new OO
.ui
.RadioSelectWidget();
15285 // Parent constructor
15286 OO
.ui
.RadioSelectInputWidget
.parent
.call( this, config
);
15289 this.radioSelectWidget
.connect( this, { select
: 'onMenuSelect' } );
15292 this.setOptions( config
.options
|| [] );
15294 .addClass( 'oo-ui-radioSelectInputWidget' )
15295 .append( this.radioSelectWidget
.$element
);
15300 OO
.inheritClass( OO
.ui
.RadioSelectInputWidget
, OO
.ui
.InputWidget
);
15302 /* Static Properties */
15304 OO
.ui
.RadioSelectInputWidget
.static.supportsSimpleLabel
= false;
15312 OO
.ui
.RadioSelectInputWidget
.prototype.getInputElement = function () {
15313 return $( '<input type="hidden">' );
15317 * Handles menu select events.
15320 * @param {OO.ui.RadioOptionWidget} item Selected menu item
15322 OO
.ui
.RadioSelectInputWidget
.prototype.onMenuSelect = function ( item
) {
15323 this.setValue( item
.getData() );
15329 OO
.ui
.RadioSelectInputWidget
.prototype.setValue = function ( value
) {
15330 value
= this.cleanUpValue( value
);
15331 this.radioSelectWidget
.selectItemByData( value
);
15332 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setValue
.call( this, value
);
15339 OO
.ui
.RadioSelectInputWidget
.prototype.setDisabled = function ( state
) {
15340 this.radioSelectWidget
.setDisabled( state
);
15341 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
15346 * Set the options available for this input.
15348 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
15351 OO
.ui
.RadioSelectInputWidget
.prototype.setOptions = function ( options
) {
15353 value
= this.getValue(),
15356 // Rebuild the radioSelect menu
15357 this.radioSelectWidget
15359 .addItems( options
.map( function ( opt
) {
15360 var optValue
= widget
.cleanUpValue( opt
.data
);
15361 return new OO
.ui
.RadioOptionWidget( {
15363 label
: opt
.label
!== undefined ? opt
.label
: optValue
15367 // Restore the previous value, or reset to something sensible
15368 if ( this.radioSelectWidget
.getItemFromData( value
) ) {
15369 // Previous value is still available, ensure consistency with the radioSelect
15370 this.setValue( value
);
15372 // No longer valid, reset
15373 if ( options
.length
) {
15374 this.setValue( options
[ 0 ].data
);
15384 OO
.ui
.RadioSelectInputWidget
.prototype.gatherPreInfuseState = function ( node
) {
15385 var state
= OO
.ui
.RadioSelectInputWidget
.parent
.prototype.gatherPreInfuseState
.call( this, node
);
15386 state
.value
= $( node
).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
15391 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
15392 * size of the field as well as its presentation. In addition, these widgets can be configured
15393 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
15394 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
15395 * which modifies incoming values rather than validating them.
15396 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
15398 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
15401 * // Example of a text input widget
15402 * var textInput = new OO.ui.TextInputWidget( {
15403 * value: 'Text input'
15405 * $( 'body' ).append( textInput.$element );
15407 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
15410 * @extends OO.ui.InputWidget
15411 * @mixins OO.ui.mixin.IconElement
15412 * @mixins OO.ui.mixin.IndicatorElement
15413 * @mixins OO.ui.mixin.PendingElement
15414 * @mixins OO.ui.mixin.LabelElement
15417 * @param {Object} [config] Configuration options
15418 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
15419 * 'email' or 'url'. Ignored if `multiline` is true.
15421 * Some values of `type` result in additional behaviors:
15423 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
15424 * empties the text field
15425 * @cfg {string} [placeholder] Placeholder text
15426 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
15427 * instruct the browser to focus this widget.
15428 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
15429 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
15430 * @cfg {boolean} [multiline=false] Allow multiple lines of text
15431 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
15432 * specifies minimum number of rows to display.
15433 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
15434 * Use the #maxRows config to specify a maximum number of displayed rows.
15435 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
15436 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
15437 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
15438 * the value or placeholder text: `'before'` or `'after'`
15439 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
15440 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
15441 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
15442 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
15443 * (the value must contain only numbers); when RegExp, a regular expression that must match the
15444 * value for it to be considered valid; when Function, a function receiving the value as parameter
15445 * that must return true, or promise resolving to true, for it to be considered valid.
15447 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
15448 // Configuration initialization
15449 config
= $.extend( {
15451 labelPosition
: 'after'
15453 if ( config
.type
=== 'search' ) {
15454 if ( config
.icon
=== undefined ) {
15455 config
.icon
= 'search';
15457 // indicator: 'clear' is set dynamically later, depending on value
15459 if ( config
.required
) {
15460 if ( config
.indicator
=== undefined ) {
15461 config
.indicator
= 'required';
15465 // Parent constructor
15466 OO
.ui
.TextInputWidget
.parent
.call( this, config
);
15468 // Mixin constructors
15469 OO
.ui
.mixin
.IconElement
.call( this, config
);
15470 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
15471 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$input
} ) );
15472 OO
.ui
.mixin
.LabelElement
.call( this, config
);
15475 this.type
= this.getSaneType( config
);
15476 this.readOnly
= false;
15477 this.multiline
= !!config
.multiline
;
15478 this.autosize
= !!config
.autosize
;
15479 this.minRows
= config
.rows
!== undefined ? config
.rows
: '';
15480 this.maxRows
= config
.maxRows
|| Math
.max( 2 * ( this.minRows
|| 0 ), 10 );
15481 this.validate
= null;
15483 // Clone for resizing
15484 if ( this.autosize
) {
15485 this.$clone
= this.$input
15487 .insertAfter( this.$input
)
15488 .attr( 'aria-hidden', 'true' )
15489 .addClass( 'oo-ui-element-hidden' );
15492 this.setValidation( config
.validate
);
15493 this.setLabelPosition( config
.labelPosition
);
15497 keypress
: this.onKeyPress
.bind( this ),
15498 blur
: this.onBlur
.bind( this )
15501 focus
: this.onElementAttach
.bind( this )
15503 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
15504 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
15505 this.on( 'labelChange', this.updatePosition
.bind( this ) );
15506 this.connect( this, {
15507 change
: 'onChange',
15508 disable
: 'onDisable'
15513 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type
)
15514 .append( this.$icon
, this.$indicator
);
15515 this.setReadOnly( !!config
.readOnly
);
15516 this.updateSearchIndicator();
15517 if ( config
.placeholder
) {
15518 this.$input
.attr( 'placeholder', config
.placeholder
);
15520 if ( config
.maxLength
!== undefined ) {
15521 this.$input
.attr( 'maxlength', config
.maxLength
);
15523 if ( config
.autofocus
) {
15524 this.$input
.attr( 'autofocus', 'autofocus' );
15526 if ( config
.required
) {
15527 this.$input
.attr( 'required', 'required' );
15528 this.$input
.attr( 'aria-required', 'true' );
15530 if ( config
.autocomplete
=== false ) {
15531 this.$input
.attr( 'autocomplete', 'off' );
15533 if ( this.multiline
&& config
.rows
) {
15534 this.$input
.attr( 'rows', config
.rows
);
15536 if ( this.label
|| config
.autosize
) {
15537 this.installParentChangeDetector();
15543 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
15544 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IconElement
);
15545 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
15546 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.PendingElement
);
15547 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.LabelElement
);
15549 /* Static Properties */
15551 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
15559 * An `enter` event is emitted when the user presses 'enter' inside the text box.
15561 * Not emitted if the input is multiline.
15569 * Handle icon mouse down events.
15572 * @param {jQuery.Event} e Mouse down event
15575 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
15576 if ( e
.which
=== 1 ) {
15577 this.$input
[ 0 ].focus();
15583 * Handle indicator mouse down events.
15586 * @param {jQuery.Event} e Mouse down event
15589 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
15590 if ( e
.which
=== 1 ) {
15591 if ( this.type
=== 'search' ) {
15592 // Clear the text field
15593 this.setValue( '' );
15595 this.$input
[ 0 ].focus();
15601 * Handle key press events.
15604 * @param {jQuery.Event} e Key press event
15605 * @fires enter If enter key is pressed and input is not multiline
15607 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
15608 if ( e
.which
=== OO
.ui
.Keys
.ENTER
&& !this.multiline
) {
15609 this.emit( 'enter', e
);
15614 * Handle blur events.
15617 * @param {jQuery.Event} e Blur event
15619 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
15620 this.setValidityFlag();
15624 * Handle element attach events.
15627 * @param {jQuery.Event} e Element attach event
15629 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
15630 // Any previously calculated size is now probably invalid if we reattached elsewhere
15631 this.valCache
= null;
15633 this.positionLabel();
15637 * Handle change events.
15639 * @param {string} value
15642 OO
.ui
.TextInputWidget
.prototype.onChange = function () {
15643 this.updateSearchIndicator();
15644 this.setValidityFlag();
15649 * Handle disable events.
15651 * @param {boolean} disabled Element is disabled
15654 OO
.ui
.TextInputWidget
.prototype.onDisable = function () {
15655 this.updateSearchIndicator();
15659 * Check if the input is {@link #readOnly read-only}.
15661 * @return {boolean}
15663 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
15664 return this.readOnly
;
15668 * Set the {@link #readOnly read-only} state of the input.
15670 * @param {boolean} state Make input read-only
15673 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
15674 this.readOnly
= !!state
;
15675 this.$input
.prop( 'readOnly', this.readOnly
);
15676 this.updateSearchIndicator();
15681 * Support function for making #onElementAttach work across browsers.
15683 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
15684 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
15686 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
15687 * first time that the element gets attached to the documented.
15689 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
15690 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
15691 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
15694 if ( MutationObserver
) {
15695 // The new way. If only it wasn't so ugly.
15697 if ( this.$element
.closest( 'html' ).length
) {
15698 // Widget is attached already, do nothing. This breaks the functionality of this function when
15699 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
15700 // would require observation of the whole document, which would hurt performance of other,
15701 // more important code.
15705 // Find topmost node in the tree
15706 topmostNode
= this.$element
[ 0 ];
15707 while ( topmostNode
.parentNode
) {
15708 topmostNode
= topmostNode
.parentNode
;
15711 // We have no way to detect the $element being attached somewhere without observing the entire
15712 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
15713 // parent node of $element, and instead detect when $element is removed from it (and thus
15714 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
15715 // doesn't get attached, we end up back here and create the parent.
15717 mutationObserver
= new MutationObserver( function ( mutations
) {
15718 var i
, j
, removedNodes
;
15719 for ( i
= 0; i
< mutations
.length
; i
++ ) {
15720 removedNodes
= mutations
[ i
].removedNodes
;
15721 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
15722 if ( removedNodes
[ j
] === topmostNode
) {
15723 setTimeout( onRemove
, 0 );
15730 onRemove = function () {
15731 // If the node was attached somewhere else, report it
15732 if ( widget
.$element
.closest( 'html' ).length
) {
15733 widget
.onElementAttach();
15735 mutationObserver
.disconnect();
15736 widget
.installParentChangeDetector();
15739 // Create a fake parent and observe it
15740 fakeParentNode
= $( '<div>' ).append( topmostNode
)[ 0 ];
15741 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
15743 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
15744 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
15745 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
15750 * Automatically adjust the size of the text input.
15752 * This only affects #multiline inputs that are {@link #autosize autosized}.
15756 OO
.ui
.TextInputWidget
.prototype.adjustSize = function () {
15757 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
, idealHeight
;
15759 if ( this.multiline
&& this.autosize
&& this.$input
.val() !== this.valCache
) {
15761 .val( this.$input
.val() )
15762 .attr( 'rows', this.minRows
)
15763 // Set inline height property to 0 to measure scroll height
15764 .css( 'height', 0 );
15766 this.$clone
.removeClass( 'oo-ui-element-hidden' );
15768 this.valCache
= this.$input
.val();
15770 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
15772 // Remove inline height property to measure natural heights
15773 this.$clone
.css( 'height', '' );
15774 innerHeight
= this.$clone
.innerHeight();
15775 outerHeight
= this.$clone
.outerHeight();
15777 // Measure max rows height
15779 .attr( 'rows', this.maxRows
)
15780 .css( 'height', 'auto' )
15782 maxInnerHeight
= this.$clone
.innerHeight();
15784 // Difference between reported innerHeight and scrollHeight with no scrollbars present
15785 // Equals 1 on Blink-based browsers and 0 everywhere else
15786 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
15787 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
15789 this.$clone
.addClass( 'oo-ui-element-hidden' );
15791 // Only apply inline height when expansion beyond natural height is needed
15792 if ( idealHeight
> innerHeight
) {
15793 // Use the difference between the inner and outer height as a buffer
15794 this.$input
.css( 'height', idealHeight
+ ( outerHeight
- innerHeight
) );
15796 this.$input
.css( 'height', '' );
15806 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
15807 return config
.multiline
?
15808 $( '<textarea>' ) :
15809 $( '<input type="' + this.getSaneType( config
) + '" />' );
15813 * Get sanitized value for 'type' for given config.
15815 * @param {Object} config Configuration options
15816 * @return {string|null}
15819 OO
.ui
.TextInputWidget
.prototype.getSaneType = function ( config
) {
15820 var type
= [ 'text', 'password', 'search', 'email', 'url' ].indexOf( config
.type
) !== -1 ?
15823 return config
.multiline
? 'multiline' : type
;
15827 * Check if the input supports multiple lines.
15829 * @return {boolean}
15831 OO
.ui
.TextInputWidget
.prototype.isMultiline = function () {
15832 return !!this.multiline
;
15836 * Check if the input automatically adjusts its size.
15838 * @return {boolean}
15840 OO
.ui
.TextInputWidget
.prototype.isAutosizing = function () {
15841 return !!this.autosize
;
15845 * Select the entire text of the input.
15849 OO
.ui
.TextInputWidget
.prototype.select = function () {
15850 this.$input
.select();
15855 * Focus the input and move the cursor to the end.
15857 OO
.ui
.TextInputWidget
.prototype.moveCursorToEnd = function () {
15859 element
= this.$input
[ 0 ];
15861 if ( element
.selectionStart
!== undefined ) {
15862 element
.selectionStart
= element
.selectionEnd
= element
.value
.length
;
15863 } else if ( element
.createTextRange
) {
15865 textRange
= element
.createTextRange();
15866 textRange
.collapse( false );
15867 textRange
.select();
15872 * Set the validation pattern.
15874 * The validation pattern is either a regular expression, a function, or the symbolic name of a
15875 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
15876 * value must contain only numbers).
15878 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
15879 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
15881 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
15882 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
15883 this.validate
= validate
;
15885 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
15890 * Sets the 'invalid' flag appropriately.
15892 * @param {boolean} [isValid] Optionally override validation result
15894 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
15896 setFlag = function ( valid
) {
15898 widget
.$input
.attr( 'aria-invalid', 'true' );
15900 widget
.$input
.removeAttr( 'aria-invalid' );
15902 widget
.setFlags( { invalid
: !valid
} );
15905 if ( isValid
!== undefined ) {
15906 setFlag( isValid
);
15908 this.getValidity().then( function () {
15917 * Check if a value is valid.
15919 * This method returns a promise that resolves with a boolean `true` if the current value is
15920 * considered valid according to the supplied {@link #validate validation pattern}.
15923 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
15925 OO
.ui
.TextInputWidget
.prototype.isValid = function () {
15928 if ( this.validate
instanceof Function
) {
15929 result
= this.validate( this.getValue() );
15930 if ( $.isFunction( result
.promise
) ) {
15931 return result
.promise();
15933 return $.Deferred().resolve( !!result
).promise();
15936 return $.Deferred().resolve( !!this.getValue().match( this.validate
) ).promise();
15941 * Get the validity of current value.
15943 * This method returns a promise that resolves if the value is valid and rejects if
15944 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
15946 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
15948 OO
.ui
.TextInputWidget
.prototype.getValidity = function () {
15949 var result
, promise
;
15951 function rejectOrResolve( valid
) {
15953 return $.Deferred().resolve().promise();
15955 return $.Deferred().reject().promise();
15959 if ( this.validate
instanceof Function
) {
15960 result
= this.validate( this.getValue() );
15962 if ( $.isFunction( result
.promise
) ) {
15963 promise
= $.Deferred();
15965 result
.then( function ( valid
) {
15975 return promise
.promise();
15977 return rejectOrResolve( result
);
15980 return rejectOrResolve( this.getValue().match( this.validate
) );
15985 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
15987 * @param {string} labelPosition Label position, 'before' or 'after'
15990 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
15991 this.labelPosition
= labelPosition
;
15992 this.updatePosition();
15997 * Deprecated alias of #setLabelPosition
15999 * @deprecated Use setLabelPosition instead.
16001 OO
.ui
.TextInputWidget
.prototype.setPosition
=
16002 OO
.ui
.TextInputWidget
.prototype.setLabelPosition
;
16005 * Update the position of the inline label.
16007 * This method is called by #setLabelPosition, and can also be called on its own if
16008 * something causes the label to be mispositioned.
16012 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
16013 var after
= this.labelPosition
=== 'after';
16016 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
16017 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
16019 this.positionLabel();
16025 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
16026 * already empty or when it's not editable.
16028 OO
.ui
.TextInputWidget
.prototype.updateSearchIndicator = function () {
16029 if ( this.type
=== 'search' ) {
16030 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
16031 this.setIndicator( null );
16033 this.setIndicator( 'clear' );
16039 * Position the label by setting the correct padding on the input.
16044 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
16045 var after
, rtl
, property
;
16046 // Clear old values
16048 // Clear old values if present
16050 'padding-right': '',
16054 if ( this.label
) {
16055 this.$element
.append( this.$label
);
16057 this.$label
.detach();
16061 after
= this.labelPosition
=== 'after';
16062 rtl
= this.$element
.css( 'direction' ) === 'rtl';
16063 property
= after
=== rtl
? 'padding-left' : 'padding-right';
16065 this.$input
.css( property
, this.$label
.outerWidth( true ) );
16073 OO
.ui
.TextInputWidget
.prototype.gatherPreInfuseState = function ( node
) {
16075 state
= OO
.ui
.TextInputWidget
.parent
.prototype.gatherPreInfuseState
.call( this, node
),
16076 $input
= $( node
).find( '.oo-ui-inputWidget-input' );
16077 state
.$input
= $input
; // shortcut for performance, used in InputWidget
16078 if ( this.multiline
) {
16079 state
.scrollTop
= $input
.scrollTop();
16087 OO
.ui
.TextInputWidget
.prototype.restorePreInfuseState = function ( state
) {
16088 OO
.ui
.TextInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
16089 if ( state
.scrollTop
!== undefined ) {
16090 this.$input
.scrollTop( state
.scrollTop
);
16095 * ComboBoxWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
16096 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
16097 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
16099 * - by typing a value in the text input field. If the value exactly matches the value of a menu
16100 * option, that option will appear to be selected.
16101 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
16104 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
16107 * // Example: A ComboBoxWidget.
16108 * var comboBox = new OO.ui.ComboBoxWidget( {
16109 * label: 'ComboBoxWidget',
16110 * input: { value: 'Option One' },
16113 * new OO.ui.MenuOptionWidget( {
16114 * data: 'Option 1',
16115 * label: 'Option One'
16117 * new OO.ui.MenuOptionWidget( {
16118 * data: 'Option 2',
16119 * label: 'Option Two'
16121 * new OO.ui.MenuOptionWidget( {
16122 * data: 'Option 3',
16123 * label: 'Option Three'
16125 * new OO.ui.MenuOptionWidget( {
16126 * data: 'Option 4',
16127 * label: 'Option Four'
16129 * new OO.ui.MenuOptionWidget( {
16130 * data: 'Option 5',
16131 * label: 'Option Five'
16136 * $( 'body' ).append( comboBox.$element );
16138 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
16141 * @extends OO.ui.Widget
16142 * @mixins OO.ui.mixin.TabIndexedElement
16145 * @param {Object} [config] Configuration options
16146 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
16147 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
16148 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
16149 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
16150 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
16152 OO
.ui
.ComboBoxWidget
= function OoUiComboBoxWidget( config
) {
16153 // Configuration initialization
16154 config
= config
|| {};
16156 // Parent constructor
16157 OO
.ui
.ComboBoxWidget
.parent
.call( this, config
);
16159 // Properties (must be set before TabIndexedElement constructor call)
16160 this.$indicator
= this.$( '<span>' );
16162 // Mixin constructors
16163 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$indicator
} ) );
16166 this.$overlay
= config
.$overlay
|| this.$element
;
16167 this.input
= new OO
.ui
.TextInputWidget( $.extend(
16170 $indicator
: this.$indicator
,
16171 disabled
: this.isDisabled()
16175 this.input
.$input
.eq( 0 ).attr( {
16177 'aria-autocomplete': 'list'
16179 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend(
16183 $container
: this.input
.$element
,
16184 disabled
: this.isDisabled()
16190 this.$indicator
.on( {
16191 click
: this.onClick
.bind( this ),
16192 keypress
: this.onKeyPress
.bind( this )
16194 this.input
.connect( this, {
16195 change
: 'onInputChange',
16196 enter
: 'onInputEnter'
16198 this.menu
.connect( this, {
16199 choose
: 'onMenuChoose',
16200 add
: 'onMenuItemsChange',
16201 remove
: 'onMenuItemsChange'
16205 this.$element
.addClass( 'oo-ui-comboBoxWidget' ).append( this.input
.$element
);
16206 this.$overlay
.append( this.menu
.$element
);
16207 this.onMenuItemsChange();
16212 OO
.inheritClass( OO
.ui
.ComboBoxWidget
, OO
.ui
.Widget
);
16213 OO
.mixinClass( OO
.ui
.ComboBoxWidget
, OO
.ui
.mixin
.TabIndexedElement
);
16218 * Get the combobox's menu.
16219 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
16221 OO
.ui
.ComboBoxWidget
.prototype.getMenu = function () {
16226 * Get the combobox's text input widget.
16227 * @return {OO.ui.TextInputWidget} Text input widget
16229 OO
.ui
.ComboBoxWidget
.prototype.getInput = function () {
16234 * Handle input change events.
16237 * @param {string} value New value
16239 OO
.ui
.ComboBoxWidget
.prototype.onInputChange = function ( value
) {
16240 var match
= this.menu
.getItemFromData( value
);
16242 this.menu
.selectItem( match
);
16243 if ( this.menu
.getHighlightedItem() ) {
16244 this.menu
.highlightItem( match
);
16247 if ( !this.isDisabled() ) {
16248 this.menu
.toggle( true );
16253 * Handle mouse click events.
16256 * @param {jQuery.Event} e Mouse click event
16258 OO
.ui
.ComboBoxWidget
.prototype.onClick = function ( e
) {
16259 if ( !this.isDisabled() && e
.which
=== 1 ) {
16260 this.menu
.toggle();
16261 this.input
.$input
[ 0 ].focus();
16267 * Handle key press events.
16270 * @param {jQuery.Event} e Key press event
16272 OO
.ui
.ComboBoxWidget
.prototype.onKeyPress = function ( e
) {
16273 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
16274 this.menu
.toggle();
16275 this.input
.$input
[ 0 ].focus();
16281 * Handle input enter events.
16285 OO
.ui
.ComboBoxWidget
.prototype.onInputEnter = function () {
16286 if ( !this.isDisabled() ) {
16287 this.menu
.toggle( false );
16292 * Handle menu choose events.
16295 * @param {OO.ui.OptionWidget} item Chosen item
16297 OO
.ui
.ComboBoxWidget
.prototype.onMenuChoose = function ( item
) {
16298 this.input
.setValue( item
.getData() );
16302 * Handle menu item change events.
16306 OO
.ui
.ComboBoxWidget
.prototype.onMenuItemsChange = function () {
16307 var match
= this.menu
.getItemFromData( this.input
.getValue() );
16308 this.menu
.selectItem( match
);
16309 if ( this.menu
.getHighlightedItem() ) {
16310 this.menu
.highlightItem( match
);
16312 this.$element
.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu
.isEmpty() );
16318 OO
.ui
.ComboBoxWidget
.prototype.setDisabled = function ( disabled
) {
16320 OO
.ui
.ComboBoxWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
16322 if ( this.input
) {
16323 this.input
.setDisabled( this.isDisabled() );
16326 this.menu
.setDisabled( this.isDisabled() );
16333 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
16334 * be configured with a `label` option that is set to a string, a label node, or a function:
16336 * - String: a plaintext string
16337 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
16338 * label that includes a link or special styling, such as a gray color or additional graphical elements.
16339 * - Function: a function that will produce a string in the future. Functions are used
16340 * in cases where the value of the label is not currently defined.
16342 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
16343 * will come into focus when the label is clicked.
16346 * // Examples of LabelWidgets
16347 * var label1 = new OO.ui.LabelWidget( {
16348 * label: 'plaintext label'
16350 * var label2 = new OO.ui.LabelWidget( {
16351 * label: $( '<a href="default.html">jQuery label</a>' )
16353 * // Create a fieldset layout with fields for each example
16354 * var fieldset = new OO.ui.FieldsetLayout();
16355 * fieldset.addItems( [
16356 * new OO.ui.FieldLayout( label1 ),
16357 * new OO.ui.FieldLayout( label2 )
16359 * $( 'body' ).append( fieldset.$element );
16362 * @extends OO.ui.Widget
16363 * @mixins OO.ui.mixin.LabelElement
16366 * @param {Object} [config] Configuration options
16367 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
16368 * Clicking the label will focus the specified input field.
16370 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
16371 // Configuration initialization
16372 config
= config
|| {};
16374 // Parent constructor
16375 OO
.ui
.LabelWidget
.parent
.call( this, config
);
16377 // Mixin constructors
16378 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
16379 OO
.ui
.mixin
.TitledElement
.call( this, config
);
16382 this.input
= config
.input
;
16385 if ( this.input
instanceof OO
.ui
.InputWidget
) {
16386 this.$element
.on( 'click', this.onClick
.bind( this ) );
16390 this.$element
.addClass( 'oo-ui-labelWidget' );
16395 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
16396 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.LabelElement
);
16397 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.TitledElement
);
16399 /* Static Properties */
16401 OO
.ui
.LabelWidget
.static.tagName
= 'span';
16406 * Handles label mouse click events.
16409 * @param {jQuery.Event} e Mouse click event
16411 OO
.ui
.LabelWidget
.prototype.onClick = function () {
16412 this.input
.simulateLabelClick();
16417 * OptionWidgets are special elements that can be selected and configured with data. The
16418 * data is often unique for each option, but it does not have to be. OptionWidgets are used
16419 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
16420 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
16422 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16425 * @extends OO.ui.Widget
16426 * @mixins OO.ui.mixin.LabelElement
16427 * @mixins OO.ui.mixin.FlaggedElement
16430 * @param {Object} [config] Configuration options
16432 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
16433 // Configuration initialization
16434 config
= config
|| {};
16436 // Parent constructor
16437 OO
.ui
.OptionWidget
.parent
.call( this, config
);
16439 // Mixin constructors
16440 OO
.ui
.mixin
.ItemWidget
.call( this );
16441 OO
.ui
.mixin
.LabelElement
.call( this, config
);
16442 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
16445 this.selected
= false;
16446 this.highlighted
= false;
16447 this.pressed
= false;
16451 .data( 'oo-ui-optionWidget', this )
16452 .attr( 'role', 'option' )
16453 .attr( 'aria-selected', 'false' )
16454 .addClass( 'oo-ui-optionWidget' )
16455 .append( this.$label
);
16460 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
16461 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.ItemWidget
);
16462 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.LabelElement
);
16463 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.FlaggedElement
);
16465 /* Static Properties */
16467 OO
.ui
.OptionWidget
.static.selectable
= true;
16469 OO
.ui
.OptionWidget
.static.highlightable
= true;
16471 OO
.ui
.OptionWidget
.static.pressable
= true;
16473 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
16478 * Check if the option can be selected.
16480 * @return {boolean} Item is selectable
16482 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
16483 return this.constructor.static.selectable
&& !this.isDisabled() && this.isVisible();
16487 * Check if the option can be highlighted. A highlight indicates that the option
16488 * may be selected when a user presses enter or clicks. Disabled items cannot
16491 * @return {boolean} Item is highlightable
16493 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
16494 return this.constructor.static.highlightable
&& !this.isDisabled() && this.isVisible();
16498 * Check if the option can be pressed. The pressed state occurs when a user mouses
16499 * down on an item, but has not yet let go of the mouse.
16501 * @return {boolean} Item is pressable
16503 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
16504 return this.constructor.static.pressable
&& !this.isDisabled() && this.isVisible();
16508 * Check if the option is selected.
16510 * @return {boolean} Item is selected
16512 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
16513 return this.selected
;
16517 * Check if the option is highlighted. A highlight indicates that the
16518 * item may be selected when a user presses enter or clicks.
16520 * @return {boolean} Item is highlighted
16522 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
16523 return this.highlighted
;
16527 * Check if the option is pressed. The pressed state occurs when a user mouses
16528 * down on an item, but has not yet let go of the mouse. The item may appear
16529 * selected, but it will not be selected until the user releases the mouse.
16531 * @return {boolean} Item is pressed
16533 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
16534 return this.pressed
;
16538 * Set the option’s selected state. In general, all modifications to the selection
16539 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
16540 * method instead of this method.
16542 * @param {boolean} [state=false] Select option
16545 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
16546 if ( this.constructor.static.selectable
) {
16547 this.selected
= !!state
;
16549 .toggleClass( 'oo-ui-optionWidget-selected', state
)
16550 .attr( 'aria-selected', state
.toString() );
16551 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
16552 this.scrollElementIntoView();
16554 this.updateThemeClasses();
16560 * Set the option’s highlighted state. In general, all programmatic
16561 * modifications to the highlight should be handled by the
16562 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
16563 * method instead of this method.
16565 * @param {boolean} [state=false] Highlight option
16568 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
16569 if ( this.constructor.static.highlightable
) {
16570 this.highlighted
= !!state
;
16571 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
16572 this.updateThemeClasses();
16578 * Set the option’s pressed state. In general, all
16579 * programmatic modifications to the pressed state should be handled by the
16580 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
16581 * method instead of this method.
16583 * @param {boolean} [state=false] Press option
16586 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
16587 if ( this.constructor.static.pressable
) {
16588 this.pressed
= !!state
;
16589 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
16590 this.updateThemeClasses();
16596 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
16597 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
16598 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
16599 * options. For more information about options and selects, please see the
16600 * [OOjs UI documentation on MediaWiki][1].
16603 * // Decorated options in a select widget
16604 * var select = new OO.ui.SelectWidget( {
16606 * new OO.ui.DecoratedOptionWidget( {
16608 * label: 'Option with icon',
16611 * new OO.ui.DecoratedOptionWidget( {
16613 * label: 'Option with indicator',
16614 * indicator: 'next'
16618 * $( 'body' ).append( select.$element );
16620 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
16623 * @extends OO.ui.OptionWidget
16624 * @mixins OO.ui.mixin.IconElement
16625 * @mixins OO.ui.mixin.IndicatorElement
16628 * @param {Object} [config] Configuration options
16630 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
16631 // Parent constructor
16632 OO
.ui
.DecoratedOptionWidget
.parent
.call( this, config
);
16634 // Mixin constructors
16635 OO
.ui
.mixin
.IconElement
.call( this, config
);
16636 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
16640 .addClass( 'oo-ui-decoratedOptionWidget' )
16641 .prepend( this.$icon
)
16642 .append( this.$indicator
);
16647 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
16648 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IconElement
);
16649 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IndicatorElement
);
16652 * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that
16653 * can be selected and configured with data. The class is
16654 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
16655 * [OOjs UI documentation on MediaWiki] [1] for more information.
16657 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
16660 * @extends OO.ui.DecoratedOptionWidget
16661 * @mixins OO.ui.mixin.ButtonElement
16662 * @mixins OO.ui.mixin.TabIndexedElement
16663 * @mixins OO.ui.mixin.TitledElement
16666 * @param {Object} [config] Configuration options
16668 OO
.ui
.ButtonOptionWidget
= function OoUiButtonOptionWidget( config
) {
16669 // Configuration initialization
16670 config
= config
|| {};
16672 // Parent constructor
16673 OO
.ui
.ButtonOptionWidget
.parent
.call( this, config
);
16675 // Mixin constructors
16676 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
16677 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
16678 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, {
16679 $tabIndexed
: this.$button
,
16684 this.$element
.addClass( 'oo-ui-buttonOptionWidget' );
16685 this.$button
.append( this.$element
.contents() );
16686 this.$element
.append( this.$button
);
16691 OO
.inheritClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
16692 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.ButtonElement
);
16693 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.TitledElement
);
16694 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.TabIndexedElement
);
16696 /* Static Properties */
16698 // Allow button mouse down events to pass through so they can be handled by the parent select widget
16699 OO
.ui
.ButtonOptionWidget
.static.cancelButtonMouseDownEvents
= false;
16701 OO
.ui
.ButtonOptionWidget
.static.highlightable
= false;
16708 OO
.ui
.ButtonOptionWidget
.prototype.setSelected = function ( state
) {
16709 OO
.ui
.ButtonOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
16711 if ( this.constructor.static.selectable
) {
16712 this.setActive( state
);
16719 * RadioOptionWidget is an option widget that looks like a radio button.
16720 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
16721 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
16723 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
16726 * @extends OO.ui.OptionWidget
16729 * @param {Object} [config] Configuration options
16731 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
16732 // Configuration initialization
16733 config
= config
|| {};
16735 // Properties (must be done before parent constructor which calls #setDisabled)
16736 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
16738 // Parent constructor
16739 OO
.ui
.RadioOptionWidget
.parent
.call( this, config
);
16742 this.radio
.$input
.on( 'focus', this.onInputFocus
.bind( this ) );
16745 // Remove implicit role, we're handling it ourselves
16746 this.radio
.$input
.attr( 'role', 'presentation' );
16748 .addClass( 'oo-ui-radioOptionWidget' )
16749 .attr( 'role', 'radio' )
16750 .attr( 'aria-checked', 'false' )
16751 .removeAttr( 'aria-selected' )
16752 .prepend( this.radio
.$element
);
16757 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
16759 /* Static Properties */
16761 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
16763 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
16765 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
16767 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
16772 * @param {jQuery.Event} e Focus event
16775 OO
.ui
.RadioOptionWidget
.prototype.onInputFocus = function () {
16776 this.radio
.$input
.blur();
16777 this.$element
.parent().focus();
16783 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
16784 OO
.ui
.RadioOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
16786 this.radio
.setSelected( state
);
16788 .attr( 'aria-checked', state
.toString() )
16789 .removeAttr( 'aria-selected' );
16797 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
16798 OO
.ui
.RadioOptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
16800 this.radio
.setDisabled( this.isDisabled() );
16806 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
16807 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
16808 * the [OOjs UI documentation on MediaWiki] [1] for more information.
16810 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
16813 * @extends OO.ui.DecoratedOptionWidget
16816 * @param {Object} [config] Configuration options
16818 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
16819 // Configuration initialization
16820 config
= $.extend( { icon
: 'check' }, config
);
16822 // Parent constructor
16823 OO
.ui
.MenuOptionWidget
.parent
.call( this, config
);
16827 .attr( 'role', 'menuitem' )
16828 .addClass( 'oo-ui-menuOptionWidget' );
16833 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
16835 /* Static Properties */
16837 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
16840 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
16841 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
16844 * var myDropdown = new OO.ui.DropdownWidget( {
16847 * new OO.ui.MenuSectionOptionWidget( {
16850 * new OO.ui.MenuOptionWidget( {
16852 * label: 'Welsh Corgi'
16854 * new OO.ui.MenuOptionWidget( {
16856 * label: 'Standard Poodle'
16858 * new OO.ui.MenuSectionOptionWidget( {
16861 * new OO.ui.MenuOptionWidget( {
16868 * $( 'body' ).append( myDropdown.$element );
16871 * @extends OO.ui.DecoratedOptionWidget
16874 * @param {Object} [config] Configuration options
16876 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
16877 // Parent constructor
16878 OO
.ui
.MenuSectionOptionWidget
.parent
.call( this, config
);
16881 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' );
16886 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
16888 /* Static Properties */
16890 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
16892 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
16895 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
16897 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
16898 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
16902 * @extends OO.ui.DecoratedOptionWidget
16905 * @param {Object} [config] Configuration options
16906 * @cfg {number} [level] Indentation level
16907 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
16909 OO
.ui
.OutlineOptionWidget
= function OoUiOutlineOptionWidget( config
) {
16910 // Configuration initialization
16911 config
= config
|| {};
16913 // Parent constructor
16914 OO
.ui
.OutlineOptionWidget
.parent
.call( this, config
);
16918 this.movable
= !!config
.movable
;
16919 this.removable
= !!config
.removable
;
16922 this.$element
.addClass( 'oo-ui-outlineOptionWidget' );
16923 this.setLevel( config
.level
);
16928 OO
.inheritClass( OO
.ui
.OutlineOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
16930 /* Static Properties */
16932 OO
.ui
.OutlineOptionWidget
.static.highlightable
= false;
16934 OO
.ui
.OutlineOptionWidget
.static.scrollIntoViewOnSelect
= true;
16936 OO
.ui
.OutlineOptionWidget
.static.levelClass
= 'oo-ui-outlineOptionWidget-level-';
16938 OO
.ui
.OutlineOptionWidget
.static.levels
= 3;
16943 * Check if item is movable.
16945 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16947 * @return {boolean} Item is movable
16949 OO
.ui
.OutlineOptionWidget
.prototype.isMovable = function () {
16950 return this.movable
;
16954 * Check if item is removable.
16956 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16958 * @return {boolean} Item is removable
16960 OO
.ui
.OutlineOptionWidget
.prototype.isRemovable = function () {
16961 return this.removable
;
16965 * Get indentation level.
16967 * @return {number} Indentation level
16969 OO
.ui
.OutlineOptionWidget
.prototype.getLevel = function () {
16976 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16978 * @param {boolean} movable Item is movable
16981 OO
.ui
.OutlineOptionWidget
.prototype.setMovable = function ( movable
) {
16982 this.movable
= !!movable
;
16983 this.updateThemeClasses();
16988 * Set removability.
16990 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
16992 * @param {boolean} movable Item is removable
16995 OO
.ui
.OutlineOptionWidget
.prototype.setRemovable = function ( removable
) {
16996 this.removable
= !!removable
;
16997 this.updateThemeClasses();
17002 * Set indentation level.
17004 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
17007 OO
.ui
.OutlineOptionWidget
.prototype.setLevel = function ( level
) {
17008 var levels
= this.constructor.static.levels
,
17009 levelClass
= this.constructor.static.levelClass
,
17012 this.level
= level
? Math
.max( 0, Math
.min( levels
- 1, level
) ) : 0;
17014 if ( this.level
=== i
) {
17015 this.$element
.addClass( levelClass
+ i
);
17017 this.$element
.removeClass( levelClass
+ i
);
17020 this.updateThemeClasses();
17026 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
17028 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
17029 * {@link OO.ui.CardLayout card layouts}. See {@link OO.ui.IndexLayout IndexLayout}
17033 * @extends OO.ui.OptionWidget
17036 * @param {Object} [config] Configuration options
17038 OO
.ui
.TabOptionWidget
= function OoUiTabOptionWidget( config
) {
17039 // Configuration initialization
17040 config
= config
|| {};
17042 // Parent constructor
17043 OO
.ui
.TabOptionWidget
.parent
.call( this, config
);
17046 this.$element
.addClass( 'oo-ui-tabOptionWidget' );
17051 OO
.inheritClass( OO
.ui
.TabOptionWidget
, OO
.ui
.OptionWidget
);
17053 /* Static Properties */
17055 OO
.ui
.TabOptionWidget
.static.highlightable
= false;
17058 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
17059 * By default, each popup has an anchor that points toward its origin.
17060 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
17063 * // A popup widget.
17064 * var popup = new OO.ui.PopupWidget( {
17065 * $content: $( '<p>Hi there!</p>' ),
17070 * $( 'body' ).append( popup.$element );
17071 * // To display the popup, toggle the visibility to 'true'.
17072 * popup.toggle( true );
17074 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
17077 * @extends OO.ui.Widget
17078 * @mixins OO.ui.mixin.LabelElement
17079 * @mixins OO.ui.mixin.ClippableElement
17082 * @param {Object} [config] Configuration options
17083 * @cfg {number} [width=320] Width of popup in pixels
17084 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
17085 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
17086 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
17087 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
17088 * popup is leaning towards the right of the screen.
17089 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
17090 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
17091 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
17092 * sentence in the given language.
17093 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
17094 * See the [OOjs UI docs on MediaWiki][3] for an example.
17095 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
17096 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
17097 * @cfg {jQuery} [$content] Content to append to the popup's body
17098 * @cfg {jQuery} [$footer] Content to append to the popup's footer
17099 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
17100 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
17101 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
17103 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
17104 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
17106 * @cfg {boolean} [padded] Add padding to the popup's body
17108 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
17109 // Configuration initialization
17110 config
= config
|| {};
17112 // Parent constructor
17113 OO
.ui
.PopupWidget
.parent
.call( this, config
);
17115 // Properties (must be set before ClippableElement constructor call)
17116 this.$body
= $( '<div>' );
17117 this.$popup
= $( '<div>' );
17119 // Mixin constructors
17120 OO
.ui
.mixin
.LabelElement
.call( this, config
);
17121 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, {
17122 $clippable
: this.$body
,
17123 $clippableContainer
: this.$popup
17127 this.$head
= $( '<div>' );
17128 this.$footer
= $( '<div>' );
17129 this.$anchor
= $( '<div>' );
17130 // If undefined, will be computed lazily in updateDimensions()
17131 this.$container
= config
.$container
;
17132 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
17133 this.autoClose
= !!config
.autoClose
;
17134 this.$autoCloseIgnore
= config
.$autoCloseIgnore
;
17135 this.transitionTimeout
= null;
17136 this.anchor
= null;
17137 this.width
= config
.width
!== undefined ? config
.width
: 320;
17138 this.height
= config
.height
!== undefined ? config
.height
: null;
17139 this.setAlignment( config
.align
);
17140 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
17141 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
17142 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
17145 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
17148 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
17149 this.$body
.addClass( 'oo-ui-popupWidget-body' );
17150 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
17152 .addClass( 'oo-ui-popupWidget-head' )
17153 .append( this.$label
, this.closeButton
.$element
);
17154 this.$footer
.addClass( 'oo-ui-popupWidget-footer' );
17155 if ( !config
.head
) {
17156 this.$head
.addClass( 'oo-ui-element-hidden' );
17158 if ( !config
.$footer
) {
17159 this.$footer
.addClass( 'oo-ui-element-hidden' );
17162 .addClass( 'oo-ui-popupWidget-popup' )
17163 .append( this.$head
, this.$body
, this.$footer
);
17165 .addClass( 'oo-ui-popupWidget' )
17166 .append( this.$popup
, this.$anchor
);
17167 // Move content, which was added to #$element by OO.ui.Widget, to the body
17168 if ( config
.$content
instanceof jQuery
) {
17169 this.$body
.append( config
.$content
);
17171 if ( config
.$footer
instanceof jQuery
) {
17172 this.$footer
.append( config
.$footer
);
17174 if ( config
.padded
) {
17175 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
17178 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
17179 // that reference properties not initialized at that time of parent class construction
17180 // TODO: Find a better way to handle post-constructor setup
17181 this.visible
= false;
17182 this.$element
.addClass( 'oo-ui-element-hidden' );
17187 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
17188 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.LabelElement
);
17189 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.ClippableElement
);
17194 * Handles mouse down events.
17197 * @param {MouseEvent} e Mouse down event
17199 OO
.ui
.PopupWidget
.prototype.onMouseDown = function ( e
) {
17201 this.isVisible() &&
17202 !$.contains( this.$element
[ 0 ], e
.target
) &&
17203 ( !this.$autoCloseIgnore
|| !this.$autoCloseIgnore
.has( e
.target
).length
)
17205 this.toggle( false );
17210 * Bind mouse down listener.
17214 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
17215 // Capture clicks outside popup
17216 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler
);
17220 * Handles close button click events.
17224 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
17225 if ( this.isVisible() ) {
17226 this.toggle( false );
17231 * Unbind mouse down listener.
17235 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
17236 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'mousedown', this.onMouseDownHandler
);
17240 * Handles key down events.
17243 * @param {KeyboardEvent} e Key down event
17245 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
17247 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
17250 this.toggle( false );
17251 e
.preventDefault();
17252 e
.stopPropagation();
17257 * Bind key down listener.
17261 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
17262 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler
);
17266 * Unbind key down listener.
17270 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
17271 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onDocumentKeyDownHandler
);
17275 * Show, hide, or toggle the visibility of the anchor.
17277 * @param {boolean} [show] Show anchor, omit to toggle
17279 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
17280 show
= show
=== undefined ? !this.anchored
: !!show
;
17282 if ( this.anchored
!== show
) {
17284 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
17286 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
17288 this.anchored
= show
;
17293 * Check if the anchor is visible.
17295 * @return {boolean} Anchor is visible
17297 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
17298 return this.anchor
;
17304 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
17306 show
= show
=== undefined ? !this.isVisible() : !!show
;
17308 change
= show
!== this.isVisible();
17311 OO
.ui
.PopupWidget
.parent
.prototype.toggle
.call( this, show
);
17315 if ( this.autoClose
) {
17316 this.bindMouseDownListener();
17317 this.bindKeyDownListener();
17319 this.updateDimensions();
17320 this.toggleClipping( true );
17322 this.toggleClipping( false );
17323 if ( this.autoClose
) {
17324 this.unbindMouseDownListener();
17325 this.unbindKeyDownListener();
17334 * Set the size of the popup.
17336 * Changing the size may also change the popup's position depending on the alignment.
17338 * @param {number} width Width in pixels
17339 * @param {number} height Height in pixels
17340 * @param {boolean} [transition=false] Use a smooth transition
17343 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
17344 this.width
= width
;
17345 this.height
= height
!== undefined ? height
: null;
17346 if ( this.isVisible() ) {
17347 this.updateDimensions( transition
);
17352 * Update the size and position.
17354 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
17355 * be called automatically.
17357 * @param {boolean} [transition=false] Use a smooth transition
17360 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
17361 var popupOffset
, originOffset
, containerLeft
, containerWidth
, containerRight
,
17362 popupLeft
, popupRight
, overlapLeft
, overlapRight
, anchorWidth
,
17363 align
= this.align
,
17366 if ( !this.$container
) {
17367 // Lazy-initialize $container if not specified in constructor
17368 this.$container
= $( this.getClosestScrollableElementContainer() );
17371 // Set height and width before measuring things, since it might cause our measurements
17372 // to change (e.g. due to scrollbars appearing or disappearing)
17375 height
: this.height
!== null ? this.height
: 'auto'
17378 // If we are in RTL, we need to flip the alignment, unless it is center
17379 if ( align
=== 'forwards' || align
=== 'backwards' ) {
17380 if ( this.$container
.css( 'direction' ) === 'rtl' ) {
17381 align
= ( { forwards
: 'force-left', backwards
: 'force-right' } )[ this.align
];
17383 align
= ( { forwards
: 'force-right', backwards
: 'force-left' } )[ this.align
];
17388 // Compute initial popupOffset based on alignment
17389 popupOffset
= this.width
* ( { 'force-left': -1, center
: -0.5, 'force-right': 0 } )[ align
];
17391 // Figure out if this will cause the popup to go beyond the edge of the container
17392 originOffset
= this.$element
.offset().left
;
17393 containerLeft
= this.$container
.offset().left
;
17394 containerWidth
= this.$container
.innerWidth();
17395 containerRight
= containerLeft
+ containerWidth
;
17396 popupLeft
= popupOffset
- this.containerPadding
;
17397 popupRight
= popupOffset
+ this.containerPadding
+ this.width
+ this.containerPadding
;
17398 overlapLeft
= ( originOffset
+ popupLeft
) - containerLeft
;
17399 overlapRight
= containerRight
- ( originOffset
+ popupRight
);
17401 // Adjust offset to make the popup not go beyond the edge, if needed
17402 if ( overlapRight
< 0 ) {
17403 popupOffset
+= overlapRight
;
17404 } else if ( overlapLeft
< 0 ) {
17405 popupOffset
-= overlapLeft
;
17408 // Adjust offset to avoid anchor being rendered too close to the edge
17409 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
17410 // TODO: Find a measurement that works for CSS anchors and image anchors
17411 anchorWidth
= this.$anchor
[ 0 ].scrollWidth
* 2;
17412 if ( popupOffset
+ this.width
< anchorWidth
) {
17413 popupOffset
= anchorWidth
- this.width
;
17414 } else if ( -popupOffset
< anchorWidth
) {
17415 popupOffset
= -anchorWidth
;
17418 // Prevent transition from being interrupted
17419 clearTimeout( this.transitionTimeout
);
17420 if ( transition
) {
17421 // Enable transition
17422 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
17425 // Position body relative to anchor
17426 this.$popup
.css( 'margin-left', popupOffset
);
17428 if ( transition
) {
17429 // Prevent transitioning after transition is complete
17430 this.transitionTimeout
= setTimeout( function () {
17431 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
17434 // Prevent transitioning immediately
17435 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
17438 // Reevaluate clipping state since we've relocated and resized the popup
17445 * Set popup alignment
17446 * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17447 * `backwards` or `forwards`.
17449 OO
.ui
.PopupWidget
.prototype.setAlignment = function ( align
) {
17450 // Validate alignment and transform deprecated values
17451 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align
) > -1 ) {
17452 this.align
= { left
: 'force-right', right
: 'force-left' }[ align
] || align
;
17454 this.align
= 'center';
17459 * Get popup alignment
17460 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
17461 * `backwards` or `forwards`.
17463 OO
.ui
.PopupWidget
.prototype.getAlignment = function () {
17468 * Progress bars visually display the status of an operation, such as a download,
17469 * and can be either determinate or indeterminate:
17471 * - **determinate** process bars show the percent of an operation that is complete.
17473 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
17474 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
17475 * not use percentages.
17477 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
17480 * // Examples of determinate and indeterminate progress bars.
17481 * var progressBar1 = new OO.ui.ProgressBarWidget( {
17484 * var progressBar2 = new OO.ui.ProgressBarWidget();
17486 * // Create a FieldsetLayout to layout progress bars
17487 * var fieldset = new OO.ui.FieldsetLayout;
17488 * fieldset.addItems( [
17489 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
17490 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
17492 * $( 'body' ).append( fieldset.$element );
17495 * @extends OO.ui.Widget
17498 * @param {Object} [config] Configuration options
17499 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
17500 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
17501 * By default, the progress bar is indeterminate.
17503 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
17504 // Configuration initialization
17505 config
= config
|| {};
17507 // Parent constructor
17508 OO
.ui
.ProgressBarWidget
.parent
.call( this, config
);
17511 this.$bar
= $( '<div>' );
17512 this.progress
= null;
17515 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
17516 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
17519 role
: 'progressbar',
17520 'aria-valuemin': 0,
17521 'aria-valuemax': 100
17523 .addClass( 'oo-ui-progressBarWidget' )
17524 .append( this.$bar
);
17529 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
17531 /* Static Properties */
17533 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
17538 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
17540 * @return {number|boolean} Progress percent
17542 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
17543 return this.progress
;
17547 * Set the percent of the process completed or `false` for an indeterminate process.
17549 * @param {number|boolean} progress Progress percent or `false` for indeterminate
17551 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
17552 this.progress
= progress
;
17554 if ( progress
!== false ) {
17555 this.$bar
.css( 'width', this.progress
+ '%' );
17556 this.$element
.attr( 'aria-valuenow', this.progress
);
17558 this.$bar
.css( 'width', '' );
17559 this.$element
.removeAttr( 'aria-valuenow' );
17561 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress
);
17565 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
17566 * and a menu of search results, which is displayed beneath the query
17567 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
17568 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
17569 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
17571 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
17572 * the [OOjs UI demos][1] for an example.
17574 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
17577 * @extends OO.ui.Widget
17580 * @param {Object} [config] Configuration options
17581 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
17582 * @cfg {string} [value] Initial query value
17584 OO
.ui
.SearchWidget
= function OoUiSearchWidget( config
) {
17585 // Configuration initialization
17586 config
= config
|| {};
17588 // Parent constructor
17589 OO
.ui
.SearchWidget
.parent
.call( this, config
);
17592 this.query
= new OO
.ui
.TextInputWidget( {
17594 placeholder
: config
.placeholder
,
17595 value
: config
.value
17597 this.results
= new OO
.ui
.SelectWidget();
17598 this.$query
= $( '<div>' );
17599 this.$results
= $( '<div>' );
17602 this.query
.connect( this, {
17603 change
: 'onQueryChange',
17604 enter
: 'onQueryEnter'
17606 this.query
.$input
.on( 'keydown', this.onQueryKeydown
.bind( this ) );
17610 .addClass( 'oo-ui-searchWidget-query' )
17611 .append( this.query
.$element
);
17613 .addClass( 'oo-ui-searchWidget-results' )
17614 .append( this.results
.$element
);
17616 .addClass( 'oo-ui-searchWidget' )
17617 .append( this.$results
, this.$query
);
17622 OO
.inheritClass( OO
.ui
.SearchWidget
, OO
.ui
.Widget
);
17627 * Handle query key down events.
17630 * @param {jQuery.Event} e Key down event
17632 OO
.ui
.SearchWidget
.prototype.onQueryKeydown = function ( e
) {
17633 var highlightedItem
, nextItem
,
17634 dir
= e
.which
=== OO
.ui
.Keys
.DOWN
? 1 : ( e
.which
=== OO
.ui
.Keys
.UP
? -1 : 0 );
17637 highlightedItem
= this.results
.getHighlightedItem();
17638 if ( !highlightedItem
) {
17639 highlightedItem
= this.results
.getSelectedItem();
17641 nextItem
= this.results
.getRelativeSelectableItem( highlightedItem
, dir
);
17642 this.results
.highlightItem( nextItem
);
17643 nextItem
.scrollElementIntoView();
17648 * Handle select widget select events.
17650 * Clears existing results. Subclasses should repopulate items according to new query.
17653 * @param {string} value New value
17655 OO
.ui
.SearchWidget
.prototype.onQueryChange = function () {
17657 this.results
.clearItems();
17661 * Handle select widget enter key events.
17663 * Chooses highlighted item.
17666 * @param {string} value New value
17668 OO
.ui
.SearchWidget
.prototype.onQueryEnter = function () {
17670 this.results
.chooseItem( this.results
.getHighlightedItem() );
17674 * Get the query input.
17676 * @return {OO.ui.TextInputWidget} Query input
17678 OO
.ui
.SearchWidget
.prototype.getQuery = function () {
17683 * Get the search results menu.
17685 * @return {OO.ui.SelectWidget} Menu of search results
17687 OO
.ui
.SearchWidget
.prototype.getResults = function () {
17688 return this.results
;
17692 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
17693 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
17694 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
17697 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
17698 * information, please see the [OOjs UI documentation on MediaWiki][1].
17701 * // Example of a select widget with three options
17702 * var select = new OO.ui.SelectWidget( {
17704 * new OO.ui.OptionWidget( {
17706 * label: 'Option One',
17708 * new OO.ui.OptionWidget( {
17710 * label: 'Option Two',
17712 * new OO.ui.OptionWidget( {
17714 * label: 'Option Three',
17718 * $( 'body' ).append( select.$element );
17720 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17724 * @extends OO.ui.Widget
17725 * @mixins OO.ui.mixin.GroupWidget
17728 * @param {Object} [config] Configuration options
17729 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
17730 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
17731 * the [OOjs UI documentation on MediaWiki] [2] for examples.
17732 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
17734 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
17735 // Configuration initialization
17736 config
= config
|| {};
17738 // Parent constructor
17739 OO
.ui
.SelectWidget
.parent
.call( this, config
);
17741 // Mixin constructors
17742 OO
.ui
.mixin
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
17745 this.pressed
= false;
17746 this.selecting
= null;
17747 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
17748 this.onMouseMoveHandler
= this.onMouseMove
.bind( this );
17749 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
17750 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
17751 this.keyPressBuffer
= '';
17752 this.keyPressBufferTimer
= null;
17755 this.connect( this, {
17758 this.$element
.on( {
17759 mousedown
: this.onMouseDown
.bind( this ),
17760 mouseover
: this.onMouseOver
.bind( this ),
17761 mouseleave
: this.onMouseLeave
.bind( this )
17766 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
17767 .attr( 'role', 'listbox' );
17768 if ( Array
.isArray( config
.items
) ) {
17769 this.addItems( config
.items
);
17775 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
17777 // Need to mixin base class as well
17778 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupElement
);
17779 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupWidget
);
17782 OO
.ui
.SelectWidget
.static.passAllFilter = function () {
17791 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
17793 * @param {OO.ui.OptionWidget|null} item Highlighted item
17799 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
17800 * pressed state of an option.
17802 * @param {OO.ui.OptionWidget|null} item Pressed item
17808 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
17810 * @param {OO.ui.OptionWidget|null} item Selected item
17815 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
17816 * @param {OO.ui.OptionWidget} item Chosen item
17822 * An `add` event is emitted when options are added to the select with the #addItems method.
17824 * @param {OO.ui.OptionWidget[]} items Added items
17825 * @param {number} index Index of insertion point
17831 * A `remove` event is emitted when options are removed from the select with the #clearItems
17832 * or #removeItems methods.
17834 * @param {OO.ui.OptionWidget[]} items Removed items
17840 * Handle mouse down events.
17843 * @param {jQuery.Event} e Mouse down event
17845 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
17848 if ( !this.isDisabled() && e
.which
=== 1 ) {
17849 this.togglePressed( true );
17850 item
= this.getTargetItem( e
);
17851 if ( item
&& item
.isSelectable() ) {
17852 this.pressItem( item
);
17853 this.selecting
= item
;
17854 OO
.ui
.addCaptureEventListener(
17855 this.getElementDocument(),
17857 this.onMouseUpHandler
17859 OO
.ui
.addCaptureEventListener(
17860 this.getElementDocument(),
17862 this.onMouseMoveHandler
17870 * Handle mouse up events.
17873 * @param {jQuery.Event} e Mouse up event
17875 OO
.ui
.SelectWidget
.prototype.onMouseUp = function ( e
) {
17878 this.togglePressed( false );
17879 if ( !this.selecting
) {
17880 item
= this.getTargetItem( e
);
17881 if ( item
&& item
.isSelectable() ) {
17882 this.selecting
= item
;
17885 if ( !this.isDisabled() && e
.which
=== 1 && this.selecting
) {
17886 this.pressItem( null );
17887 this.chooseItem( this.selecting
);
17888 this.selecting
= null;
17891 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mouseup',
17892 this.onMouseUpHandler
);
17893 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mousemove',
17894 this.onMouseMoveHandler
);
17900 * Handle mouse move events.
17903 * @param {jQuery.Event} e Mouse move event
17905 OO
.ui
.SelectWidget
.prototype.onMouseMove = function ( e
) {
17908 if ( !this.isDisabled() && this.pressed
) {
17909 item
= this.getTargetItem( e
);
17910 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
17911 this.pressItem( item
);
17912 this.selecting
= item
;
17919 * Handle mouse over events.
17922 * @param {jQuery.Event} e Mouse over event
17924 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
17927 if ( !this.isDisabled() ) {
17928 item
= this.getTargetItem( e
);
17929 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
17935 * Handle mouse leave events.
17938 * @param {jQuery.Event} e Mouse over event
17940 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
17941 if ( !this.isDisabled() ) {
17942 this.highlightItem( null );
17948 * Handle key down events.
17951 * @param {jQuery.Event} e Key down event
17953 OO
.ui
.SelectWidget
.prototype.onKeyDown = function ( e
) {
17956 currentItem
= this.getHighlightedItem() || this.getSelectedItem();
17958 if ( !this.isDisabled() && this.isVisible() ) {
17959 switch ( e
.keyCode
) {
17960 case OO
.ui
.Keys
.ENTER
:
17961 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
17962 // Was only highlighted, now let's select it. No-op if already selected.
17963 this.chooseItem( currentItem
);
17967 case OO
.ui
.Keys
.UP
:
17968 case OO
.ui
.Keys
.LEFT
:
17969 this.clearKeyPressBuffer();
17970 nextItem
= this.getRelativeSelectableItem( currentItem
, -1 );
17973 case OO
.ui
.Keys
.DOWN
:
17974 case OO
.ui
.Keys
.RIGHT
:
17975 this.clearKeyPressBuffer();
17976 nextItem
= this.getRelativeSelectableItem( currentItem
, 1 );
17979 case OO
.ui
.Keys
.ESCAPE
:
17980 case OO
.ui
.Keys
.TAB
:
17981 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
17982 currentItem
.setHighlighted( false );
17984 this.unbindKeyDownListener();
17985 this.unbindKeyPressListener();
17986 // Don't prevent tabbing away / defocusing
17992 if ( nextItem
.constructor.static.highlightable
) {
17993 this.highlightItem( nextItem
);
17995 this.chooseItem( nextItem
);
17997 nextItem
.scrollElementIntoView();
18001 // Can't just return false, because e is not always a jQuery event
18002 e
.preventDefault();
18003 e
.stopPropagation();
18009 * Bind key down listener.
18013 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
18014 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler
);
18018 * Unbind key down listener.
18022 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
18023 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'keydown', this.onKeyDownHandler
);
18027 * Clear the key-press buffer
18031 OO
.ui
.SelectWidget
.prototype.clearKeyPressBuffer = function () {
18032 if ( this.keyPressBufferTimer
) {
18033 clearTimeout( this.keyPressBufferTimer
);
18034 this.keyPressBufferTimer
= null;
18036 this.keyPressBuffer
= '';
18040 * Handle key press events.
18043 * @param {jQuery.Event} e Key press event
18045 OO
.ui
.SelectWidget
.prototype.onKeyPress = function ( e
) {
18046 var c
, filter
, item
;
18048 if ( !e
.charCode
) {
18049 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.keyPressBuffer
!== '' ) {
18050 this.keyPressBuffer
= this.keyPressBuffer
.substr( 0, this.keyPressBuffer
.length
- 1 );
18055 if ( String
.fromCodePoint
) {
18056 c
= String
.fromCodePoint( e
.charCode
);
18058 c
= String
.fromCharCode( e
.charCode
);
18061 if ( this.keyPressBufferTimer
) {
18062 clearTimeout( this.keyPressBufferTimer
);
18064 this.keyPressBufferTimer
= setTimeout( this.clearKeyPressBuffer
.bind( this ), 1500 );
18066 item
= this.getHighlightedItem() || this.getSelectedItem();
18068 if ( this.keyPressBuffer
=== c
) {
18069 // Common (if weird) special case: typing "xxxx" will cycle through all
18070 // the items beginning with "x".
18072 item
= this.getRelativeSelectableItem( item
, 1 );
18075 this.keyPressBuffer
+= c
;
18078 filter
= this.getItemMatcher( this.keyPressBuffer
, false );
18079 if ( !item
|| !filter( item
) ) {
18080 item
= this.getRelativeSelectableItem( item
, 1, filter
);
18083 if ( item
.constructor.static.highlightable
) {
18084 this.highlightItem( item
);
18086 this.chooseItem( item
);
18088 item
.scrollElementIntoView();
18095 * Get a matcher for the specific string
18098 * @param {string} s String to match against items
18099 * @param {boolean} [exact=false] Only accept exact matches
18100 * @return {Function} function ( OO.ui.OptionItem ) => boolean
18102 OO
.ui
.SelectWidget
.prototype.getItemMatcher = function ( s
, exact
) {
18105 if ( s
.normalize
) {
18108 s
= exact
? s
.trim() : s
.replace( /^\s+/, '' );
18109 re
= '^\\s*' + s
.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
18113 re
= new RegExp( re
, 'i' );
18114 return function ( item
) {
18115 var l
= item
.getLabel();
18116 if ( typeof l
!== 'string' ) {
18117 l
= item
.$label
.text();
18119 if ( l
.normalize
) {
18122 return re
.test( l
);
18127 * Bind key press listener.
18131 OO
.ui
.SelectWidget
.prototype.bindKeyPressListener = function () {
18132 OO
.ui
.addCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler
);
18136 * Unbind key down listener.
18138 * If you override this, be sure to call this.clearKeyPressBuffer() from your
18143 OO
.ui
.SelectWidget
.prototype.unbindKeyPressListener = function () {
18144 OO
.ui
.removeCaptureEventListener( this.getElementWindow(), 'keypress', this.onKeyPressHandler
);
18145 this.clearKeyPressBuffer();
18149 * Visibility change handler
18152 * @param {boolean} visible
18154 OO
.ui
.SelectWidget
.prototype.onToggle = function ( visible
) {
18156 this.clearKeyPressBuffer();
18161 * Get the closest item to a jQuery.Event.
18164 * @param {jQuery.Event} e
18165 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
18167 OO
.ui
.SelectWidget
.prototype.getTargetItem = function ( e
) {
18168 return $( e
.target
).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
18172 * Get selected item.
18174 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
18176 OO
.ui
.SelectWidget
.prototype.getSelectedItem = function () {
18179 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18180 if ( this.items
[ i
].isSelected() ) {
18181 return this.items
[ i
];
18188 * Get highlighted item.
18190 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
18192 OO
.ui
.SelectWidget
.prototype.getHighlightedItem = function () {
18195 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18196 if ( this.items
[ i
].isHighlighted() ) {
18197 return this.items
[ i
];
18204 * Toggle pressed state.
18206 * Press is a state that occurs when a user mouses down on an item, but
18207 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
18208 * until the user releases the mouse.
18210 * @param {boolean} pressed An option is being pressed
18212 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
18213 if ( pressed
=== undefined ) {
18214 pressed
= !this.pressed
;
18216 if ( pressed
!== this.pressed
) {
18218 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
18219 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
18220 this.pressed
= pressed
;
18225 * Highlight an option. If the `item` param is omitted, no options will be highlighted
18226 * and any existing highlight will be removed. The highlight is mutually exclusive.
18228 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
18232 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
18233 var i
, len
, highlighted
,
18236 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18237 highlighted
= this.items
[ i
] === item
;
18238 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
18239 this.items
[ i
].setHighlighted( highlighted
);
18244 this.emit( 'highlight', item
);
18251 * Fetch an item by its label.
18253 * @param {string} label Label of the item to select.
18254 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18255 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
18257 OO
.ui
.SelectWidget
.prototype.getItemFromLabel = function ( label
, prefix
) {
18258 var i
, item
, found
,
18259 len
= this.items
.length
,
18260 filter
= this.getItemMatcher( label
, true );
18262 for ( i
= 0; i
< len
; i
++ ) {
18263 item
= this.items
[ i
];
18264 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
18271 filter
= this.getItemMatcher( label
, false );
18272 for ( i
= 0; i
< len
; i
++ ) {
18273 item
= this.items
[ i
];
18274 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
18290 * Programmatically select an option by its label. If the item does not exist,
18291 * all options will be deselected.
18293 * @param {string} [label] Label of the item to select.
18294 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
18298 OO
.ui
.SelectWidget
.prototype.selectItemByLabel = function ( label
, prefix
) {
18299 var itemFromLabel
= this.getItemFromLabel( label
, !!prefix
);
18300 if ( label
=== undefined || !itemFromLabel
) {
18301 return this.selectItem();
18303 return this.selectItem( itemFromLabel
);
18307 * Programmatically select an option by its data. If the `data` parameter is omitted,
18308 * or if the item does not exist, all options will be deselected.
18310 * @param {Object|string} [data] Value of the item to select, omit to deselect all
18314 OO
.ui
.SelectWidget
.prototype.selectItemByData = function ( data
) {
18315 var itemFromData
= this.getItemFromData( data
);
18316 if ( data
=== undefined || !itemFromData
) {
18317 return this.selectItem();
18319 return this.selectItem( itemFromData
);
18323 * Programmatically select an option by its reference. If the `item` parameter is omitted,
18324 * all options will be deselected.
18326 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
18330 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
18331 var i
, len
, selected
,
18334 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18335 selected
= this.items
[ i
] === item
;
18336 if ( this.items
[ i
].isSelected() !== selected
) {
18337 this.items
[ i
].setSelected( selected
);
18342 this.emit( 'select', item
);
18351 * Press is a state that occurs when a user mouses down on an item, but has not
18352 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
18353 * releases the mouse.
18355 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
18359 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
18360 var i
, len
, pressed
,
18363 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18364 pressed
= this.items
[ i
] === item
;
18365 if ( this.items
[ i
].isPressed() !== pressed
) {
18366 this.items
[ i
].setPressed( pressed
);
18371 this.emit( 'press', item
);
18380 * Note that ‘choose’ should never be modified programmatically. A user can choose
18381 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
18382 * use the #selectItem method.
18384 * This method is identical to #selectItem, but may vary in subclasses that take additional action
18385 * when users choose an item with the keyboard or mouse.
18387 * @param {OO.ui.OptionWidget} item Item to choose
18391 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
18392 this.selectItem( item
);
18393 this.emit( 'choose', item
);
18399 * Get an option by its position relative to the specified item (or to the start of the option array,
18400 * if item is `null`). The direction in which to search through the option array is specified with a
18401 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
18402 * `null` if there are no options in the array.
18404 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
18405 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
18406 * @param {Function} filter Only consider items for which this function returns
18407 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
18408 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
18410 OO
.ui
.SelectWidget
.prototype.getRelativeSelectableItem = function ( item
, direction
, filter
) {
18411 var currentIndex
, nextIndex
, i
,
18412 increase
= direction
> 0 ? 1 : -1,
18413 len
= this.items
.length
;
18415 if ( !$.isFunction( filter
) ) {
18416 filter
= OO
.ui
.SelectWidget
.static.passAllFilter
;
18419 if ( item
instanceof OO
.ui
.OptionWidget
) {
18420 currentIndex
= this.items
.indexOf( item
);
18421 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
18423 // If no item is selected and moving forward, start at the beginning.
18424 // If moving backward, start at the end.
18425 nextIndex
= direction
> 0 ? 0 : len
- 1;
18428 for ( i
= 0; i
< len
; i
++ ) {
18429 item
= this.items
[ nextIndex
];
18430 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
18433 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
18439 * Get the next selectable item or `null` if there are no selectable items.
18440 * Disabled options and menu-section markers and breaks are not selectable.
18442 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
18444 OO
.ui
.SelectWidget
.prototype.getFirstSelectableItem = function () {
18447 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
18448 item
= this.items
[ i
];
18449 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() ) {
18458 * Add an array of options to the select. Optionally, an index number can be used to
18459 * specify an insertion point.
18461 * @param {OO.ui.OptionWidget[]} items Items to add
18462 * @param {number} [index] Index to insert items after
18466 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
18468 OO
.ui
.mixin
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
18470 // Always provide an index, even if it was omitted
18471 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
18477 * Remove the specified array of options from the select. Options will be detached
18478 * from the DOM, not removed, so they can be reused later. To remove all options from
18479 * the select, you may wish to use the #clearItems method instead.
18481 * @param {OO.ui.OptionWidget[]} items Items to remove
18485 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
18488 // Deselect items being removed
18489 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
18491 if ( item
.isSelected() ) {
18492 this.selectItem( null );
18497 OO
.ui
.mixin
.GroupWidget
.prototype.removeItems
.call( this, items
);
18499 this.emit( 'remove', items
);
18505 * Clear all options from the select. Options will be detached from the DOM, not removed,
18506 * so that they can be reused later. To remove a subset of options from the select, use
18507 * the #removeItems method.
18512 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
18513 var items
= this.items
.slice();
18516 OO
.ui
.mixin
.GroupWidget
.prototype.clearItems
.call( this );
18519 this.selectItem( null );
18521 this.emit( 'remove', items
);
18527 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
18528 * button options and is used together with
18529 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
18530 * highlighting, choosing, and selecting mutually exclusive options. Please see
18531 * the [OOjs UI documentation on MediaWiki] [1] for more information.
18534 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
18535 * var option1 = new OO.ui.ButtonOptionWidget( {
18537 * label: 'Option 1',
18538 * title: 'Button option 1'
18541 * var option2 = new OO.ui.ButtonOptionWidget( {
18543 * label: 'Option 2',
18544 * title: 'Button option 2'
18547 * var option3 = new OO.ui.ButtonOptionWidget( {
18549 * label: 'Option 3',
18550 * title: 'Button option 3'
18553 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
18554 * items: [ option1, option2, option3 ]
18556 * $( 'body' ).append( buttonSelect.$element );
18558 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18561 * @extends OO.ui.SelectWidget
18562 * @mixins OO.ui.mixin.TabIndexedElement
18565 * @param {Object} [config] Configuration options
18567 OO
.ui
.ButtonSelectWidget
= function OoUiButtonSelectWidget( config
) {
18568 // Parent constructor
18569 OO
.ui
.ButtonSelectWidget
.parent
.call( this, config
);
18571 // Mixin constructors
18572 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
18575 this.$element
.on( {
18576 focus
: this.bindKeyDownListener
.bind( this ),
18577 blur
: this.unbindKeyDownListener
.bind( this )
18581 this.$element
.addClass( 'oo-ui-buttonSelectWidget' );
18586 OO
.inheritClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.SelectWidget
);
18587 OO
.mixinClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
18590 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
18591 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
18592 * an interface for adding, removing and selecting options.
18593 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18595 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
18596 * OO.ui.RadioSelectInputWidget instead.
18599 * // A RadioSelectWidget with RadioOptions.
18600 * var option1 = new OO.ui.RadioOptionWidget( {
18602 * label: 'Selected radio option'
18605 * var option2 = new OO.ui.RadioOptionWidget( {
18607 * label: 'Unselected radio option'
18610 * var radioSelect=new OO.ui.RadioSelectWidget( {
18611 * items: [ option1, option2 ]
18614 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
18615 * radioSelect.selectItem( option1 );
18617 * $( 'body' ).append( radioSelect.$element );
18619 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18623 * @extends OO.ui.SelectWidget
18624 * @mixins OO.ui.mixin.TabIndexedElement
18627 * @param {Object} [config] Configuration options
18629 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
18630 // Parent constructor
18631 OO
.ui
.RadioSelectWidget
.parent
.call( this, config
);
18633 // Mixin constructors
18634 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
18637 this.$element
.on( {
18638 focus
: this.bindKeyDownListener
.bind( this ),
18639 blur
: this.unbindKeyDownListener
.bind( this )
18644 .addClass( 'oo-ui-radioSelectWidget' )
18645 .attr( 'role', 'radiogroup' );
18650 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
18651 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
18654 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
18655 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
18656 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxWidget ComboBoxWidget},
18657 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
18658 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
18659 * and customized to be opened, closed, and displayed as needed.
18661 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
18662 * mouse outside the menu.
18664 * Menus also have support for keyboard interaction:
18666 * - Enter/Return key: choose and select a menu option
18667 * - Up-arrow key: highlight the previous menu option
18668 * - Down-arrow key: highlight the next menu option
18669 * - Esc key: hide the menu
18671 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
18672 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
18675 * @extends OO.ui.SelectWidget
18676 * @mixins OO.ui.mixin.ClippableElement
18679 * @param {Object} [config] Configuration options
18680 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
18681 * the text the user types. This config is used by {@link OO.ui.ComboBoxWidget ComboBoxWidget}
18682 * and {@link OO.ui.mixin.LookupElement LookupElement}
18683 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
18684 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiSelectWidget CapsuleMultiSelectWidget}
18685 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
18686 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
18687 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
18688 * that button, unless the button (or its parent widget) is passed in here.
18689 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
18690 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
18692 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
18693 // Configuration initialization
18694 config
= config
|| {};
18696 // Parent constructor
18697 OO
.ui
.MenuSelectWidget
.parent
.call( this, config
);
18699 // Mixin constructors
18700 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
18703 this.newItems
= null;
18704 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
18705 this.filterFromInput
= !!config
.filterFromInput
;
18706 this.$input
= config
.$input
? config
.$input
: config
.input
? config
.input
.$input
: null;
18707 this.$widget
= config
.widget
? config
.widget
.$element
: null;
18708 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
18709 this.onInputEditHandler
= OO
.ui
.debounce( this.updateItemVisibility
.bind( this ), 100 );
18713 .addClass( 'oo-ui-menuSelectWidget' )
18714 .attr( 'role', 'menu' );
18716 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
18717 // that reference properties not initialized at that time of parent class construction
18718 // TODO: Find a better way to handle post-constructor setup
18719 this.visible
= false;
18720 this.$element
.addClass( 'oo-ui-element-hidden' );
18725 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
18726 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.ClippableElement
);
18731 * Handles document mouse down events.
18734 * @param {jQuery.Event} e Key down event
18736 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
18738 !OO
.ui
.contains( this.$element
[ 0 ], e
.target
, true ) &&
18739 ( !this.$widget
|| !OO
.ui
.contains( this.$widget
[ 0 ], e
.target
, true ) )
18741 this.toggle( false );
18748 OO
.ui
.MenuSelectWidget
.prototype.onKeyDown = function ( e
) {
18749 var currentItem
= this.getHighlightedItem() || this.getSelectedItem();
18751 if ( !this.isDisabled() && this.isVisible() ) {
18752 switch ( e
.keyCode
) {
18753 case OO
.ui
.Keys
.LEFT
:
18754 case OO
.ui
.Keys
.RIGHT
:
18755 // Do nothing if a text field is associated, arrow keys will be handled natively
18756 if ( !this.$input
) {
18757 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
18760 case OO
.ui
.Keys
.ESCAPE
:
18761 case OO
.ui
.Keys
.TAB
:
18762 if ( currentItem
) {
18763 currentItem
.setHighlighted( false );
18765 this.toggle( false );
18766 // Don't prevent tabbing away, prevent defocusing
18767 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
18768 e
.preventDefault();
18769 e
.stopPropagation();
18773 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
18780 * Update menu item visibility after input changes.
18783 OO
.ui
.MenuSelectWidget
.prototype.updateItemVisibility = function () {
18785 len
= this.items
.length
,
18786 showAll
= !this.isVisible(),
18787 filter
= showAll
? null : this.getItemMatcher( this.$input
.val() );
18789 for ( i
= 0; i
< len
; i
++ ) {
18790 item
= this.items
[ i
];
18791 if ( item
instanceof OO
.ui
.OptionWidget
) {
18792 item
.toggle( showAll
|| filter( item
) );
18796 // Reevaluate clipping
18803 OO
.ui
.MenuSelectWidget
.prototype.bindKeyDownListener = function () {
18804 if ( this.$input
) {
18805 this.$input
.on( 'keydown', this.onKeyDownHandler
);
18807 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyDownListener
.call( this );
18814 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyDownListener = function () {
18815 if ( this.$input
) {
18816 this.$input
.off( 'keydown', this.onKeyDownHandler
);
18818 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyDownListener
.call( this );
18825 OO
.ui
.MenuSelectWidget
.prototype.bindKeyPressListener = function () {
18826 if ( this.$input
) {
18827 if ( this.filterFromInput
) {
18828 this.$input
.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
18831 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyPressListener
.call( this );
18838 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyPressListener = function () {
18839 if ( this.$input
) {
18840 if ( this.filterFromInput
) {
18841 this.$input
.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
18842 this.updateItemVisibility();
18845 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyPressListener
.call( this );
18852 * When a user chooses an item, the menu is closed.
18854 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
18855 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
18856 * @param {OO.ui.OptionWidget} item Item to choose
18859 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
18860 OO
.ui
.MenuSelectWidget
.parent
.prototype.chooseItem
.call( this, item
);
18861 this.toggle( false );
18868 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
18872 OO
.ui
.MenuSelectWidget
.parent
.prototype.addItems
.call( this, items
, index
);
18875 if ( !this.newItems
) {
18876 this.newItems
= [];
18879 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
18881 if ( this.isVisible() ) {
18882 // Defer fitting label until item has been attached
18885 this.newItems
.push( item
);
18889 // Reevaluate clipping
18898 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
18900 OO
.ui
.MenuSelectWidget
.parent
.prototype.removeItems
.call( this, items
);
18902 // Reevaluate clipping
18911 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
18913 OO
.ui
.MenuSelectWidget
.parent
.prototype.clearItems
.call( this );
18915 // Reevaluate clipping
18924 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
18925 var i
, len
, change
;
18927 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
18928 change
= visible
!== this.isVisible();
18931 OO
.ui
.MenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
18935 this.bindKeyDownListener();
18936 this.bindKeyPressListener();
18938 if ( this.newItems
&& this.newItems
.length
) {
18939 for ( i
= 0, len
= this.newItems
.length
; i
< len
; i
++ ) {
18940 this.newItems
[ i
].fitLabel();
18942 this.newItems
= null;
18944 this.toggleClipping( true );
18947 if ( this.autoHide
) {
18948 OO
.ui
.addCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler
);
18951 this.unbindKeyDownListener();
18952 this.unbindKeyPressListener();
18953 OO
.ui
.removeCaptureEventListener( this.getElementDocument(), 'mousedown', this.onDocumentMouseDownHandler
);
18954 this.toggleClipping( false );
18962 * FloatingMenuSelectWidget is a menu that will stick under a specified
18963 * container, even when it is inserted elsewhere in the document (for example,
18964 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
18965 * menu from being clipped too aggresively.
18967 * The menu's position is automatically calculated and maintained when the menu
18968 * is toggled or the window is resized.
18970 * See OO.ui.ComboBoxWidget for an example of a widget that uses this class.
18973 * @extends OO.ui.MenuSelectWidget
18974 * @mixins OO.ui.mixin.FloatableElement
18977 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
18978 * Deprecated, omit this parameter and specify `$container` instead.
18979 * @param {Object} [config] Configuration options
18980 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
18982 OO
.ui
.FloatingMenuSelectWidget
= function OoUiFloatingMenuSelectWidget( inputWidget
, config
) {
18983 // Allow 'inputWidget' parameter and config for backwards compatibility
18984 if ( OO
.isPlainObject( inputWidget
) && config
=== undefined ) {
18985 config
= inputWidget
;
18986 inputWidget
= config
.inputWidget
;
18989 // Configuration initialization
18990 config
= config
|| {};
18992 // Parent constructor
18993 OO
.ui
.FloatingMenuSelectWidget
.parent
.call( this, config
);
18995 // Properties (must be set before mixin constructors)
18996 this.inputWidget
= inputWidget
; // For backwards compatibility
18997 this.$container
= config
.$container
|| this.inputWidget
.$element
;
18999 // Mixins constructors
19000 OO
.ui
.mixin
.FloatableElement
.call( this, $.extend( {}, config
, { $floatableContainer
: this.$container
} ) );
19003 this.$element
.addClass( 'oo-ui-floatingMenuSelectWidget' );
19004 // For backwards compatibility
19005 this.$element
.addClass( 'oo-ui-textInputMenuSelectWidget' );
19010 OO
.inheritClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.MenuSelectWidget
);
19011 OO
.mixinClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.mixin
.FloatableElement
);
19013 // For backwards compatibility
19014 OO
.ui
.TextInputMenuSelectWidget
= OO
.ui
.FloatingMenuSelectWidget
;
19021 OO
.ui
.FloatingMenuSelectWidget
.prototype.toggle = function ( visible
) {
19023 visible
= visible
=== undefined ? !this.isVisible() : !!visible
;
19024 change
= visible
!== this.isVisible();
19026 if ( change
&& visible
) {
19027 // Make sure the width is set before the parent method runs.
19028 this.setIdealSize( this.$container
.width() );
19032 // This will call this.clip(), which is nonsensical since we're not positioned yet...
19033 OO
.ui
.FloatingMenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
19036 this.togglePositioning( this.isVisible() );
19043 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
19044 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
19046 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
19049 * @extends OO.ui.SelectWidget
19050 * @mixins OO.ui.mixin.TabIndexedElement
19053 * @param {Object} [config] Configuration options
19055 OO
.ui
.OutlineSelectWidget
= function OoUiOutlineSelectWidget( config
) {
19056 // Parent constructor
19057 OO
.ui
.OutlineSelectWidget
.parent
.call( this, config
);
19059 // Mixin constructors
19060 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
19063 this.$element
.on( {
19064 focus
: this.bindKeyDownListener
.bind( this ),
19065 blur
: this.unbindKeyDownListener
.bind( this )
19069 this.$element
.addClass( 'oo-ui-outlineSelectWidget' );
19074 OO
.inheritClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.SelectWidget
);
19075 OO
.mixinClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
19078 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
19080 * **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.**
19083 * @extends OO.ui.SelectWidget
19084 * @mixins OO.ui.mixin.TabIndexedElement
19087 * @param {Object} [config] Configuration options
19089 OO
.ui
.TabSelectWidget
= function OoUiTabSelectWidget( config
) {
19090 // Parent constructor
19091 OO
.ui
.TabSelectWidget
.parent
.call( this, config
);
19093 // Mixin constructors
19094 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
19097 this.$element
.on( {
19098 focus
: this.bindKeyDownListener
.bind( this ),
19099 blur
: this.unbindKeyDownListener
.bind( this )
19103 this.$element
.addClass( 'oo-ui-tabSelectWidget' );
19108 OO
.inheritClass( OO
.ui
.TabSelectWidget
, OO
.ui
.SelectWidget
);
19109 OO
.mixinClass( OO
.ui
.TabSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
19112 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
19113 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
19114 * (to adjust the value in increments) to allow the user to enter a number.
19117 * // Example: A NumberInputWidget.
19118 * var numberInput = new OO.ui.NumberInputWidget( {
19119 * label: 'NumberInputWidget',
19120 * input: { value: 5, min: 1, max: 10 }
19122 * $( 'body' ).append( numberInput.$element );
19125 * @extends OO.ui.Widget
19128 * @param {Object} [config] Configuration options
19129 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
19130 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
19131 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
19132 * @cfg {boolean} [isInteger=false] Whether the field accepts only integer values.
19133 * @cfg {number} [min=-Infinity] Minimum allowed value
19134 * @cfg {number} [max=Infinity] Maximum allowed value
19135 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
19136 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
19138 OO
.ui
.NumberInputWidget
= function OoUiNumberInputWidget( config
) {
19139 // Configuration initialization
19140 config
= $.extend( {
19148 // Parent constructor
19149 OO
.ui
.NumberInputWidget
.parent
.call( this, config
);
19152 this.input
= new OO
.ui
.TextInputWidget( $.extend(
19154 disabled
: this.isDisabled()
19158 this.minusButton
= new OO
.ui
.ButtonWidget( $.extend(
19160 disabled
: this.isDisabled(),
19163 config
.minusButton
,
19165 classes
: [ 'oo-ui-numberInputWidget-minusButton' ],
19169 this.plusButton
= new OO
.ui
.ButtonWidget( $.extend(
19171 disabled
: this.isDisabled(),
19176 classes
: [ 'oo-ui-numberInputWidget-plusButton' ],
19182 this.input
.connect( this, {
19183 change
: this.emit
.bind( this, 'change' ),
19184 enter
: this.emit
.bind( this, 'enter' )
19186 this.input
.$input
.on( {
19187 keydown
: this.onKeyDown
.bind( this ),
19188 'wheel mousewheel DOMMouseScroll': this.onWheel
.bind( this )
19190 this.plusButton
.connect( this, {
19191 click
: [ 'onButtonClick', +1 ]
19193 this.minusButton
.connect( this, {
19194 click
: [ 'onButtonClick', -1 ]
19198 this.setIsInteger( !!config
.isInteger
);
19199 this.setRange( config
.min
, config
.max
);
19200 this.setStep( config
.step
, config
.pageStep
);
19202 this.$field
= $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' )
19204 this.minusButton
.$element
,
19205 this.input
.$element
,
19206 this.plusButton
.$element
19208 this.$element
.addClass( 'oo-ui-numberInputWidget' ).append( this.$field
);
19209 this.input
.setValidation( this.validateNumber
.bind( this ) );
19214 OO
.inheritClass( OO
.ui
.NumberInputWidget
, OO
.ui
.Widget
);
19219 * A `change` event is emitted when the value of the input changes.
19225 * An `enter` event is emitted when the user presses 'enter' inside the text box.
19233 * Set whether only integers are allowed
19234 * @param {boolean} flag
19236 OO
.ui
.NumberInputWidget
.prototype.setIsInteger = function ( flag
) {
19237 this.isInteger
= !!flag
;
19238 this.input
.setValidityFlag();
19242 * Get whether only integers are allowed
19243 * @return {boolean} Flag value
19245 OO
.ui
.NumberInputWidget
.prototype.getIsInteger = function () {
19246 return this.isInteger
;
19250 * Set the range of allowed values
19251 * @param {number} min Minimum allowed value
19252 * @param {number} max Maximum allowed value
19254 OO
.ui
.NumberInputWidget
.prototype.setRange = function ( min
, max
) {
19256 throw new Error( 'Minimum (' + min
+ ') must not be greater than maximum (' + max
+ ')' );
19260 this.input
.setValidityFlag();
19264 * Get the current range
19265 * @return {number[]} Minimum and maximum values
19267 OO
.ui
.NumberInputWidget
.prototype.getRange = function () {
19268 return [ this.min
, this.max
];
19272 * Set the stepping deltas
19273 * @param {number} step Normal step
19274 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
19276 OO
.ui
.NumberInputWidget
.prototype.setStep = function ( step
, pageStep
) {
19278 throw new Error( 'Step value must be positive' );
19280 if ( pageStep
=== null ) {
19281 pageStep
= step
* 10;
19282 } else if ( pageStep
<= 0 ) {
19283 throw new Error( 'Page step value must be positive' );
19286 this.pageStep
= pageStep
;
19290 * Get the current stepping values
19291 * @return {number[]} Step and page step
19293 OO
.ui
.NumberInputWidget
.prototype.getStep = function () {
19294 return [ this.step
, this.pageStep
];
19298 * Get the current value of the widget
19301 OO
.ui
.NumberInputWidget
.prototype.getValue = function () {
19302 return this.input
.getValue();
19306 * Get the current value of the widget as a number
19307 * @return {number} May be NaN, or an invalid number
19309 OO
.ui
.NumberInputWidget
.prototype.getNumericValue = function () {
19310 return +this.input
.getValue();
19314 * Set the value of the widget
19315 * @param {string} value Invalid values are allowed
19317 OO
.ui
.NumberInputWidget
.prototype.setValue = function ( value
) {
19318 this.input
.setValue( value
);
19322 * Adjust the value of the widget
19323 * @param {number} delta Adjustment amount
19325 OO
.ui
.NumberInputWidget
.prototype.adjustValue = function ( delta
) {
19326 var n
, v
= this.getNumericValue();
19329 if ( isNaN( delta
) || !isFinite( delta
) ) {
19330 throw new Error( 'Delta must be a finite number' );
19333 if ( isNaN( v
) ) {
19337 n
= Math
.max( Math
.min( n
, this.max
), this.min
);
19338 if ( this.isInteger
) {
19339 n
= Math
.round( n
);
19344 this.setValue( n
);
19351 * @param {string} value Field value
19352 * @return {boolean}
19354 OO
.ui
.NumberInputWidget
.prototype.validateNumber = function ( value
) {
19356 if ( isNaN( n
) || !isFinite( n
) ) {
19360 /*jshint bitwise: false */
19361 if ( this.isInteger
&& ( n
| 0 ) !== n
) {
19364 /*jshint bitwise: true */
19366 if ( n
< this.min
|| n
> this.max
) {
19374 * Handle mouse click events.
19377 * @param {number} dir +1 or -1
19379 OO
.ui
.NumberInputWidget
.prototype.onButtonClick = function ( dir
) {
19380 this.adjustValue( dir
* this.step
);
19384 * Handle mouse wheel events.
19387 * @param {jQuery.Event} event
19389 OO
.ui
.NumberInputWidget
.prototype.onWheel = function ( event
) {
19392 // Standard 'wheel' event
19393 if ( event
.originalEvent
.deltaMode
!== undefined ) {
19394 this.sawWheelEvent
= true;
19396 if ( event
.originalEvent
.deltaY
) {
19397 delta
= -event
.originalEvent
.deltaY
;
19398 } else if ( event
.originalEvent
.deltaX
) {
19399 delta
= event
.originalEvent
.deltaX
;
19402 // Non-standard events
19403 if ( !this.sawWheelEvent
) {
19404 if ( event
.originalEvent
.wheelDeltaX
) {
19405 delta
= -event
.originalEvent
.wheelDeltaX
;
19406 } else if ( event
.originalEvent
.wheelDeltaY
) {
19407 delta
= event
.originalEvent
.wheelDeltaY
;
19408 } else if ( event
.originalEvent
.wheelDelta
) {
19409 delta
= event
.originalEvent
.wheelDelta
;
19410 } else if ( event
.originalEvent
.detail
) {
19411 delta
= -event
.originalEvent
.detail
;
19416 delta
= delta
< 0 ? -1 : 1;
19417 this.adjustValue( delta
* this.step
);
19424 * Handle key down events.
19427 * @param {jQuery.Event} e Key down event
19429 OO
.ui
.NumberInputWidget
.prototype.onKeyDown = function ( e
) {
19430 if ( !this.isDisabled() ) {
19431 switch ( e
.which
) {
19432 case OO
.ui
.Keys
.UP
:
19433 this.adjustValue( this.step
);
19435 case OO
.ui
.Keys
.DOWN
:
19436 this.adjustValue( -this.step
);
19438 case OO
.ui
.Keys
.PAGEUP
:
19439 this.adjustValue( this.pageStep
);
19441 case OO
.ui
.Keys
.PAGEDOWN
:
19442 this.adjustValue( -this.pageStep
);
19451 OO
.ui
.NumberInputWidget
.prototype.setDisabled = function ( disabled
) {
19453 OO
.ui
.NumberInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
19455 if ( this.input
) {
19456 this.input
.setDisabled( this.isDisabled() );
19458 if ( this.minusButton
) {
19459 this.minusButton
.setDisabled( this.isDisabled() );
19461 if ( this.plusButton
) {
19462 this.plusButton
.setDisabled( this.isDisabled() );
19469 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
19470 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
19471 * visually by a slider in the leftmost position.
19474 * // Toggle switches in the 'off' and 'on' position.
19475 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
19476 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
19480 * // Create a FieldsetLayout to layout and label switches
19481 * var fieldset = new OO.ui.FieldsetLayout( {
19482 * label: 'Toggle switches'
19484 * fieldset.addItems( [
19485 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
19486 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
19488 * $( 'body' ).append( fieldset.$element );
19491 * @extends OO.ui.ToggleWidget
19492 * @mixins OO.ui.mixin.TabIndexedElement
19495 * @param {Object} [config] Configuration options
19496 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
19497 * By default, the toggle switch is in the 'off' position.
19499 OO
.ui
.ToggleSwitchWidget
= function OoUiToggleSwitchWidget( config
) {
19500 // Parent constructor
19501 OO
.ui
.ToggleSwitchWidget
.parent
.call( this, config
);
19503 // Mixin constructors
19504 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
19507 this.dragging
= false;
19508 this.dragStart
= null;
19509 this.sliding
= false;
19510 this.$glow
= $( '<span>' );
19511 this.$grip
= $( '<span>' );
19514 this.$element
.on( {
19515 click
: this.onClick
.bind( this ),
19516 keypress
: this.onKeyPress
.bind( this )
19520 this.$glow
.addClass( 'oo-ui-toggleSwitchWidget-glow' );
19521 this.$grip
.addClass( 'oo-ui-toggleSwitchWidget-grip' );
19523 .addClass( 'oo-ui-toggleSwitchWidget' )
19524 .attr( 'role', 'checkbox' )
19525 .append( this.$glow
, this.$grip
);
19530 OO
.inheritClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.ToggleWidget
);
19531 OO
.mixinClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.mixin
.TabIndexedElement
);
19536 * Handle mouse click events.
19539 * @param {jQuery.Event} e Mouse click event
19541 OO
.ui
.ToggleSwitchWidget
.prototype.onClick = function ( e
) {
19542 if ( !this.isDisabled() && e
.which
=== 1 ) {
19543 this.setValue( !this.value
);
19549 * Handle key press events.
19552 * @param {jQuery.Event} e Key press event
19554 OO
.ui
.ToggleSwitchWidget
.prototype.onKeyPress = function ( e
) {
19555 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
19556 this.setValue( !this.value
);
19562 * Deprecated aliases for classes in the `OO.ui.mixin` namespace.
19566 * @inheritdoc OO.ui.mixin.ButtonElement
19567 * @deprecated Use {@link OO.ui.mixin.ButtonElement} instead.
19569 OO
.ui
.ButtonElement
= OO
.ui
.mixin
.ButtonElement
;
19572 * @inheritdoc OO.ui.mixin.ClippableElement
19573 * @deprecated Use {@link OO.ui.mixin.ClippableElement} instead.
19575 OO
.ui
.ClippableElement
= OO
.ui
.mixin
.ClippableElement
;
19578 * @inheritdoc OO.ui.mixin.DraggableElement
19579 * @deprecated Use {@link OO.ui.mixin.DraggableElement} instead.
19581 OO
.ui
.DraggableElement
= OO
.ui
.mixin
.DraggableElement
;
19584 * @inheritdoc OO.ui.mixin.DraggableGroupElement
19585 * @deprecated Use {@link OO.ui.mixin.DraggableGroupElement} instead.
19587 OO
.ui
.DraggableGroupElement
= OO
.ui
.mixin
.DraggableGroupElement
;
19590 * @inheritdoc OO.ui.mixin.FlaggedElement
19591 * @deprecated Use {@link OO.ui.mixin.FlaggedElement} instead.
19593 OO
.ui
.FlaggedElement
= OO
.ui
.mixin
.FlaggedElement
;
19596 * @inheritdoc OO.ui.mixin.GroupElement
19597 * @deprecated Use {@link OO.ui.mixin.GroupElement} instead.
19599 OO
.ui
.GroupElement
= OO
.ui
.mixin
.GroupElement
;
19602 * @inheritdoc OO.ui.mixin.GroupWidget
19603 * @deprecated Use {@link OO.ui.mixin.GroupWidget} instead.
19605 OO
.ui
.GroupWidget
= OO
.ui
.mixin
.GroupWidget
;
19608 * @inheritdoc OO.ui.mixin.IconElement
19609 * @deprecated Use {@link OO.ui.mixin.IconElement} instead.
19611 OO
.ui
.IconElement
= OO
.ui
.mixin
.IconElement
;
19614 * @inheritdoc OO.ui.mixin.IndicatorElement
19615 * @deprecated Use {@link OO.ui.mixin.IndicatorElement} instead.
19617 OO
.ui
.IndicatorElement
= OO
.ui
.mixin
.IndicatorElement
;
19620 * @inheritdoc OO.ui.mixin.ItemWidget
19621 * @deprecated Use {@link OO.ui.mixin.ItemWidget} instead.
19623 OO
.ui
.ItemWidget
= OO
.ui
.mixin
.ItemWidget
;
19626 * @inheritdoc OO.ui.mixin.LabelElement
19627 * @deprecated Use {@link OO.ui.mixin.LabelElement} instead.
19629 OO
.ui
.LabelElement
= OO
.ui
.mixin
.LabelElement
;
19632 * @inheritdoc OO.ui.mixin.LookupElement
19633 * @deprecated Use {@link OO.ui.mixin.LookupElement} instead.
19635 OO
.ui
.LookupElement
= OO
.ui
.mixin
.LookupElement
;
19638 * @inheritdoc OO.ui.mixin.PendingElement
19639 * @deprecated Use {@link OO.ui.mixin.PendingElement} instead.
19641 OO
.ui
.PendingElement
= OO
.ui
.mixin
.PendingElement
;
19644 * @inheritdoc OO.ui.mixin.PopupElement
19645 * @deprecated Use {@link OO.ui.mixin.PopupElement} instead.
19647 OO
.ui
.PopupElement
= OO
.ui
.mixin
.PopupElement
;
19650 * @inheritdoc OO.ui.mixin.TabIndexedElement
19651 * @deprecated Use {@link OO.ui.mixin.TabIndexedElement} instead.
19653 OO
.ui
.TabIndexedElement
= OO
.ui
.mixin
.TabIndexedElement
;
19656 * @inheritdoc OO.ui.mixin.TitledElement
19657 * @deprecated Use {@link OO.ui.mixin.TitledElement} instead.
19659 OO
.ui
.TitledElement
= OO
.ui
.mixin
.TitledElement
;