3 * https://www.mediawiki.org/wiki/OOUI
5 * Copyright 2011–2018 OOUI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
9 * Date: 2018-05-09T00:44:45Z
16 * Namespace for all classes, static methods and static properties.
48 * Constants for MouseEvent.which
52 OO
.ui
.MouseButtons
= {
65 * Generate a unique ID for element
69 OO
.ui
.generateElementId = function () {
71 return 'ooui-' + OO
.ui
.elementId
;
75 * Check if an element is focusable.
76 * Inspired by :focusable in jQueryUI v1.11.4 - 2015-04-14
78 * @param {jQuery} $element Element to test
79 * @return {boolean} Element is focusable
81 OO
.ui
.isFocusableElement = function ( $element
) {
83 element
= $element
[ 0 ];
85 // Anything disabled is not focusable
86 if ( element
.disabled
) {
90 // Check if the element is visible
92 // This is quicker than calling $element.is( ':visible' )
93 $.expr
.pseudos
.visible( element
) &&
94 // Check that all parents are visible
95 !$element
.parents().addBack().filter( function () {
96 return $.css( this, 'visibility' ) === 'hidden';
102 // Check if the element is ContentEditable, which is the string 'true'
103 if ( element
.contentEditable
=== 'true' ) {
107 // Anything with a non-negative numeric tabIndex is focusable.
108 // Use .prop to avoid browser bugs
109 if ( $element
.prop( 'tabIndex' ) >= 0 ) {
113 // Some element types are naturally focusable
114 // (indexOf is much faster than regex in Chrome and about the
115 // same in FF: https://jsperf.com/regex-vs-indexof-array2)
116 nodeName
= element
.nodeName
.toLowerCase();
117 if ( [ 'input', 'select', 'textarea', 'button', 'object' ].indexOf( nodeName
) !== -1 ) {
121 // Links and areas are focusable if they have an href
122 if ( ( nodeName
=== 'a' || nodeName
=== 'area' ) && $element
.attr( 'href' ) !== undefined ) {
130 * Find a focusable child
132 * @param {jQuery} $container Container to search in
133 * @param {boolean} [backwards] Search backwards
134 * @return {jQuery} Focusable child, or an empty jQuery object if none found
136 OO
.ui
.findFocusable = function ( $container
, backwards
) {
137 var $focusable
= $( [] ),
138 // $focusableCandidates is a superset of things that
139 // could get matched by isFocusableElement
140 $focusableCandidates
= $container
141 .find( 'input, select, textarea, button, object, a, area, [contenteditable], [tabindex]' );
144 $focusableCandidates
= Array
.prototype.reverse
.call( $focusableCandidates
);
147 $focusableCandidates
.each( function () {
148 var $this = $( this );
149 if ( OO
.ui
.isFocusableElement( $this ) ) {
158 * Get the user's language and any fallback languages.
160 * These language codes are used to localize user interface elements in the user's language.
162 * In environments that provide a localization system, this function should be overridden to
163 * return the user's language(s). The default implementation returns English (en) only.
165 * @return {string[]} Language codes, in descending order of priority
167 OO
.ui
.getUserLanguages = function () {
172 * Get a value in an object keyed by language code.
174 * @param {Object.<string,Mixed>} obj Object keyed by language code
175 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
176 * @param {string} [fallback] Fallback code, used if no matching language can be found
177 * @return {Mixed} Local value
179 OO
.ui
.getLocalValue = function ( obj
, lang
, fallback
) {
182 // Requested language
186 // Known user language
187 langs
= OO
.ui
.getUserLanguages();
188 for ( i
= 0, len
= langs
.length
; i
< len
; i
++ ) {
195 if ( obj
[ fallback
] ) {
196 return obj
[ fallback
];
198 // First existing language
199 for ( lang
in obj
) {
207 * Check if a node is contained within another node
209 * Similar to jQuery#contains except a list of containers can be supplied
210 * and a boolean argument allows you to include the container in the match list
212 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
213 * @param {HTMLElement} contained Node to find
214 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
215 * @return {boolean} The node is in the list of target nodes
217 OO
.ui
.contains = function ( containers
, contained
, matchContainers
) {
219 if ( !Array
.isArray( containers
) ) {
220 containers
= [ containers
];
222 for ( i
= containers
.length
- 1; i
>= 0; i
-- ) {
223 if ( ( matchContainers
&& contained
=== containers
[ i
] ) || $.contains( containers
[ i
], contained
) ) {
231 * Return a function, that, as long as it continues to be invoked, will not
232 * be triggered. The function will be called after it stops being called for
233 * N milliseconds. If `immediate` is passed, trigger the function on the
234 * leading edge, instead of the trailing.
236 * Ported from: http://underscorejs.org/underscore.js
238 * @param {Function} func Function to debounce
239 * @param {number} [wait=0] Wait period in milliseconds
240 * @param {boolean} [immediate] Trigger on leading edge
241 * @return {Function} Debounced function
243 OO
.ui
.debounce = function ( func
, wait
, immediate
) {
248 later = function () {
251 func
.apply( context
, args
);
254 if ( immediate
&& !timeout
) {
255 func
.apply( context
, args
);
257 if ( !timeout
|| wait
) {
258 clearTimeout( timeout
);
259 timeout
= setTimeout( later
, wait
);
265 * Puts a console warning with provided message.
267 * @param {string} message Message
269 OO
.ui
.warnDeprecation = function ( message
) {
270 if ( OO
.getProp( window
, 'console', 'warn' ) !== undefined ) {
271 // eslint-disable-next-line no-console
272 console
.warn( message
);
277 * Returns a function, that, when invoked, will only be triggered at most once
278 * during a given window of time. If called again during that window, it will
279 * wait until the window ends and then trigger itself again.
281 * As it's not knowable to the caller whether the function will actually run
282 * when the wrapper is called, return values from the function are entirely
285 * @param {Function} func Function to throttle
286 * @param {number} wait Throttle window length, in milliseconds
287 * @return {Function} Throttled function
289 OO
.ui
.throttle = function ( func
, wait
) {
290 var context
, args
, timeout
,
294 previous
= OO
.ui
.now();
295 func
.apply( context
, args
);
298 // Check how long it's been since the last time the function was
299 // called, and whether it's more or less than the requested throttle
300 // period. If it's less, run the function immediately. If it's more,
301 // set a timeout for the remaining time -- but don't replace an
302 // existing timeout, since that'd indefinitely prolong the wait.
303 var remaining
= wait
- ( OO
.ui
.now() - previous
);
306 if ( remaining
<= 0 ) {
307 // Note: unless wait was ridiculously large, this means we'll
308 // automatically run the first time the function was called in a
309 // given period. (If you provide a wait period larger than the
310 // current Unix timestamp, you *deserve* unexpected behavior.)
311 clearTimeout( timeout
);
313 } else if ( !timeout
) {
314 timeout
= setTimeout( run
, remaining
);
320 * A (possibly faster) way to get the current timestamp as an integer
322 * @return {number} Current timestamp, in milliseconds since the Unix epoch
324 OO
.ui
.now
= Date
.now
|| function () {
325 return new Date().getTime();
329 * Reconstitute a JavaScript object corresponding to a widget created by
330 * the PHP implementation.
332 * This is an alias for `OO.ui.Element.static.infuse()`.
334 * @param {string|HTMLElement|jQuery} idOrNode
335 * A DOM id (if a string) or node for the widget to infuse.
336 * @return {OO.ui.Element}
337 * The `OO.ui.Element` corresponding to this (infusable) document node.
339 OO
.ui
.infuse = function ( idOrNode
) {
340 return OO
.ui
.Element
.static.infuse( idOrNode
);
345 * Message store for the default implementation of OO.ui.msg
347 * Environments that provide a localization system should not use this, but should override
348 * OO.ui.msg altogether.
353 // Tool tip for a button that moves items in a list down one place
354 'ooui-outline-control-move-down': 'Move item down',
355 // Tool tip for a button that moves items in a list up one place
356 'ooui-outline-control-move-up': 'Move item up',
357 // Tool tip for a button that removes items from a list
358 'ooui-outline-control-remove': 'Remove item',
359 // Label for the toolbar group that contains a list of all other available tools
360 'ooui-toolbar-more': 'More',
361 // Label for the fake tool that expands the full list of tools in a toolbar group
362 'ooui-toolgroup-expand': 'More',
363 // Label for the fake tool that collapses the full list of tools in a toolbar group
364 'ooui-toolgroup-collapse': 'Fewer',
365 // Default label for the tooltip for the button that removes a tag item
366 'ooui-item-remove': 'Remove',
367 // Default label for the accept button of a confirmation dialog
368 'ooui-dialog-message-accept': 'OK',
369 // Default label for the reject button of a confirmation dialog
370 'ooui-dialog-message-reject': 'Cancel',
371 // Title for process dialog error description
372 'ooui-dialog-process-error': 'Something went wrong',
373 // Label for process dialog dismiss error button, visible when describing errors
374 'ooui-dialog-process-dismiss': 'Dismiss',
375 // Label for process dialog retry action button, visible when describing only recoverable errors
376 'ooui-dialog-process-retry': 'Try again',
377 // Label for process dialog retry action button, visible when describing only warnings
378 'ooui-dialog-process-continue': 'Continue',
379 // Label for the file selection widget's select file button
380 'ooui-selectfile-button-select': 'Select a file',
381 // Label for the file selection widget if file selection is not supported
382 'ooui-selectfile-not-supported': 'File selection is not supported',
383 // Label for the file selection widget when no file is currently selected
384 'ooui-selectfile-placeholder': 'No file is selected',
385 // Label for the file selection widget's drop target
386 'ooui-selectfile-dragdrop-placeholder': 'Drop file here'
390 * Get a localized message.
392 * After the message key, message parameters may optionally be passed. In the default implementation,
393 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
394 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
395 * they support unnamed, ordered message parameters.
397 * In environments that provide a localization system, this function should be overridden to
398 * return the message translated in the user's language. The default implementation always returns
399 * English messages. An example of doing this with [jQuery.i18n](https://github.com/wikimedia/jquery.i18n)
403 * var i, iLen, button,
404 * messagePath = 'oojs-ui/dist/i18n/',
405 * languages = [ $.i18n().locale, 'ur', 'en' ],
408 * for ( i = 0, iLen = languages.length; i < iLen; i++ ) {
409 * languageMap[ languages[ i ] ] = messagePath + languages[ i ].toLowerCase() + '.json';
412 * $.i18n().load( languageMap ).done( function() {
413 * // Replace the built-in `msg` only once we've loaded the internationalization.
414 * // OOUI uses `OO.ui.deferMsg` for all initially-loaded messages. So long as
415 * // you put off creating any widgets until this promise is complete, no English
416 * // will be displayed.
417 * OO.ui.msg = $.i18n;
419 * // A button displaying "OK" in the default locale
420 * button = new OO.ui.ButtonWidget( {
421 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
424 * $( 'body' ).append( button.$element );
426 * // A button displaying "OK" in Urdu
427 * $.i18n().locale = 'ur';
428 * button = new OO.ui.ButtonWidget( {
429 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
432 * $( 'body' ).append( button.$element );
435 * @param {string} key Message key
436 * @param {...Mixed} [params] Message parameters
437 * @return {string} Translated message with parameters substituted
439 OO
.ui
.msg = function ( key
) {
440 var message
= messages
[ key
],
441 params
= Array
.prototype.slice
.call( arguments
, 1 );
442 if ( typeof message
=== 'string' ) {
443 // Perform $1 substitution
444 message
= message
.replace( /\$(\d+)/g, function ( unused
, n
) {
445 var i
= parseInt( n
, 10 );
446 return params
[ i
- 1 ] !== undefined ? params
[ i
- 1 ] : '$' + n
;
449 // Return placeholder if message not found
450 message
= '[' + key
+ ']';
457 * Package a message and arguments for deferred resolution.
459 * Use this when you are statically specifying a message and the message may not yet be present.
461 * @param {string} key Message key
462 * @param {...Mixed} [params] Message parameters
463 * @return {Function} Function that returns the resolved message when executed
465 OO
.ui
.deferMsg = function () {
466 var args
= arguments
;
468 return OO
.ui
.msg
.apply( OO
.ui
, args
);
475 * If the message is a function it will be executed, otherwise it will pass through directly.
477 * @param {Function|string} msg Deferred message, or message text
478 * @return {string} Resolved message
480 OO
.ui
.resolveMsg = function ( msg
) {
481 if ( $.isFunction( msg
) ) {
488 * @param {string} url
491 OO
.ui
.isSafeUrl = function ( url
) {
492 // Keep this function in sync with php/Tag.php
493 var i
, protocolWhitelist
;
495 function stringStartsWith( haystack
, needle
) {
496 return haystack
.substr( 0, needle
.length
) === needle
;
499 protocolWhitelist
= [
500 'bitcoin', 'ftp', 'ftps', 'geo', 'git', 'gopher', 'http', 'https', 'irc', 'ircs',
501 'magnet', 'mailto', 'mms', 'news', 'nntp', 'redis', 'sftp', 'sip', 'sips', 'sms', 'ssh',
502 'svn', 'tel', 'telnet', 'urn', 'worldwind', 'xmpp'
509 for ( i
= 0; i
< protocolWhitelist
.length
; i
++ ) {
510 if ( stringStartsWith( url
, protocolWhitelist
[ i
] + ':' ) ) {
515 // This matches '//' too
516 if ( stringStartsWith( url
, '/' ) || stringStartsWith( url
, './' ) ) {
519 if ( stringStartsWith( url
, '?' ) || stringStartsWith( url
, '#' ) ) {
527 * Check if the user has a 'mobile' device.
529 * For our purposes this means the user is primarily using an
530 * on-screen keyboard, touch input instead of a mouse and may
531 * have a physically small display.
533 * It is left up to implementors to decide how to compute this
534 * so the default implementation always returns false.
536 * @return {boolean} User is on a mobile device
538 OO
.ui
.isMobile = function () {
543 * Get the additional spacing that should be taken into account when displaying elements that are
544 * clipped to the viewport, e.g. dropdown menus and popups. This is meant to be overridden to avoid
545 * such menus overlapping any fixed headers/toolbars/navigation used by the site.
547 * @return {Object} Object with the properties 'top', 'right', 'bottom', 'left', each representing
548 * the extra spacing from that edge of viewport (in pixels)
550 OO
.ui
.getViewportSpacing = function () {
560 * Get the default overlay, which is used by various widgets when they are passed `$overlay: true`.
561 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
563 * @return {jQuery} Default overlay node
565 OO
.ui
.getDefaultOverlay = function () {
566 if ( !OO
.ui
.$defaultOverlay
) {
567 OO
.ui
.$defaultOverlay
= $( '<div>' ).addClass( 'oo-ui-defaultOverlay' );
568 $( 'body' ).append( OO
.ui
.$defaultOverlay
);
570 return OO
.ui
.$defaultOverlay
;
578 * Namespace for OOUI mixins.
580 * Mixins are named according to the type of object they are intended to
581 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
582 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
583 * is intended to be mixed in to an instance of OO.ui.Widget.
591 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
592 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
593 * connected to them and can't be interacted with.
599 * @param {Object} [config] Configuration options
600 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
601 * to the top level (e.g., the outermost div) of the element. See the [OOUI documentation on MediaWiki][2]
603 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches#cssExample
604 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
605 * @cfg {string} [text] Text to insert
606 * @cfg {Array} [content] An array of content elements to append (after #text).
607 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
608 * Instances of OO.ui.Element will have their $element appended.
609 * @cfg {jQuery} [$content] Content elements to append (after #text).
610 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
611 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
612 * Data can also be specified with the #setData method.
614 OO
.ui
.Element
= function OoUiElement( config
) {
615 if ( OO
.ui
.isDemo
) {
616 this.initialConfig
= config
;
618 // Configuration initialization
619 config
= config
|| {};
623 this.elementId
= null;
625 this.data
= config
.data
;
626 this.$element
= config
.$element
||
627 $( document
.createElement( this.getTagName() ) );
628 this.elementGroup
= null;
631 if ( Array
.isArray( config
.classes
) ) {
632 this.$element
.addClass( config
.classes
.join( ' ' ) );
635 this.setElementId( config
.id
);
638 this.$element
.text( config
.text
);
640 if ( config
.content
) {
641 // The `content` property treats plain strings as text; use an
642 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
643 // appropriate $element appended.
644 this.$element
.append( config
.content
.map( function ( v
) {
645 if ( typeof v
=== 'string' ) {
646 // Escape string so it is properly represented in HTML.
647 return document
.createTextNode( v
);
648 } else if ( v
instanceof OO
.ui
.HtmlSnippet
) {
651 } else if ( v
instanceof OO
.ui
.Element
) {
657 if ( config
.$content
) {
658 // The `$content` property treats plain strings as HTML.
659 this.$element
.append( config
.$content
);
665 OO
.initClass( OO
.ui
.Element
);
667 /* Static Properties */
670 * The name of the HTML tag used by the element.
672 * The static value may be ignored if the #getTagName method is overridden.
678 OO
.ui
.Element
.static.tagName
= 'div';
683 * Reconstitute a JavaScript object corresponding to a widget created
684 * by the PHP implementation.
686 * @param {string|HTMLElement|jQuery} idOrNode
687 * A DOM id (if a string) or node for the widget to infuse.
688 * @return {OO.ui.Element}
689 * The `OO.ui.Element` corresponding to this (infusable) document node.
690 * For `Tag` objects emitted on the HTML side (used occasionally for content)
691 * the value returned is a newly-created Element wrapping around the existing
694 OO
.ui
.Element
.static.infuse = function ( idOrNode
) {
695 var obj
= OO
.ui
.Element
.static.unsafeInfuse( idOrNode
, false );
696 // Verify that the type matches up.
697 // FIXME: uncomment after T89721 is fixed, see T90929.
699 if ( !( obj instanceof this['class'] ) ) {
700 throw new Error( 'Infusion type mismatch!' );
707 * Implementation helper for `infuse`; skips the type check and has an
708 * extra property so that only the top-level invocation touches the DOM.
711 * @param {string|HTMLElement|jQuery} idOrNode
712 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
713 * when the top-level widget of this infusion is inserted into DOM,
714 * replacing the original node; or false for top-level invocation.
715 * @return {OO.ui.Element}
717 OO
.ui
.Element
.static.unsafeInfuse = function ( idOrNode
, domPromise
) {
718 // look for a cached result of a previous infusion.
719 var id
, $elem
, error
, data
, cls
, parts
, parent
, obj
, top
, state
, infusedChildren
;
720 if ( typeof idOrNode
=== 'string' ) {
722 $elem
= $( document
.getElementById( id
) );
724 $elem
= $( idOrNode
);
725 id
= $elem
.attr( 'id' );
727 if ( !$elem
.length
) {
728 if ( typeof idOrNode
=== 'string' ) {
729 error
= 'Widget not found: ' + idOrNode
;
730 } else if ( idOrNode
&& idOrNode
.selector
) {
731 error
= 'Widget not found: ' + idOrNode
.selector
;
733 error
= 'Widget not found';
735 throw new Error( error
);
737 if ( $elem
[ 0 ].oouiInfused
) {
738 $elem
= $elem
[ 0 ].oouiInfused
;
740 data
= $elem
.data( 'ooui-infused' );
743 if ( data
=== true ) {
744 throw new Error( 'Circular dependency! ' + id
);
747 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
748 state
= data
.constructor.static.gatherPreInfuseState( $elem
, data
);
749 // restore dynamic state after the new element is re-inserted into DOM under infused parent
750 domPromise
.done( data
.restorePreInfuseState
.bind( data
, state
) );
751 infusedChildren
= $elem
.data( 'ooui-infused-children' );
752 if ( infusedChildren
&& infusedChildren
.length
) {
753 infusedChildren
.forEach( function ( data
) {
754 var state
= data
.constructor.static.gatherPreInfuseState( $elem
, data
);
755 domPromise
.done( data
.restorePreInfuseState
.bind( data
, state
) );
761 data
= $elem
.attr( 'data-ooui' );
763 throw new Error( 'No infusion data found: ' + id
);
766 data
= JSON
.parse( data
);
770 if ( !( data
&& data
._
) ) {
771 throw new Error( 'No valid infusion data found: ' + id
);
773 if ( data
._
=== 'Tag' ) {
774 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
775 return new OO
.ui
.Element( { $element
: $elem
} );
777 parts
= data
._
.split( '.' );
778 cls
= OO
.getProp
.apply( OO
, [ window
].concat( parts
) );
779 if ( cls
=== undefined ) {
780 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
783 // Verify that we're creating an OO.ui.Element instance
786 while ( parent
!== undefined ) {
787 if ( parent
=== OO
.ui
.Element
) {
792 parent
= parent
.parent
;
795 if ( parent
!== OO
.ui
.Element
) {
796 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
799 if ( domPromise
=== false ) {
801 domPromise
= top
.promise();
803 $elem
.data( 'ooui-infused', true ); // prevent loops
804 data
.id
= id
; // implicit
805 infusedChildren
= [];
806 data
= OO
.copy( data
, null, function deserialize( value
) {
808 if ( OO
.isPlainObject( value
) ) {
810 infused
= OO
.ui
.Element
.static.unsafeInfuse( value
.tag
, domPromise
);
811 infusedChildren
.push( infused
);
812 // Flatten the structure
813 infusedChildren
.push
.apply( infusedChildren
, infused
.$element
.data( 'ooui-infused-children' ) || [] );
814 infused
.$element
.removeData( 'ooui-infused-children' );
817 if ( value
.html
!== undefined ) {
818 return new OO
.ui
.HtmlSnippet( value
.html
);
822 // allow widgets to reuse parts of the DOM
823 data
= cls
.static.reusePreInfuseDOM( $elem
[ 0 ], data
);
824 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
825 state
= cls
.static.gatherPreInfuseState( $elem
[ 0 ], data
);
827 // eslint-disable-next-line new-cap
828 obj
= new cls( data
);
829 // If anyone is holding a reference to the old DOM element,
830 // let's allow them to OO.ui.infuse() it and do what they expect, see T105828.
831 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
832 $elem
[ 0 ].oouiInfused
= obj
.$element
;
833 // now replace old DOM with this new DOM.
835 // An efficient constructor might be able to reuse the entire DOM tree of the original element,
836 // so only mutate the DOM if we need to.
837 if ( $elem
[ 0 ] !== obj
.$element
[ 0 ] ) {
838 $elem
.replaceWith( obj
.$element
);
842 obj
.$element
.data( 'ooui-infused', obj
);
843 obj
.$element
.data( 'ooui-infused-children', infusedChildren
);
844 // set the 'data-ooui' attribute so we can identify infused widgets
845 obj
.$element
.attr( 'data-ooui', '' );
846 // restore dynamic state after the new element is inserted into DOM
847 domPromise
.done( obj
.restorePreInfuseState
.bind( obj
, state
) );
852 * Pick out parts of `node`'s DOM to be reused when infusing a widget.
854 * This method **must not** make any changes to the DOM, only find interesting pieces and add them
855 * to `config` (which should then be returned). Actual DOM juggling should then be done by the
856 * constructor, which will be given the enhanced config.
859 * @param {HTMLElement} node
860 * @param {Object} config
863 OO
.ui
.Element
.static.reusePreInfuseDOM = function ( node
, config
) {
868 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of an HTML DOM node
869 * (and its children) that represent an Element of the same class and the given configuration,
870 * generated by the PHP implementation.
872 * This method is called just before `node` is detached from the DOM. The return value of this
873 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
874 * is inserted into DOM to replace `node`.
877 * @param {HTMLElement} node
878 * @param {Object} config
881 OO
.ui
.Element
.static.gatherPreInfuseState = function () {
886 * Get a jQuery function within a specific document.
889 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
890 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
892 * @return {Function} Bound jQuery function
894 OO
.ui
.Element
.static.getJQuery = function ( context
, $iframe
) {
895 function wrapper( selector
) {
896 return $( selector
, wrapper
.context
);
899 wrapper
.context
= this.getDocument( context
);
902 wrapper
.$iframe
= $iframe
;
909 * Get the document of an element.
912 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
913 * @return {HTMLDocument|null} Document object
915 OO
.ui
.Element
.static.getDocument = function ( obj
) {
916 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
917 return ( obj
[ 0 ] && obj
[ 0 ].ownerDocument
) ||
918 // Empty jQuery selections might have a context
925 ( obj
.nodeType
=== Node
.DOCUMENT_NODE
&& obj
) ||
930 * Get the window of an element or document.
933 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
934 * @return {Window} Window object
936 OO
.ui
.Element
.static.getWindow = function ( obj
) {
937 var doc
= this.getDocument( obj
);
938 return doc
.defaultView
;
942 * Get the direction of an element or document.
945 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
946 * @return {string} Text direction, either 'ltr' or 'rtl'
948 OO
.ui
.Element
.static.getDir = function ( obj
) {
951 if ( obj
instanceof jQuery
) {
954 isDoc
= obj
.nodeType
=== Node
.DOCUMENT_NODE
;
955 isWin
= obj
.document
!== undefined;
956 if ( isDoc
|| isWin
) {
962 return $( obj
).css( 'direction' );
966 * Get the offset between two frames.
968 * TODO: Make this function not use recursion.
971 * @param {Window} from Window of the child frame
972 * @param {Window} [to=window] Window of the parent frame
973 * @param {Object} [offset] Offset to start with, used internally
974 * @return {Object} Offset object, containing left and top properties
976 OO
.ui
.Element
.static.getFrameOffset = function ( from, to
, offset
) {
977 var i
, len
, frames
, frame
, rect
;
983 offset
= { top
: 0, left
: 0 };
985 if ( from.parent
=== from ) {
989 // Get iframe element
990 frames
= from.parent
.document
.getElementsByTagName( 'iframe' );
991 for ( i
= 0, len
= frames
.length
; i
< len
; i
++ ) {
992 if ( frames
[ i
].contentWindow
=== from ) {
998 // Recursively accumulate offset values
1000 rect
= frame
.getBoundingClientRect();
1001 offset
.left
+= rect
.left
;
1002 offset
.top
+= rect
.top
;
1003 if ( from !== to
) {
1004 this.getFrameOffset( from.parent
, offset
);
1011 * Get the offset between two elements.
1013 * The two elements may be in a different frame, but in that case the frame $element is in must
1014 * be contained in the frame $anchor is in.
1017 * @param {jQuery} $element Element whose position to get
1018 * @param {jQuery} $anchor Element to get $element's position relative to
1019 * @return {Object} Translated position coordinates, containing top and left properties
1021 OO
.ui
.Element
.static.getRelativePosition = function ( $element
, $anchor
) {
1022 var iframe
, iframePos
,
1023 pos
= $element
.offset(),
1024 anchorPos
= $anchor
.offset(),
1025 elementDocument
= this.getDocument( $element
),
1026 anchorDocument
= this.getDocument( $anchor
);
1028 // If $element isn't in the same document as $anchor, traverse up
1029 while ( elementDocument
!== anchorDocument
) {
1030 iframe
= elementDocument
.defaultView
.frameElement
;
1032 throw new Error( '$element frame is not contained in $anchor frame' );
1034 iframePos
= $( iframe
).offset();
1035 pos
.left
+= iframePos
.left
;
1036 pos
.top
+= iframePos
.top
;
1037 elementDocument
= iframe
.ownerDocument
;
1039 pos
.left
-= anchorPos
.left
;
1040 pos
.top
-= anchorPos
.top
;
1045 * Get element border sizes.
1048 * @param {HTMLElement} el Element to measure
1049 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1051 OO
.ui
.Element
.static.getBorders = function ( el
) {
1052 var doc
= el
.ownerDocument
,
1053 win
= doc
.defaultView
,
1054 style
= win
.getComputedStyle( el
, null ),
1056 top
= parseFloat( style
? style
.borderTopWidth
: $el
.css( 'borderTopWidth' ) ) || 0,
1057 left
= parseFloat( style
? style
.borderLeftWidth
: $el
.css( 'borderLeftWidth' ) ) || 0,
1058 bottom
= parseFloat( style
? style
.borderBottomWidth
: $el
.css( 'borderBottomWidth' ) ) || 0,
1059 right
= parseFloat( style
? style
.borderRightWidth
: $el
.css( 'borderRightWidth' ) ) || 0;
1070 * Get dimensions of an element or window.
1073 * @param {HTMLElement|Window} el Element to measure
1074 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1076 OO
.ui
.Element
.static.getDimensions = function ( el
) {
1078 doc
= el
.ownerDocument
|| el
.document
,
1079 win
= doc
.defaultView
;
1081 if ( win
=== el
|| el
=== doc
.documentElement
) {
1084 borders
: { top
: 0, left
: 0, bottom
: 0, right
: 0 },
1086 top
: $win
.scrollTop(),
1087 left
: $win
.scrollLeft()
1089 scrollbar
: { right
: 0, bottom
: 0 },
1093 bottom
: $win
.innerHeight(),
1094 right
: $win
.innerWidth()
1100 borders
: this.getBorders( el
),
1102 top
: $el
.scrollTop(),
1103 left
: $el
.scrollLeft()
1106 right
: $el
.innerWidth() - el
.clientWidth
,
1107 bottom
: $el
.innerHeight() - el
.clientHeight
1109 rect
: el
.getBoundingClientRect()
1115 * Get the number of pixels that an element's content is scrolled to the left.
1117 * Adapted from <https://github.com/othree/jquery.rtl-scroll-type>.
1118 * Original code copyright 2012 Wei-Ko Kao, licensed under the MIT License.
1120 * This function smooths out browser inconsistencies (nicely described in the README at
1121 * <https://github.com/othree/jquery.rtl-scroll-type>) and produces a result consistent
1122 * with Firefox's 'scrollLeft', which seems the sanest.
1126 * @param {HTMLElement|Window} el Element to measure
1127 * @return {number} Scroll position from the left.
1128 * If the element's direction is LTR, this is a positive number between `0` (initial scroll position)
1129 * and `el.scrollWidth - el.clientWidth` (furthest possible scroll position).
1130 * If the element's direction is RTL, this is a negative number between `0` (initial scroll position)
1131 * and `-el.scrollWidth + el.clientWidth` (furthest possible scroll position).
1133 OO
.ui
.Element
.static.getScrollLeft
= ( function () {
1134 var rtlScrollType
= null;
1137 var $definer
= $( '<div dir="rtl" style="font-size: 14px; width: 1px; height: 1px; position: absolute; top: -1000px; overflow: scroll">A</div>' ),
1138 definer
= $definer
[ 0 ];
1140 $definer
.appendTo( 'body' );
1141 if ( definer
.scrollLeft
> 0 ) {
1143 rtlScrollType
= 'default';
1145 definer
.scrollLeft
= 1;
1146 if ( definer
.scrollLeft
=== 0 ) {
1147 // Firefox, old Opera
1148 rtlScrollType
= 'negative';
1150 // Internet Explorer, Edge
1151 rtlScrollType
= 'reverse';
1157 return function getScrollLeft( el
) {
1158 var isRoot
= el
.window
=== el
||
1159 el
=== el
.ownerDocument
.body
||
1160 el
=== el
.ownerDocument
.documentElement
,
1161 scrollLeft
= isRoot
? $( window
).scrollLeft() : el
.scrollLeft
,
1162 // All browsers use the correct scroll type ('negative') on the root, so don't
1163 // do any fixups when looking at the root element
1164 direction
= isRoot
? 'ltr' : $( el
).css( 'direction' );
1166 if ( direction
=== 'rtl' ) {
1167 if ( rtlScrollType
=== null ) {
1170 if ( rtlScrollType
=== 'reverse' ) {
1171 scrollLeft
= -scrollLeft
;
1172 } else if ( rtlScrollType
=== 'default' ) {
1173 scrollLeft
= scrollLeft
- el
.scrollWidth
+ el
.clientWidth
;
1182 * Get the root scrollable element of given element's document.
1184 * On Blink-based browsers (Chrome etc.), `document.documentElement` can't be used to get or set
1185 * the scrollTop property; instead we have to use `document.body`. Changing and testing the value
1186 * lets us use 'body' or 'documentElement' based on what is working.
1188 * https://code.google.com/p/chromium/issues/detail?id=303131
1191 * @param {HTMLElement} el Element to find root scrollable parent for
1192 * @return {HTMLElement} Scrollable parent, `document.body` or `document.documentElement`
1193 * depending on browser
1195 OO
.ui
.Element
.static.getRootScrollableElement = function ( el
) {
1196 var scrollTop
, body
;
1198 if ( OO
.ui
.scrollableElement
=== undefined ) {
1199 body
= el
.ownerDocument
.body
;
1200 scrollTop
= body
.scrollTop
;
1203 // In some browsers (observed in Chrome 56 on Linux Mint 18.1),
1204 // body.scrollTop doesn't become exactly 1, but a fractional value like 0.76
1205 if ( Math
.round( body
.scrollTop
) === 1 ) {
1206 body
.scrollTop
= scrollTop
;
1207 OO
.ui
.scrollableElement
= 'body';
1209 OO
.ui
.scrollableElement
= 'documentElement';
1213 return el
.ownerDocument
[ OO
.ui
.scrollableElement
];
1217 * Get closest scrollable container.
1219 * Traverses up until either a scrollable element or the root is reached, in which case the root
1220 * scrollable element will be returned (see #getRootScrollableElement).
1223 * @param {HTMLElement} el Element to find scrollable container for
1224 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1225 * @return {HTMLElement} Closest scrollable container
1227 OO
.ui
.Element
.static.getClosestScrollableContainer = function ( el
, dimension
) {
1229 // Browsers do not correctly return the computed value of 'overflow' when 'overflow-x' and
1230 // 'overflow-y' have different values, so we need to check the separate properties.
1231 props
= [ 'overflow-x', 'overflow-y' ],
1232 $parent
= $( el
).parent();
1234 if ( dimension
=== 'x' || dimension
=== 'y' ) {
1235 props
= [ 'overflow-' + dimension
];
1238 // Special case for the document root (which doesn't really have any scrollable container, since
1239 // it is the ultimate scrollable container, but this is probably saner than null or exception)
1240 if ( $( el
).is( 'html, body' ) ) {
1241 return this.getRootScrollableElement( el
);
1244 while ( $parent
.length
) {
1245 if ( $parent
[ 0 ] === this.getRootScrollableElement( el
) ) {
1246 return $parent
[ 0 ];
1250 val
= $parent
.css( props
[ i
] );
1251 // We assume that elements with 'overflow' (in any direction) set to 'hidden' will never be
1252 // scrolled in that direction, but they can actually be scrolled programatically. The user can
1253 // unintentionally perform a scroll in such case even if the application doesn't scroll
1254 // programatically, e.g. when jumping to an anchor, or when using built-in find functionality.
1255 // This could cause funny issues...
1256 if ( val
=== 'auto' || val
=== 'scroll' ) {
1257 return $parent
[ 0 ];
1260 $parent
= $parent
.parent();
1262 // The element is unattached... return something mostly sane
1263 return this.getRootScrollableElement( el
);
1267 * Scroll element into view.
1270 * @param {HTMLElement} el Element to scroll into view
1271 * @param {Object} [config] Configuration options
1272 * @param {string} [config.duration='fast'] jQuery animation duration value
1273 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1274 * to scroll in both directions
1275 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1277 OO
.ui
.Element
.static.scrollIntoView = function ( el
, config
) {
1278 var position
, animations
, container
, $container
, elementDimensions
, containerDimensions
, $window
,
1279 deferred
= $.Deferred();
1281 // Configuration initialization
1282 config
= config
|| {};
1285 container
= this.getClosestScrollableContainer( el
, config
.direction
);
1286 $container
= $( container
);
1287 elementDimensions
= this.getDimensions( el
);
1288 containerDimensions
= this.getDimensions( container
);
1289 $window
= $( this.getWindow( el
) );
1291 // Compute the element's position relative to the container
1292 if ( $container
.is( 'html, body' ) ) {
1293 // If the scrollable container is the root, this is easy
1295 top
: elementDimensions
.rect
.top
,
1296 bottom
: $window
.innerHeight() - elementDimensions
.rect
.bottom
,
1297 left
: elementDimensions
.rect
.left
,
1298 right
: $window
.innerWidth() - elementDimensions
.rect
.right
1301 // Otherwise, we have to subtract el's coordinates from container's coordinates
1303 top
: elementDimensions
.rect
.top
- ( containerDimensions
.rect
.top
+ containerDimensions
.borders
.top
),
1304 bottom
: containerDimensions
.rect
.bottom
- containerDimensions
.borders
.bottom
- containerDimensions
.scrollbar
.bottom
- elementDimensions
.rect
.bottom
,
1305 left
: elementDimensions
.rect
.left
- ( containerDimensions
.rect
.left
+ containerDimensions
.borders
.left
),
1306 right
: containerDimensions
.rect
.right
- containerDimensions
.borders
.right
- containerDimensions
.scrollbar
.right
- elementDimensions
.rect
.right
1310 if ( !config
.direction
|| config
.direction
=== 'y' ) {
1311 if ( position
.top
< 0 ) {
1312 animations
.scrollTop
= containerDimensions
.scroll
.top
+ position
.top
;
1313 } else if ( position
.top
> 0 && position
.bottom
< 0 ) {
1314 animations
.scrollTop
= containerDimensions
.scroll
.top
+ Math
.min( position
.top
, -position
.bottom
);
1317 if ( !config
.direction
|| config
.direction
=== 'x' ) {
1318 if ( position
.left
< 0 ) {
1319 animations
.scrollLeft
= containerDimensions
.scroll
.left
+ position
.left
;
1320 } else if ( position
.left
> 0 && position
.right
< 0 ) {
1321 animations
.scrollLeft
= containerDimensions
.scroll
.left
+ Math
.min( position
.left
, -position
.right
);
1324 if ( !$.isEmptyObject( animations
) ) {
1325 $container
.stop( true ).animate( animations
, config
.duration
=== undefined ? 'fast' : config
.duration
);
1326 $container
.queue( function ( next
) {
1333 return deferred
.promise();
1337 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1338 * and reserve space for them, because it probably doesn't.
1340 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1341 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1342 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1343 * and then reattach (or show) them back.
1346 * @param {HTMLElement} el Element to reconsider the scrollbars on
1348 OO
.ui
.Element
.static.reconsiderScrollbars = function ( el
) {
1349 var i
, len
, scrollLeft
, scrollTop
, nodes
= [];
1350 // Save scroll position
1351 scrollLeft
= el
.scrollLeft
;
1352 scrollTop
= el
.scrollTop
;
1353 // Detach all children
1354 while ( el
.firstChild
) {
1355 nodes
.push( el
.firstChild
);
1356 el
.removeChild( el
.firstChild
);
1359 void el
.offsetHeight
;
1360 // Reattach all children
1361 for ( i
= 0, len
= nodes
.length
; i
< len
; i
++ ) {
1362 el
.appendChild( nodes
[ i
] );
1364 // Restore scroll position (no-op if scrollbars disappeared)
1365 el
.scrollLeft
= scrollLeft
;
1366 el
.scrollTop
= scrollTop
;
1372 * Toggle visibility of an element.
1374 * @param {boolean} [show] Make element visible, omit to toggle visibility
1378 OO
.ui
.Element
.prototype.toggle = function ( show
) {
1379 show
= show
=== undefined ? !this.visible
: !!show
;
1381 if ( show
!== this.isVisible() ) {
1382 this.visible
= show
;
1383 this.$element
.toggleClass( 'oo-ui-element-hidden', !this.visible
);
1384 this.emit( 'toggle', show
);
1391 * Check if element is visible.
1393 * @return {boolean} element is visible
1395 OO
.ui
.Element
.prototype.isVisible = function () {
1396 return this.visible
;
1402 * @return {Mixed} Element data
1404 OO
.ui
.Element
.prototype.getData = function () {
1411 * @param {Mixed} data Element data
1414 OO
.ui
.Element
.prototype.setData = function ( data
) {
1420 * Set the element has an 'id' attribute.
1422 * @param {string} id
1425 OO
.ui
.Element
.prototype.setElementId = function ( id
) {
1426 this.elementId
= id
;
1427 this.$element
.attr( 'id', id
);
1432 * Ensure that the element has an 'id' attribute, setting it to an unique value if it's missing,
1433 * and return its value.
1437 OO
.ui
.Element
.prototype.getElementId = function () {
1438 if ( this.elementId
=== null ) {
1439 this.setElementId( OO
.ui
.generateElementId() );
1441 return this.elementId
;
1445 * Check if element supports one or more methods.
1447 * @param {string|string[]} methods Method or list of methods to check
1448 * @return {boolean} All methods are supported
1450 OO
.ui
.Element
.prototype.supports = function ( methods
) {
1454 methods
= Array
.isArray( methods
) ? methods
: [ methods
];
1455 for ( i
= 0, len
= methods
.length
; i
< len
; i
++ ) {
1456 if ( $.isFunction( this[ methods
[ i
] ] ) ) {
1461 return methods
.length
=== support
;
1465 * Update the theme-provided classes.
1467 * @localdoc This is called in element mixins and widget classes any time state changes.
1468 * Updating is debounced, minimizing overhead of changing multiple attributes and
1469 * guaranteeing that theme updates do not occur within an element's constructor
1471 OO
.ui
.Element
.prototype.updateThemeClasses = function () {
1472 OO
.ui
.theme
.queueUpdateElementClasses( this );
1476 * Get the HTML tag name.
1478 * Override this method to base the result on instance information.
1480 * @return {string} HTML tag name
1482 OO
.ui
.Element
.prototype.getTagName = function () {
1483 return this.constructor.static.tagName
;
1487 * Check if the element is attached to the DOM
1489 * @return {boolean} The element is attached to the DOM
1491 OO
.ui
.Element
.prototype.isElementAttached = function () {
1492 return $.contains( this.getElementDocument(), this.$element
[ 0 ] );
1496 * Get the DOM document.
1498 * @return {HTMLDocument} Document object
1500 OO
.ui
.Element
.prototype.getElementDocument = function () {
1501 // Don't cache this in other ways either because subclasses could can change this.$element
1502 return OO
.ui
.Element
.static.getDocument( this.$element
);
1506 * Get the DOM window.
1508 * @return {Window} Window object
1510 OO
.ui
.Element
.prototype.getElementWindow = function () {
1511 return OO
.ui
.Element
.static.getWindow( this.$element
);
1515 * Get closest scrollable container.
1517 * @return {HTMLElement} Closest scrollable container
1519 OO
.ui
.Element
.prototype.getClosestScrollableElementContainer = function () {
1520 return OO
.ui
.Element
.static.getClosestScrollableContainer( this.$element
[ 0 ] );
1524 * Get group element is in.
1526 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1528 OO
.ui
.Element
.prototype.getElementGroup = function () {
1529 return this.elementGroup
;
1533 * Set group element is in.
1535 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1538 OO
.ui
.Element
.prototype.setElementGroup = function ( group
) {
1539 this.elementGroup
= group
;
1544 * Scroll element into view.
1546 * @param {Object} [config] Configuration options
1547 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1549 OO
.ui
.Element
.prototype.scrollElementIntoView = function ( config
) {
1551 !this.isElementAttached() ||
1552 !this.isVisible() ||
1553 ( this.getElementGroup() && !this.getElementGroup().isVisible() )
1555 return $.Deferred().resolve();
1557 return OO
.ui
.Element
.static.scrollIntoView( this.$element
[ 0 ], config
);
1561 * Restore the pre-infusion dynamic state for this widget.
1563 * This method is called after #$element has been inserted into DOM. The parameter is the return
1564 * value of #gatherPreInfuseState.
1567 * @param {Object} state
1569 OO
.ui
.Element
.prototype.restorePreInfuseState = function () {
1573 * Wraps an HTML snippet for use with configuration values which default
1574 * to strings. This bypasses the default html-escaping done to string
1580 * @param {string} [content] HTML content
1582 OO
.ui
.HtmlSnippet
= function OoUiHtmlSnippet( content
) {
1584 this.content
= content
;
1589 OO
.initClass( OO
.ui
.HtmlSnippet
);
1596 * @return {string} Unchanged HTML snippet.
1598 OO
.ui
.HtmlSnippet
.prototype.toString = function () {
1599 return this.content
;
1603 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1604 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1605 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1606 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1607 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1611 * @extends OO.ui.Element
1612 * @mixins OO.EventEmitter
1615 * @param {Object} [config] Configuration options
1617 OO
.ui
.Layout
= function OoUiLayout( config
) {
1618 // Configuration initialization
1619 config
= config
|| {};
1621 // Parent constructor
1622 OO
.ui
.Layout
.parent
.call( this, config
);
1624 // Mixin constructors
1625 OO
.EventEmitter
.call( this );
1628 this.$element
.addClass( 'oo-ui-layout' );
1633 OO
.inheritClass( OO
.ui
.Layout
, OO
.ui
.Element
);
1634 OO
.mixinClass( OO
.ui
.Layout
, OO
.EventEmitter
);
1637 * Widgets are compositions of one or more OOUI elements that users can both view
1638 * and interact with. All widgets can be configured and modified via a standard API,
1639 * and their state can change dynamically according to a model.
1643 * @extends OO.ui.Element
1644 * @mixins OO.EventEmitter
1647 * @param {Object} [config] Configuration options
1648 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1649 * appearance reflects this state.
1651 OO
.ui
.Widget
= function OoUiWidget( config
) {
1652 // Initialize config
1653 config
= $.extend( { disabled
: false }, config
);
1655 // Parent constructor
1656 OO
.ui
.Widget
.parent
.call( this, config
);
1658 // Mixin constructors
1659 OO
.EventEmitter
.call( this );
1662 this.disabled
= null;
1663 this.wasDisabled
= null;
1666 this.$element
.addClass( 'oo-ui-widget' );
1667 this.setDisabled( !!config
.disabled
);
1672 OO
.inheritClass( OO
.ui
.Widget
, OO
.ui
.Element
);
1673 OO
.mixinClass( OO
.ui
.Widget
, OO
.EventEmitter
);
1680 * A 'disable' event is emitted when the disabled state of the widget changes
1681 * (i.e. on disable **and** enable).
1683 * @param {boolean} disabled Widget is disabled
1689 * A 'toggle' event is emitted when the visibility of the widget changes.
1691 * @param {boolean} visible Widget is visible
1697 * Check if the widget is disabled.
1699 * @return {boolean} Widget is disabled
1701 OO
.ui
.Widget
.prototype.isDisabled = function () {
1702 return this.disabled
;
1706 * Set the 'disabled' state of the widget.
1708 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1710 * @param {boolean} disabled Disable widget
1713 OO
.ui
.Widget
.prototype.setDisabled = function ( disabled
) {
1716 this.disabled
= !!disabled
;
1717 isDisabled
= this.isDisabled();
1718 if ( isDisabled
!== this.wasDisabled
) {
1719 this.$element
.toggleClass( 'oo-ui-widget-disabled', isDisabled
);
1720 this.$element
.toggleClass( 'oo-ui-widget-enabled', !isDisabled
);
1721 this.$element
.attr( 'aria-disabled', isDisabled
.toString() );
1722 this.emit( 'disable', isDisabled
);
1723 this.updateThemeClasses();
1725 this.wasDisabled
= isDisabled
;
1731 * Update the disabled state, in case of changes in parent widget.
1735 OO
.ui
.Widget
.prototype.updateDisabled = function () {
1736 this.setDisabled( this.disabled
);
1741 * Get an ID of a labelable node which is part of this widget, if any, to be used for `<label for>`
1744 * If this function returns null, the widget should have a meaningful #simulateLabelClick method
1747 * @return {string|null} The ID of the labelable element
1749 OO
.ui
.Widget
.prototype.getInputId = function () {
1754 * Simulate the behavior of clicking on a label (a HTML `<label>` element) bound to this input.
1755 * HTML only allows `<label>` to act on specific "labelable" elements; complex widgets might need to
1756 * override this method to provide intuitive, accessible behavior.
1758 * By default, this does nothing. OO.ui.mixin.TabIndexedElement overrides it for focusable widgets.
1759 * Individual widgets may override it too.
1761 * This method is called by OO.ui.LabelWidget and OO.ui.FieldLayout. It should not be called
1764 OO
.ui
.Widget
.prototype.simulateLabelClick = function () {
1775 OO
.ui
.Theme
= function OoUiTheme() {
1776 this.elementClassesQueue
= [];
1777 this.debouncedUpdateQueuedElementClasses
= OO
.ui
.debounce( this.updateQueuedElementClasses
);
1782 OO
.initClass( OO
.ui
.Theme
);
1787 * Get a list of classes to be applied to a widget.
1789 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
1790 * otherwise state transitions will not work properly.
1792 * @param {OO.ui.Element} element Element for which to get classes
1793 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
1795 OO
.ui
.Theme
.prototype.getElementClasses = function () {
1796 return { on
: [], off
: [] };
1800 * Update CSS classes provided by the theme.
1802 * For elements with theme logic hooks, this should be called any time there's a state change.
1804 * @param {OO.ui.Element} element Element for which to update classes
1806 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
1807 var $elements
= $( [] ),
1808 classes
= this.getElementClasses( element
);
1810 if ( element
.$icon
) {
1811 $elements
= $elements
.add( element
.$icon
);
1813 if ( element
.$indicator
) {
1814 $elements
= $elements
.add( element
.$indicator
);
1818 .removeClass( classes
.off
.join( ' ' ) )
1819 .addClass( classes
.on
.join( ' ' ) );
1825 OO
.ui
.Theme
.prototype.updateQueuedElementClasses = function () {
1827 for ( i
= 0; i
< this.elementClassesQueue
.length
; i
++ ) {
1828 this.updateElementClasses( this.elementClassesQueue
[ i
] );
1831 this.elementClassesQueue
= [];
1835 * Queue #updateElementClasses to be called for this element.
1837 * @localdoc QUnit tests override this method to directly call #queueUpdateElementClasses,
1838 * to make them synchronous.
1840 * @param {OO.ui.Element} element Element for which to update classes
1842 OO
.ui
.Theme
.prototype.queueUpdateElementClasses = function ( element
) {
1843 // Keep items in the queue unique. Use lastIndexOf to start checking from the end because that's
1844 // the most common case (this method is often called repeatedly for the same element).
1845 if ( this.elementClassesQueue
.lastIndexOf( element
) !== -1 ) {
1848 this.elementClassesQueue
.push( element
);
1849 this.debouncedUpdateQueuedElementClasses();
1853 * Get the transition duration in milliseconds for dialogs opening/closing
1855 * The dialog should be fully rendered this many milliseconds after the
1856 * ready process has executed.
1858 * @return {number} Transition duration in milliseconds
1860 OO
.ui
.Theme
.prototype.getDialogTransitionDuration = function () {
1865 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
1866 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
1867 * order in which users will navigate through the focusable elements via the "tab" key.
1870 * // TabIndexedElement is mixed into the ButtonWidget class
1871 * // to provide a tabIndex property.
1872 * var button1 = new OO.ui.ButtonWidget( {
1876 * var button2 = new OO.ui.ButtonWidget( {
1880 * var button3 = new OO.ui.ButtonWidget( {
1884 * var button4 = new OO.ui.ButtonWidget( {
1888 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
1894 * @param {Object} [config] Configuration options
1895 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
1896 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
1897 * functionality will be applied to it instead.
1898 * @cfg {string|number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
1899 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
1900 * to remove the element from the tab-navigation flow.
1902 OO
.ui
.mixin
.TabIndexedElement
= function OoUiMixinTabIndexedElement( config
) {
1903 // Configuration initialization
1904 config
= $.extend( { tabIndex
: 0 }, config
);
1907 this.$tabIndexed
= null;
1908 this.tabIndex
= null;
1911 this.connect( this, { disable
: 'onTabIndexedElementDisable' } );
1914 this.setTabIndex( config
.tabIndex
);
1915 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
1920 OO
.initClass( OO
.ui
.mixin
.TabIndexedElement
);
1925 * Set the element that should use the tabindex functionality.
1927 * This method is used to retarget a tabindex mixin so that its functionality applies
1928 * to the specified element. If an element is currently using the functionality, the mixin’s
1929 * effect on that element is removed before the new element is set up.
1931 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
1934 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
1935 var tabIndex
= this.tabIndex
;
1936 // Remove attributes from old $tabIndexed
1937 this.setTabIndex( null );
1938 // Force update of new $tabIndexed
1939 this.$tabIndexed
= $tabIndexed
;
1940 this.tabIndex
= tabIndex
;
1941 return this.updateTabIndex();
1945 * Set the value of the tabindex.
1947 * @param {string|number|null} tabIndex Tabindex value, or `null` for no tabindex
1950 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
1951 tabIndex
= /^-?\d+$/.test( tabIndex
) ? Number( tabIndex
) : null;
1953 if ( this.tabIndex
!== tabIndex
) {
1954 this.tabIndex
= tabIndex
;
1955 this.updateTabIndex();
1962 * Update the `tabindex` attribute, in case of changes to tab index or
1968 OO
.ui
.mixin
.TabIndexedElement
.prototype.updateTabIndex = function () {
1969 if ( this.$tabIndexed
) {
1970 if ( this.tabIndex
!== null ) {
1971 // Do not index over disabled elements
1972 this.$tabIndexed
.attr( {
1973 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
1974 // Support: ChromeVox and NVDA
1975 // These do not seem to inherit aria-disabled from parent elements
1976 'aria-disabled': this.isDisabled().toString()
1979 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
1986 * Handle disable events.
1989 * @param {boolean} disabled Element is disabled
1991 OO
.ui
.mixin
.TabIndexedElement
.prototype.onTabIndexedElementDisable = function () {
1992 this.updateTabIndex();
1996 * Get the value of the tabindex.
1998 * @return {number|null} Tabindex value
2000 OO
.ui
.mixin
.TabIndexedElement
.prototype.getTabIndex = function () {
2001 return this.tabIndex
;
2005 * Get an ID of a focusable element of this widget, if any, to be used for `<label for>` value.
2007 * If the element already has an ID then that is returned, otherwise unique ID is
2008 * generated, set on the element, and returned.
2010 * @return {string|null} The ID of the focusable element
2012 OO
.ui
.mixin
.TabIndexedElement
.prototype.getInputId = function () {
2015 if ( !this.$tabIndexed
) {
2018 if ( !this.isLabelableNode( this.$tabIndexed
) ) {
2022 id
= this.$tabIndexed
.attr( 'id' );
2023 if ( id
=== undefined ) {
2024 id
= OO
.ui
.generateElementId();
2025 this.$tabIndexed
.attr( 'id', id
);
2032 * Whether the node is 'labelable' according to the HTML spec
2033 * (i.e., whether it can be interacted with through a `<label for="…">`).
2034 * See: <https://html.spec.whatwg.org/multipage/forms.html#category-label>.
2037 * @param {jQuery} $node
2040 OO
.ui
.mixin
.TabIndexedElement
.prototype.isLabelableNode = function ( $node
) {
2042 labelableTags
= [ 'button', 'meter', 'output', 'progress', 'select', 'textarea' ],
2043 tagName
= $node
.prop( 'tagName' ).toLowerCase();
2045 if ( tagName
=== 'input' && $node
.attr( 'type' ) !== 'hidden' ) {
2048 if ( labelableTags
.indexOf( tagName
) !== -1 ) {
2055 * Focus this element.
2059 OO
.ui
.mixin
.TabIndexedElement
.prototype.focus = function () {
2060 if ( !this.isDisabled() ) {
2061 this.$tabIndexed
.focus();
2067 * Blur this element.
2071 OO
.ui
.mixin
.TabIndexedElement
.prototype.blur = function () {
2072 this.$tabIndexed
.blur();
2077 * @inheritdoc OO.ui.Widget
2079 OO
.ui
.mixin
.TabIndexedElement
.prototype.simulateLabelClick = function () {
2084 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
2085 * interface element that can be configured with access keys for accessibility.
2086 * See the [OOUI documentation on MediaWiki] [1] for examples.
2088 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches#Buttons
2094 * @param {Object} [config] Configuration options
2095 * @cfg {jQuery} [$button] The button element created by the class.
2096 * If this configuration is omitted, the button element will use a generated `<a>`.
2097 * @cfg {boolean} [framed=true] Render the button with a frame
2099 OO
.ui
.mixin
.ButtonElement
= function OoUiMixinButtonElement( config
) {
2100 // Configuration initialization
2101 config
= config
|| {};
2104 this.$button
= null;
2106 this.active
= config
.active
!== undefined && config
.active
;
2107 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
2108 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
2109 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
2110 this.onKeyUpHandler
= this.onKeyUp
.bind( this );
2111 this.onClickHandler
= this.onClick
.bind( this );
2112 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
2115 this.$element
.addClass( 'oo-ui-buttonElement' );
2116 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
2117 this.setButtonElement( config
.$button
|| $( '<a>' ) );
2122 OO
.initClass( OO
.ui
.mixin
.ButtonElement
);
2124 /* Static Properties */
2127 * Cancel mouse down events.
2129 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
2130 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
2131 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
2136 * @property {boolean}
2138 OO
.ui
.mixin
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
2143 * A 'click' event is emitted when the button element is clicked.
2151 * Set the button element.
2153 * This method is used to retarget a button mixin so that its functionality applies to
2154 * the specified button element instead of the one created by the class. If a button element
2155 * is already set, the method will remove the mixin’s effect on that element.
2157 * @param {jQuery} $button Element to use as button
2159 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
2160 if ( this.$button
) {
2162 .removeClass( 'oo-ui-buttonElement-button' )
2163 .removeAttr( 'role accesskey' )
2165 mousedown
: this.onMouseDownHandler
,
2166 keydown
: this.onKeyDownHandler
,
2167 click
: this.onClickHandler
,
2168 keypress
: this.onKeyPressHandler
2172 this.$button
= $button
2173 .addClass( 'oo-ui-buttonElement-button' )
2175 mousedown
: this.onMouseDownHandler
,
2176 keydown
: this.onKeyDownHandler
,
2177 click
: this.onClickHandler
,
2178 keypress
: this.onKeyPressHandler
2181 // Add `role="button"` on `<a>` elements, where it's needed
2182 // `toUppercase()` is added for XHTML documents
2183 if ( this.$button
.prop( 'tagName' ).toUpperCase() === 'A' ) {
2184 this.$button
.attr( 'role', 'button' );
2189 * Handles mouse down events.
2192 * @param {jQuery.Event} e Mouse down event
2194 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown = function ( e
) {
2195 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
2198 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
2199 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
2200 // reliably remove the pressed class
2201 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
2202 // Prevent change of focus unless specifically configured otherwise
2203 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
2209 * Handles mouse up events.
2212 * @param {MouseEvent} e Mouse up event
2214 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp = function ( e
) {
2215 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
2218 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
2219 // Stop listening for mouseup, since we only needed this once
2220 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
2224 * Handles mouse click events.
2227 * @param {jQuery.Event} e Mouse click event
2230 OO
.ui
.mixin
.ButtonElement
.prototype.onClick = function ( e
) {
2231 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
2232 if ( this.emit( 'click' ) ) {
2239 * Handles key down events.
2242 * @param {jQuery.Event} e Key down event
2244 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyDown = function ( e
) {
2245 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
2248 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
2249 // Run the keyup handler no matter where the key is when the button is let go, so we can
2250 // reliably remove the pressed class
2251 this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler
, true );
2255 * Handles key up events.
2258 * @param {KeyboardEvent} e Key up event
2260 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyUp = function ( e
) {
2261 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
2264 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
2265 // Stop listening for keyup, since we only needed this once
2266 this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler
, true );
2270 * Handles key press events.
2273 * @param {jQuery.Event} e Key press event
2276 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyPress = function ( e
) {
2277 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
2278 if ( this.emit( 'click' ) ) {
2285 * Check if button has a frame.
2287 * @return {boolean} Button is framed
2289 OO
.ui
.mixin
.ButtonElement
.prototype.isFramed = function () {
2294 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
2296 * @param {boolean} [framed] Make button framed, omit to toggle
2299 OO
.ui
.mixin
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
2300 framed
= framed
=== undefined ? !this.framed
: !!framed
;
2301 if ( framed
!== this.framed
) {
2302 this.framed
= framed
;
2304 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
2305 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
2306 this.updateThemeClasses();
2313 * Set the button's active state.
2315 * The active state can be set on:
2317 * - {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} when it is selected
2318 * - {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} when it is toggle on
2319 * - {@link OO.ui.ButtonWidget ButtonWidget} when clicking the button would only refresh the page
2322 * @param {boolean} value Make button active
2325 OO
.ui
.mixin
.ButtonElement
.prototype.setActive = function ( value
) {
2326 this.active
= !!value
;
2327 this.$element
.toggleClass( 'oo-ui-buttonElement-active', this.active
);
2328 this.updateThemeClasses();
2333 * Check if the button is active
2336 * @return {boolean} The button is active
2338 OO
.ui
.mixin
.ButtonElement
.prototype.isActive = function () {
2343 * Any OOUI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
2344 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
2345 * items from the group is done through the interface the class provides.
2346 * For more information, please see the [OOUI documentation on MediaWiki] [1].
2348 * [1]: https://www.mediawiki.org/wiki/OOUI/Elements/Groups
2351 * @mixins OO.EmitterList
2355 * @param {Object} [config] Configuration options
2356 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
2357 * is omitted, the group element will use a generated `<div>`.
2359 OO
.ui
.mixin
.GroupElement
= function OoUiMixinGroupElement( config
) {
2360 // Configuration initialization
2361 config
= config
|| {};
2363 // Mixin constructors
2364 OO
.EmitterList
.call( this, config
);
2370 this.setGroupElement( config
.$group
|| $( '<div>' ) );
2375 OO
.mixinClass( OO
.ui
.mixin
.GroupElement
, OO
.EmitterList
);
2382 * A change event is emitted when the set of selected items changes.
2384 * @param {OO.ui.Element[]} items Items currently in the group
2390 * Set the group element.
2392 * If an element is already set, items will be moved to the new element.
2394 * @param {jQuery} $group Element to use as group
2396 OO
.ui
.mixin
.GroupElement
.prototype.setGroupElement = function ( $group
) {
2399 this.$group
= $group
;
2400 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2401 this.$group
.append( this.items
[ i
].$element
);
2406 * Find an item by its data.
2408 * Only the first item with matching data will be returned. To return all matching items,
2409 * use the #findItemsFromData method.
2411 * @param {Object} data Item data to search for
2412 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
2414 OO
.ui
.mixin
.GroupElement
.prototype.findItemFromData = function ( data
) {
2416 hash
= OO
.getHash( data
);
2418 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2419 item
= this.items
[ i
];
2420 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2429 * Find items by their data.
2431 * All items with matching data will be returned. To return only the first match, use the #findItemFromData method instead.
2433 * @param {Object} data Item data to search for
2434 * @return {OO.ui.Element[]} Items with equivalent data
2436 OO
.ui
.mixin
.GroupElement
.prototype.findItemsFromData = function ( data
) {
2438 hash
= OO
.getHash( data
),
2441 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2442 item
= this.items
[ i
];
2443 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2452 * Add items to the group.
2454 * Items will be added to the end of the group array unless the optional `index` parameter specifies
2455 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
2457 * @param {OO.ui.Element[]} items An array of items to add to the group
2458 * @param {number} [index] Index of the insertion point
2461 OO
.ui
.mixin
.GroupElement
.prototype.addItems = function ( items
, index
) {
2463 OO
.EmitterList
.prototype.addItems
.call( this, items
, index
);
2465 this.emit( 'change', this.getItems() );
2472 OO
.ui
.mixin
.GroupElement
.prototype.moveItem = function ( items
, newIndex
) {
2473 // insertItemElements expects this.items to not have been modified yet, so call before the mixin
2474 this.insertItemElements( items
, newIndex
);
2477 newIndex
= OO
.EmitterList
.prototype.moveItem
.call( this, items
, newIndex
);
2485 OO
.ui
.mixin
.GroupElement
.prototype.insertItem = function ( item
, index
) {
2486 item
.setElementGroup( this );
2487 this.insertItemElements( item
, index
);
2490 index
= OO
.EmitterList
.prototype.insertItem
.call( this, item
, index
);
2496 * Insert elements into the group
2499 * @param {OO.ui.Element} itemWidget Item to insert
2500 * @param {number} index Insertion index
2502 OO
.ui
.mixin
.GroupElement
.prototype.insertItemElements = function ( itemWidget
, index
) {
2503 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
2504 this.$group
.append( itemWidget
.$element
);
2505 } else if ( index
=== 0 ) {
2506 this.$group
.prepend( itemWidget
.$element
);
2508 this.items
[ index
].$element
.before( itemWidget
.$element
);
2513 * Remove the specified items from a group.
2515 * Removed items are detached (not removed) from the DOM so that they may be reused.
2516 * To remove all items from a group, you may wish to use the #clearItems method instead.
2518 * @param {OO.ui.Element[]} items An array of items to remove
2521 OO
.ui
.mixin
.GroupElement
.prototype.removeItems = function ( items
) {
2522 var i
, len
, item
, index
;
2524 // Remove specific items elements
2525 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
2527 index
= this.items
.indexOf( item
);
2528 if ( index
!== -1 ) {
2529 item
.setElementGroup( null );
2530 item
.$element
.detach();
2535 OO
.EmitterList
.prototype.removeItems
.call( this, items
);
2537 this.emit( 'change', this.getItems() );
2542 * Clear all items from the group.
2544 * Cleared items are detached from the DOM, not removed, so that they may be reused.
2545 * To remove only a subset of items from a group, use the #removeItems method.
2549 OO
.ui
.mixin
.GroupElement
.prototype.clearItems = function () {
2552 // Remove all item elements
2553 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2554 this.items
[ i
].setElementGroup( null );
2555 this.items
[ i
].$element
.detach();
2559 OO
.EmitterList
.prototype.clearItems
.call( this );
2561 this.emit( 'change', this.getItems() );
2566 * IconElement is often mixed into other classes to generate an icon.
2567 * Icons are graphics, about the size of normal text. They are used to aid the user
2568 * in locating a control or to convey information in a space-efficient way. See the
2569 * [OOUI documentation on MediaWiki] [1] for a list of icons
2570 * included in the library.
2572 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
2578 * @param {Object} [config] Configuration options
2579 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
2580 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
2581 * the icon element be set to an existing icon instead of the one generated by this class, set a
2582 * value using a jQuery selection. For example:
2584 * // Use a <div> tag instead of a <span>
2586 * // Use an existing icon element instead of the one generated by the class
2587 * $icon: this.$element
2588 * // Use an icon element from a child widget
2589 * $icon: this.childwidget.$element
2590 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
2591 * symbolic names. A map is used for i18n purposes and contains a `default` icon
2592 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
2593 * by the user's language.
2595 * Example of an i18n map:
2597 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2598 * See the [OOUI documentation on MediaWiki] [2] for a list of icons included in the library.
2599 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
2600 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
2601 * text. The icon title is displayed when users move the mouse over the icon.
2603 OO
.ui
.mixin
.IconElement
= function OoUiMixinIconElement( config
) {
2604 // Configuration initialization
2605 config
= config
|| {};
2610 this.iconTitle
= null;
2613 this.setIcon( config
.icon
|| this.constructor.static.icon
);
2614 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
2615 this.setIconElement( config
.$icon
|| $( '<span>' ) );
2620 OO
.initClass( OO
.ui
.mixin
.IconElement
);
2622 /* Static Properties */
2625 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
2626 * for i18n purposes and contains a `default` icon name and additional names keyed by
2627 * language code. The `default` name is used when no icon is keyed by the user's language.
2629 * Example of an i18n map:
2631 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2633 * Note: the static property will be overridden if the #icon configuration is used.
2637 * @property {Object|string}
2639 OO
.ui
.mixin
.IconElement
.static.icon
= null;
2642 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
2643 * function that returns title text, or `null` for no title.
2645 * The static property will be overridden if the #iconTitle configuration is used.
2649 * @property {string|Function|null}
2651 OO
.ui
.mixin
.IconElement
.static.iconTitle
= null;
2656 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
2657 * applies to the specified icon element instead of the one created by the class. If an icon
2658 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
2659 * and mixin methods will no longer affect the element.
2661 * @param {jQuery} $icon Element to use as icon
2663 OO
.ui
.mixin
.IconElement
.prototype.setIconElement = function ( $icon
) {
2666 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
2667 .removeAttr( 'title' );
2671 .addClass( 'oo-ui-iconElement-icon' )
2672 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
2673 if ( this.iconTitle
!== null ) {
2674 this.$icon
.attr( 'title', this.iconTitle
);
2677 this.updateThemeClasses();
2681 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
2682 * The icon parameter can also be set to a map of icon names. See the #icon config setting
2685 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
2686 * by language code, or `null` to remove the icon.
2689 OO
.ui
.mixin
.IconElement
.prototype.setIcon = function ( icon
) {
2690 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
2691 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
2693 if ( this.icon
!== icon
) {
2695 if ( this.icon
!== null ) {
2696 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
2698 if ( icon
!== null ) {
2699 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
2705 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
2706 this.updateThemeClasses();
2712 * Set the icon title. Use `null` to remove the title.
2714 * @param {string|Function|null} iconTitle A text string used as the icon title,
2715 * a function that returns title text, or `null` for no title.
2718 OO
.ui
.mixin
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
2720 ( typeof iconTitle
=== 'function' || ( typeof iconTitle
=== 'string' && iconTitle
.length
) ) ?
2721 OO
.ui
.resolveMsg( iconTitle
) : null;
2723 if ( this.iconTitle
!== iconTitle
) {
2724 this.iconTitle
= iconTitle
;
2726 if ( this.iconTitle
!== null ) {
2727 this.$icon
.attr( 'title', iconTitle
);
2729 this.$icon
.removeAttr( 'title' );
2738 * Get the symbolic name of the icon.
2740 * @return {string} Icon name
2742 OO
.ui
.mixin
.IconElement
.prototype.getIcon = function () {
2747 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
2749 * @return {string} Icon title text
2751 OO
.ui
.mixin
.IconElement
.prototype.getIconTitle = function () {
2752 return this.iconTitle
;
2756 * IndicatorElement is often mixed into other classes to generate an indicator.
2757 * Indicators are small graphics that are generally used in two ways:
2759 * - To draw attention to the status of an item. For example, an indicator might be
2760 * used to show that an item in a list has errors that need to be resolved.
2761 * - To clarify the function of a control that acts in an exceptional way (a button
2762 * that opens a menu instead of performing an action directly, for example).
2764 * For a list of indicators included in the library, please see the
2765 * [OOUI documentation on MediaWiki] [1].
2767 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2773 * @param {Object} [config] Configuration options
2774 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
2775 * configuration is omitted, the indicator element will use a generated `<span>`.
2776 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
2777 * See the [OOUI documentation on MediaWiki][2] for a list of indicators included
2779 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2780 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
2781 * or a function that returns title text. The indicator title is displayed when users move
2782 * the mouse over the indicator.
2784 OO
.ui
.mixin
.IndicatorElement
= function OoUiMixinIndicatorElement( config
) {
2785 // Configuration initialization
2786 config
= config
|| {};
2789 this.$indicator
= null;
2790 this.indicator
= null;
2791 this.indicatorTitle
= null;
2794 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
2795 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
2796 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
2801 OO
.initClass( OO
.ui
.mixin
.IndicatorElement
);
2803 /* Static Properties */
2806 * Symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
2807 * The static property will be overridden if the #indicator configuration is used.
2811 * @property {string|null}
2813 OO
.ui
.mixin
.IndicatorElement
.static.indicator
= null;
2816 * A text string used as the indicator title, a function that returns title text, or `null`
2817 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
2821 * @property {string|Function|null}
2823 OO
.ui
.mixin
.IndicatorElement
.static.indicatorTitle
= null;
2828 * Set the indicator element.
2830 * If an element is already set, it will be cleaned up before setting up the new element.
2832 * @param {jQuery} $indicator Element to use as indicator
2834 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
2835 if ( this.$indicator
) {
2837 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
2838 .removeAttr( 'title' );
2841 this.$indicator
= $indicator
2842 .addClass( 'oo-ui-indicatorElement-indicator' )
2843 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
2844 if ( this.indicatorTitle
!== null ) {
2845 this.$indicator
.attr( 'title', this.indicatorTitle
);
2848 this.updateThemeClasses();
2852 * Set the indicator by its symbolic name: ‘clear’, ‘down’, ‘required’, ‘search’, ‘up’. Use `null` to remove the indicator.
2854 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
2857 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
2858 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
2860 if ( this.indicator
!== indicator
) {
2861 if ( this.$indicator
) {
2862 if ( this.indicator
!== null ) {
2863 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
2865 if ( indicator
!== null ) {
2866 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
2869 this.indicator
= indicator
;
2872 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
2873 this.updateThemeClasses();
2879 * Set the indicator title.
2881 * The title is displayed when a user moves the mouse over the indicator.
2883 * @param {string|Function|null} indicatorTitle Indicator title text, a function that returns text, or
2884 * `null` for no indicator title
2887 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorTitle = function ( indicatorTitle
) {
2889 ( typeof indicatorTitle
=== 'function' || ( typeof indicatorTitle
=== 'string' && indicatorTitle
.length
) ) ?
2890 OO
.ui
.resolveMsg( indicatorTitle
) : null;
2892 if ( this.indicatorTitle
!== indicatorTitle
) {
2893 this.indicatorTitle
= indicatorTitle
;
2894 if ( this.$indicator
) {
2895 if ( this.indicatorTitle
!== null ) {
2896 this.$indicator
.attr( 'title', indicatorTitle
);
2898 this.$indicator
.removeAttr( 'title' );
2907 * Get the symbolic name of the indicator (e.g., ‘clear’ or ‘down’).
2909 * @return {string} Symbolic name of indicator
2911 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicator = function () {
2912 return this.indicator
;
2916 * Get the indicator title.
2918 * The title is displayed when a user moves the mouse over the indicator.
2920 * @return {string} Indicator title text
2922 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicatorTitle = function () {
2923 return this.indicatorTitle
;
2927 * LabelElement is often mixed into other classes to generate a label, which
2928 * helps identify the function of an interface element.
2929 * See the [OOUI documentation on MediaWiki] [1] for more information.
2931 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Labels
2937 * @param {Object} [config] Configuration options
2938 * @cfg {jQuery} [$label] The label element created by the class. If this
2939 * configuration is omitted, the label element will use a generated `<span>`.
2940 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
2941 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
2942 * in the future. See the [OOUI documentation on MediaWiki] [2] for examples.
2943 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Labels
2945 OO
.ui
.mixin
.LabelElement
= function OoUiMixinLabelElement( config
) {
2946 // Configuration initialization
2947 config
= config
|| {};
2954 this.setLabel( config
.label
|| this.constructor.static.label
);
2955 this.setLabelElement( config
.$label
|| $( '<span>' ) );
2960 OO
.initClass( OO
.ui
.mixin
.LabelElement
);
2965 * @event labelChange
2966 * @param {string} value
2969 /* Static Properties */
2972 * The label text. The label can be specified as a plaintext string, a function that will
2973 * produce a string in the future, or `null` for no label. The static value will
2974 * be overridden if a label is specified with the #label config option.
2978 * @property {string|Function|null}
2980 OO
.ui
.mixin
.LabelElement
.static.label
= null;
2982 /* Static methods */
2985 * Highlight the first occurrence of the query in the given text
2987 * @param {string} text Text
2988 * @param {string} query Query to find
2989 * @param {Function} [compare] Optional string comparator, e.g. Intl.Collator().compare
2990 * @return {jQuery} Text with the first match of the query
2991 * sub-string wrapped in highlighted span
2993 OO
.ui
.mixin
.LabelElement
.static.highlightQuery = function ( text
, query
, compare
) {
2996 $result
= $( '<span>' );
3000 qLen
= query
.length
;
3001 for ( i
= 0; offset
=== -1 && i
<= tLen
- qLen
; i
++ ) {
3002 if ( compare( query
, text
.slice( i
, i
+ qLen
) ) === 0 ) {
3007 offset
= text
.toLowerCase().indexOf( query
.toLowerCase() );
3010 if ( !query
.length
|| offset
=== -1 ) {
3011 $result
.text( text
);
3014 document
.createTextNode( text
.slice( 0, offset
) ),
3016 .addClass( 'oo-ui-labelElement-label-highlight' )
3017 .text( text
.slice( offset
, offset
+ query
.length
) ),
3018 document
.createTextNode( text
.slice( offset
+ query
.length
) )
3021 return $result
.contents();
3027 * Set the label element.
3029 * If an element is already set, it will be cleaned up before setting up the new element.
3031 * @param {jQuery} $label Element to use as label
3033 OO
.ui
.mixin
.LabelElement
.prototype.setLabelElement = function ( $label
) {
3034 if ( this.$label
) {
3035 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
3038 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
3039 this.setLabelContent( this.label
);
3045 * An empty string will result in the label being hidden. A string containing only whitespace will
3046 * be converted to a single ` `.
3048 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
3049 * text; or null for no label
3052 OO
.ui
.mixin
.LabelElement
.prototype.setLabel = function ( label
) {
3053 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
3054 label
= ( ( typeof label
=== 'string' || label
instanceof jQuery
) && label
.length
) || ( label
instanceof OO
.ui
.HtmlSnippet
&& label
.toString().length
) ? label
: null;
3056 if ( this.label
!== label
) {
3057 if ( this.$label
) {
3058 this.setLabelContent( label
);
3061 this.emit( 'labelChange' );
3064 this.$element
.toggleClass( 'oo-ui-labelElement', !!this.label
);
3070 * Set the label as plain text with a highlighted query
3072 * @param {string} text Text label to set
3073 * @param {string} query Substring of text to highlight
3074 * @param {Function} [compare] Optional string comparator, e.g. Intl.Collator().compare
3077 OO
.ui
.mixin
.LabelElement
.prototype.setHighlightedQuery = function ( text
, query
, compare
) {
3078 return this.setLabel( this.constructor.static.highlightQuery( text
, query
, compare
) );
3084 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
3085 * text; or null for no label
3087 OO
.ui
.mixin
.LabelElement
.prototype.getLabel = function () {
3092 * Set the content of the label.
3094 * Do not call this method until after the label element has been set by #setLabelElement.
3097 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
3098 * text; or null for no label
3100 OO
.ui
.mixin
.LabelElement
.prototype.setLabelContent = function ( label
) {
3101 if ( typeof label
=== 'string' ) {
3102 if ( label
.match( /^\s*$/ ) ) {
3103 // Convert whitespace only string to a single non-breaking space
3104 this.$label
.html( ' ' );
3106 this.$label
.text( label
);
3108 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
3109 this.$label
.html( label
.toString() );
3110 } else if ( label
instanceof jQuery
) {
3111 this.$label
.empty().append( label
);
3113 this.$label
.empty();
3118 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
3119 * additional functionality to an element created by another class. The class provides
3120 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
3121 * which are used to customize the look and feel of a widget to better describe its
3122 * importance and functionality.
3124 * The library currently contains the following styling flags for general use:
3126 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
3127 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
3129 * The flags affect the appearance of the buttons:
3132 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
3133 * var button1 = new OO.ui.ButtonWidget( {
3134 * label: 'Progressive',
3135 * flags: 'progressive'
3137 * var button2 = new OO.ui.ButtonWidget( {
3138 * label: 'Destructive',
3139 * flags: 'destructive'
3141 * $( 'body' ).append( button1.$element, button2.$element );
3143 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
3144 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
3146 * [1]: https://www.mediawiki.org/wiki/OOUI/Elements/Flagged
3152 * @param {Object} [config] Configuration options
3153 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'progressive' or 'primary') to apply.
3154 * Please see the [OOUI documentation on MediaWiki] [2] for more information about available flags.
3155 * [2]: https://www.mediawiki.org/wiki/OOUI/Elements/Flagged
3156 * @cfg {jQuery} [$flagged] The flagged element. By default,
3157 * the flagged functionality is applied to the element created by the class ($element).
3158 * If a different element is specified, the flagged functionality will be applied to it instead.
3160 OO
.ui
.mixin
.FlaggedElement
= function OoUiMixinFlaggedElement( config
) {
3161 // Configuration initialization
3162 config
= config
|| {};
3166 this.$flagged
= null;
3169 this.setFlags( config
.flags
);
3170 this.setFlaggedElement( config
.$flagged
|| this.$element
);
3177 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
3178 * parameter contains the name of each modified flag and indicates whether it was
3181 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
3182 * that the flag was added, `false` that the flag was removed.
3188 * Set the flagged element.
3190 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
3191 * If an element is already set, the method will remove the mixin’s effect on that element.
3193 * @param {jQuery} $flagged Element that should be flagged
3195 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
3196 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
3197 return 'oo-ui-flaggedElement-' + flag
;
3200 if ( this.$flagged
) {
3201 this.$flagged
.removeClass( classNames
);
3204 this.$flagged
= $flagged
.addClass( classNames
);
3208 * Check if the specified flag is set.
3210 * @param {string} flag Name of flag
3211 * @return {boolean} The flag is set
3213 OO
.ui
.mixin
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
3214 // This may be called before the constructor, thus before this.flags is set
3215 return this.flags
&& ( flag
in this.flags
);
3219 * Get the names of all flags set.
3221 * @return {string[]} Flag names
3223 OO
.ui
.mixin
.FlaggedElement
.prototype.getFlags = function () {
3224 // This may be called before the constructor, thus before this.flags is set
3225 return Object
.keys( this.flags
|| {} );
3234 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags = function () {
3235 var flag
, className
,
3238 classPrefix
= 'oo-ui-flaggedElement-';
3240 for ( flag
in this.flags
) {
3241 className
= classPrefix
+ flag
;
3242 changes
[ flag
] = false;
3243 delete this.flags
[ flag
];
3244 remove
.push( className
);
3247 if ( this.$flagged
) {
3248 this.$flagged
.removeClass( remove
.join( ' ' ) );
3251 this.updateThemeClasses();
3252 this.emit( 'flag', changes
);
3258 * Add one or more flags.
3260 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
3261 * or an object keyed by flag name with a boolean value that indicates whether the flag should
3262 * be added (`true`) or removed (`false`).
3266 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags = function ( flags
) {
3267 var i
, len
, flag
, className
,
3271 classPrefix
= 'oo-ui-flaggedElement-';
3273 if ( typeof flags
=== 'string' ) {
3274 className
= classPrefix
+ flags
;
3276 if ( !this.flags
[ flags
] ) {
3277 this.flags
[ flags
] = true;
3278 add
.push( className
);
3280 } else if ( Array
.isArray( flags
) ) {
3281 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
3283 className
= classPrefix
+ flag
;
3285 if ( !this.flags
[ flag
] ) {
3286 changes
[ flag
] = true;
3287 this.flags
[ flag
] = true;
3288 add
.push( className
);
3291 } else if ( OO
.isPlainObject( flags
) ) {
3292 for ( flag
in flags
) {
3293 className
= classPrefix
+ flag
;
3294 if ( flags
[ flag
] ) {
3296 if ( !this.flags
[ flag
] ) {
3297 changes
[ flag
] = true;
3298 this.flags
[ flag
] = true;
3299 add
.push( className
);
3303 if ( this.flags
[ flag
] ) {
3304 changes
[ flag
] = false;
3305 delete this.flags
[ flag
];
3306 remove
.push( className
);
3312 if ( this.$flagged
) {
3314 .addClass( add
.join( ' ' ) )
3315 .removeClass( remove
.join( ' ' ) );
3318 this.updateThemeClasses();
3319 this.emit( 'flag', changes
);
3325 * TitledElement is mixed into other classes to provide a `title` attribute.
3326 * Titles are rendered by the browser and are made visible when the user moves
3327 * the mouse over the element. Titles are not visible on touch devices.
3330 * // TitledElement provides a 'title' attribute to the
3331 * // ButtonWidget class
3332 * var button = new OO.ui.ButtonWidget( {
3333 * label: 'Button with Title',
3334 * title: 'I am a button'
3336 * $( 'body' ).append( button.$element );
3342 * @param {Object} [config] Configuration options
3343 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
3344 * If this config is omitted, the title functionality is applied to $element, the
3345 * element created by the class.
3346 * @cfg {string|Function} [title] The title text or a function that returns text. If
3347 * this config is omitted, the value of the {@link #static-title static title} property is used.
3349 OO
.ui
.mixin
.TitledElement
= function OoUiMixinTitledElement( config
) {
3350 // Configuration initialization
3351 config
= config
|| {};
3354 this.$titled
= null;
3358 this.setTitle( config
.title
!== undefined ? config
.title
: this.constructor.static.title
);
3359 this.setTitledElement( config
.$titled
|| this.$element
);
3364 OO
.initClass( OO
.ui
.mixin
.TitledElement
);
3366 /* Static Properties */
3369 * The title text, a function that returns text, or `null` for no title. The value of the static property
3370 * is overridden if the #title config option is used.
3374 * @property {string|Function|null}
3376 OO
.ui
.mixin
.TitledElement
.static.title
= null;
3381 * Set the titled element.
3383 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
3384 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
3386 * @param {jQuery} $titled Element that should use the 'titled' functionality
3388 OO
.ui
.mixin
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
3389 if ( this.$titled
) {
3390 this.$titled
.removeAttr( 'title' );
3393 this.$titled
= $titled
;
3402 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
3405 OO
.ui
.mixin
.TitledElement
.prototype.setTitle = function ( title
) {
3406 title
= typeof title
=== 'function' ? OO
.ui
.resolveMsg( title
) : title
;
3407 title
= ( typeof title
=== 'string' && title
.length
) ? title
: null;
3409 if ( this.title
!== title
) {
3418 * Update the title attribute, in case of changes to title or accessKey.
3423 OO
.ui
.mixin
.TitledElement
.prototype.updateTitle = function () {
3424 var title
= this.getTitle();
3425 if ( this.$titled
) {
3426 if ( title
!== null ) {
3427 // Only if this is an AccessKeyedElement
3428 if ( this.formatTitleWithAccessKey
) {
3429 title
= this.formatTitleWithAccessKey( title
);
3431 this.$titled
.attr( 'title', title
);
3433 this.$titled
.removeAttr( 'title' );
3442 * @return {string} Title string
3444 OO
.ui
.mixin
.TitledElement
.prototype.getTitle = function () {
3449 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
3450 * Accesskeys allow an user to go to a specific element by using
3451 * a shortcut combination of a browser specific keys + the key
3455 * // AccessKeyedElement provides an 'accesskey' attribute to the
3456 * // ButtonWidget class
3457 * var button = new OO.ui.ButtonWidget( {
3458 * label: 'Button with Accesskey',
3461 * $( 'body' ).append( button.$element );
3467 * @param {Object} [config] Configuration options
3468 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
3469 * If this config is omitted, the accesskey functionality is applied to $element, the
3470 * element created by the class.
3471 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
3472 * this config is omitted, no accesskey will be added.
3474 OO
.ui
.mixin
.AccessKeyedElement
= function OoUiMixinAccessKeyedElement( config
) {
3475 // Configuration initialization
3476 config
= config
|| {};
3479 this.$accessKeyed
= null;
3480 this.accessKey
= null;
3483 this.setAccessKey( config
.accessKey
|| null );
3484 this.setAccessKeyedElement( config
.$accessKeyed
|| this.$element
);
3486 // If this is also a TitledElement and it initialized before we did, we may have
3487 // to update the title with the access key
3488 if ( this.updateTitle
) {
3495 OO
.initClass( OO
.ui
.mixin
.AccessKeyedElement
);
3497 /* Static Properties */
3500 * The access key, a function that returns a key, or `null` for no accesskey.
3504 * @property {string|Function|null}
3506 OO
.ui
.mixin
.AccessKeyedElement
.static.accessKey
= null;
3511 * Set the accesskeyed element.
3513 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
3514 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
3516 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
3518 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKeyedElement = function ( $accessKeyed
) {
3519 if ( this.$accessKeyed
) {
3520 this.$accessKeyed
.removeAttr( 'accesskey' );
3523 this.$accessKeyed
= $accessKeyed
;
3524 if ( this.accessKey
) {
3525 this.$accessKeyed
.attr( 'accesskey', this.accessKey
);
3532 * @param {string|Function|null} accessKey Key, a function that returns a key, or `null` for no accesskey
3535 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKey = function ( accessKey
) {
3536 accessKey
= typeof accessKey
=== 'string' ? OO
.ui
.resolveMsg( accessKey
) : null;
3538 if ( this.accessKey
!== accessKey
) {
3539 if ( this.$accessKeyed
) {
3540 if ( accessKey
!== null ) {
3541 this.$accessKeyed
.attr( 'accesskey', accessKey
);
3543 this.$accessKeyed
.removeAttr( 'accesskey' );
3546 this.accessKey
= accessKey
;
3548 // Only if this is a TitledElement
3549 if ( this.updateTitle
) {
3560 * @return {string} accessKey string
3562 OO
.ui
.mixin
.AccessKeyedElement
.prototype.getAccessKey = function () {
3563 return this.accessKey
;
3567 * Add information about the access key to the element's tooltip label.
3568 * (This is only public for hacky usage in FieldLayout.)
3570 * @param {string} title Tooltip label for `title` attribute
3573 OO
.ui
.mixin
.AccessKeyedElement
.prototype.formatTitleWithAccessKey = function ( title
) {
3576 if ( !this.$accessKeyed
) {
3577 // Not initialized yet; the constructor will call updateTitle() which will rerun this function
3580 // Use jquery.accessKeyLabel if available to show modifiers, otherwise just display the single key
3581 if ( $.fn
.updateTooltipAccessKeys
&& $.fn
.updateTooltipAccessKeys
.getAccessKeyLabel
) {
3582 accessKey
= $.fn
.updateTooltipAccessKeys
.getAccessKeyLabel( this.$accessKeyed
[ 0 ] );
3584 accessKey
= this.getAccessKey();
3587 title
+= ' [' + accessKey
+ ']';
3593 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
3594 * feels, and functionality can be customized via the class’s configuration options
3595 * and methods. Please see the [OOUI documentation on MediaWiki] [1] for more information
3598 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches
3601 * // A button widget
3602 * var button = new OO.ui.ButtonWidget( {
3603 * label: 'Button with Icon',
3605 * iconTitle: 'Remove'
3607 * $( 'body' ).append( button.$element );
3609 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
3612 * @extends OO.ui.Widget
3613 * @mixins OO.ui.mixin.ButtonElement
3614 * @mixins OO.ui.mixin.IconElement
3615 * @mixins OO.ui.mixin.IndicatorElement
3616 * @mixins OO.ui.mixin.LabelElement
3617 * @mixins OO.ui.mixin.TitledElement
3618 * @mixins OO.ui.mixin.FlaggedElement
3619 * @mixins OO.ui.mixin.TabIndexedElement
3620 * @mixins OO.ui.mixin.AccessKeyedElement
3623 * @param {Object} [config] Configuration options
3624 * @cfg {boolean} [active=false] Whether button should be shown as active
3625 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
3626 * @cfg {string} [target] The frame or window in which to open the hyperlink.
3627 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
3629 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
3630 // Configuration initialization
3631 config
= config
|| {};
3633 // Parent constructor
3634 OO
.ui
.ButtonWidget
.parent
.call( this, config
);
3636 // Mixin constructors
3637 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
3638 OO
.ui
.mixin
.IconElement
.call( this, config
);
3639 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
3640 OO
.ui
.mixin
.LabelElement
.call( this, config
);
3641 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
3642 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
3643 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
3644 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$button
} ) );
3649 this.noFollow
= false;
3652 this.connect( this, { disable
: 'onDisable' } );
3655 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
3657 .addClass( 'oo-ui-buttonWidget' )
3658 .append( this.$button
);
3659 this.setActive( config
.active
);
3660 this.setHref( config
.href
);
3661 this.setTarget( config
.target
);
3662 this.setNoFollow( config
.noFollow
);
3667 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
3668 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
3669 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IconElement
);
3670 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
3671 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.LabelElement
);
3672 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TitledElement
);
3673 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
3674 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
3675 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
3677 /* Static Properties */
3683 OO
.ui
.ButtonWidget
.static.cancelButtonMouseDownEvents
= false;
3689 OO
.ui
.ButtonWidget
.static.tagName
= 'span';
3694 * Get hyperlink location.
3696 * @return {string} Hyperlink location
3698 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
3703 * Get hyperlink target.
3705 * @return {string} Hyperlink target
3707 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
3712 * Get search engine traversal hint.
3714 * @return {boolean} Whether search engines should avoid traversing this hyperlink
3716 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
3717 return this.noFollow
;
3721 * Set hyperlink location.
3723 * @param {string|null} href Hyperlink location, null to remove
3725 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
3726 href
= typeof href
=== 'string' ? href
: null;
3727 if ( href
!== null && !OO
.ui
.isSafeUrl( href
) ) {
3731 if ( href
!== this.href
) {
3740 * Update the `href` attribute, in case of changes to href or
3746 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
3747 if ( this.href
!== null && !this.isDisabled() ) {
3748 this.$button
.attr( 'href', this.href
);
3750 this.$button
.removeAttr( 'href' );
3757 * Handle disable events.
3760 * @param {boolean} disabled Element is disabled
3762 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
3767 * Set hyperlink target.
3769 * @param {string|null} target Hyperlink target, null to remove
3771 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
3772 target
= typeof target
=== 'string' ? target
: null;
3774 if ( target
!== this.target
) {
3775 this.target
= target
;
3776 if ( target
!== null ) {
3777 this.$button
.attr( 'target', target
);
3779 this.$button
.removeAttr( 'target' );
3787 * Set search engine traversal hint.
3789 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
3791 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
3792 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
3794 if ( noFollow
!== this.noFollow
) {
3795 this.noFollow
= noFollow
;
3797 this.$button
.attr( 'rel', 'nofollow' );
3799 this.$button
.removeAttr( 'rel' );
3806 // Override method visibility hints from ButtonElement
3817 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
3818 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
3819 * removed, and cleared from the group.
3822 * // Example: A ButtonGroupWidget with two buttons
3823 * var button1 = new OO.ui.PopupButtonWidget( {
3824 * label: 'Select a category',
3827 * $content: $( '<p>List of categories...</p>' ),
3832 * var button2 = new OO.ui.ButtonWidget( {
3835 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
3836 * items: [button1, button2]
3838 * $( 'body' ).append( buttonGroup.$element );
3841 * @extends OO.ui.Widget
3842 * @mixins OO.ui.mixin.GroupElement
3845 * @param {Object} [config] Configuration options
3846 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
3848 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
3849 // Configuration initialization
3850 config
= config
|| {};
3852 // Parent constructor
3853 OO
.ui
.ButtonGroupWidget
.parent
.call( this, config
);
3855 // Mixin constructors
3856 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
3859 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
3860 if ( Array
.isArray( config
.items
) ) {
3861 this.addItems( config
.items
);
3867 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
3868 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.GroupElement
);
3870 /* Static Properties */
3876 OO
.ui
.ButtonGroupWidget
.static.tagName
= 'span';
3885 OO
.ui
.ButtonGroupWidget
.prototype.focus = function () {
3886 if ( !this.isDisabled() ) {
3887 if ( this.items
[ 0 ] ) {
3888 this.items
[ 0 ].focus();
3897 OO
.ui
.ButtonGroupWidget
.prototype.simulateLabelClick = function () {
3902 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
3903 * which creates a label that identifies the icon’s function. See the [OOUI documentation on MediaWiki] [1]
3904 * for a list of icons included in the library.
3907 * // An icon widget with a label
3908 * var myIcon = new OO.ui.IconWidget( {
3912 * // Create a label.
3913 * var iconLabel = new OO.ui.LabelWidget( {
3916 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
3918 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Icons
3921 * @extends OO.ui.Widget
3922 * @mixins OO.ui.mixin.IconElement
3923 * @mixins OO.ui.mixin.TitledElement
3924 * @mixins OO.ui.mixin.FlaggedElement
3927 * @param {Object} [config] Configuration options
3929 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
3930 // Configuration initialization
3931 config
= config
|| {};
3933 // Parent constructor
3934 OO
.ui
.IconWidget
.parent
.call( this, config
);
3936 // Mixin constructors
3937 OO
.ui
.mixin
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
3938 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
3939 OO
.ui
.mixin
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
3942 this.$element
.addClass( 'oo-ui-iconWidget' );
3947 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
3948 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.IconElement
);
3949 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.TitledElement
);
3950 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.FlaggedElement
);
3952 /* Static Properties */
3958 OO
.ui
.IconWidget
.static.tagName
= 'span';
3961 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
3962 * attention to the status of an item or to clarify the function within a control. For a list of
3963 * indicators included in the library, please see the [OOUI documentation on MediaWiki][1].
3966 * // Example of an indicator widget
3967 * var indicator1 = new OO.ui.IndicatorWidget( {
3968 * indicator: 'required'
3971 * // Create a fieldset layout to add a label
3972 * var fieldset = new OO.ui.FieldsetLayout();
3973 * fieldset.addItems( [
3974 * new OO.ui.FieldLayout( indicator1, { label: 'A required indicator:' } )
3976 * $( 'body' ).append( fieldset.$element );
3978 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3981 * @extends OO.ui.Widget
3982 * @mixins OO.ui.mixin.IndicatorElement
3983 * @mixins OO.ui.mixin.TitledElement
3986 * @param {Object} [config] Configuration options
3988 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
3989 // Configuration initialization
3990 config
= config
|| {};
3992 // Parent constructor
3993 OO
.ui
.IndicatorWidget
.parent
.call( this, config
);
3995 // Mixin constructors
3996 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
3997 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
4000 this.$element
.addClass( 'oo-ui-indicatorWidget' );
4005 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
4006 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.IndicatorElement
);
4007 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.TitledElement
);
4009 /* Static Properties */
4015 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
4018 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
4019 * be configured with a `label` option that is set to a string, a label node, or a function:
4021 * - String: a plaintext string
4022 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
4023 * label that includes a link or special styling, such as a gray color or additional graphical elements.
4024 * - Function: a function that will produce a string in the future. Functions are used
4025 * in cases where the value of the label is not currently defined.
4027 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
4028 * will come into focus when the label is clicked.
4031 * // Examples of LabelWidgets
4032 * var label1 = new OO.ui.LabelWidget( {
4033 * label: 'plaintext label'
4035 * var label2 = new OO.ui.LabelWidget( {
4036 * label: $( '<a href="default.html">jQuery label</a>' )
4038 * // Create a fieldset layout with fields for each example
4039 * var fieldset = new OO.ui.FieldsetLayout();
4040 * fieldset.addItems( [
4041 * new OO.ui.FieldLayout( label1 ),
4042 * new OO.ui.FieldLayout( label2 )
4044 * $( 'body' ).append( fieldset.$element );
4047 * @extends OO.ui.Widget
4048 * @mixins OO.ui.mixin.LabelElement
4049 * @mixins OO.ui.mixin.TitledElement
4052 * @param {Object} [config] Configuration options
4053 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
4054 * Clicking the label will focus the specified input field.
4056 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
4057 // Configuration initialization
4058 config
= config
|| {};
4060 // Parent constructor
4061 OO
.ui
.LabelWidget
.parent
.call( this, config
);
4063 // Mixin constructors
4064 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
4065 OO
.ui
.mixin
.TitledElement
.call( this, config
);
4068 this.input
= config
.input
;
4072 if ( this.input
.getInputId() ) {
4073 this.$element
.attr( 'for', this.input
.getInputId() );
4075 this.$label
.on( 'click', function () {
4076 this.input
.simulateLabelClick();
4080 this.$element
.addClass( 'oo-ui-labelWidget' );
4085 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
4086 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.LabelElement
);
4087 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.TitledElement
);
4089 /* Static Properties */
4095 OO
.ui
.LabelWidget
.static.tagName
= 'label';
4098 * PendingElement is a mixin that is used to create elements that notify users that something is happening
4099 * and that they should wait before proceeding. The pending state is visually represented with a pending
4100 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
4101 * field of a {@link OO.ui.TextInputWidget text input widget}.
4103 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
4104 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
4105 * in process dialogs.
4108 * function MessageDialog( config ) {
4109 * MessageDialog.parent.call( this, config );
4111 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
4113 * MessageDialog.static.name = 'myMessageDialog';
4114 * MessageDialog.static.actions = [
4115 * { action: 'save', label: 'Done', flags: 'primary' },
4116 * { label: 'Cancel', flags: 'safe' }
4119 * MessageDialog.prototype.initialize = function () {
4120 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
4121 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
4122 * 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>' );
4123 * this.$body.append( this.content.$element );
4125 * MessageDialog.prototype.getBodyHeight = function () {
4128 * MessageDialog.prototype.getActionProcess = function ( action ) {
4129 * var dialog = this;
4130 * if ( action === 'save' ) {
4131 * dialog.getActions().get({actions: 'save'})[0].pushPending();
4132 * return new OO.ui.Process()
4134 * .next( function () {
4135 * dialog.getActions().get({actions: 'save'})[0].popPending();
4138 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
4141 * var windowManager = new OO.ui.WindowManager();
4142 * $( 'body' ).append( windowManager.$element );
4144 * var dialog = new MessageDialog();
4145 * windowManager.addWindows( [ dialog ] );
4146 * windowManager.openWindow( dialog );
4152 * @param {Object} [config] Configuration options
4153 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
4155 OO
.ui
.mixin
.PendingElement
= function OoUiMixinPendingElement( config
) {
4156 // Configuration initialization
4157 config
= config
|| {};
4161 this.$pending
= null;
4164 this.setPendingElement( config
.$pending
|| this.$element
);
4169 OO
.initClass( OO
.ui
.mixin
.PendingElement
);
4174 * Set the pending element (and clean up any existing one).
4176 * @param {jQuery} $pending The element to set to pending.
4178 OO
.ui
.mixin
.PendingElement
.prototype.setPendingElement = function ( $pending
) {
4179 if ( this.$pending
) {
4180 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
4183 this.$pending
= $pending
;
4184 if ( this.pending
> 0 ) {
4185 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
4190 * Check if an element is pending.
4192 * @return {boolean} Element is pending
4194 OO
.ui
.mixin
.PendingElement
.prototype.isPending = function () {
4195 return !!this.pending
;
4199 * Increase the pending counter. The pending state will remain active until the counter is zero
4200 * (i.e., the number of calls to #pushPending and #popPending is the same).
4204 OO
.ui
.mixin
.PendingElement
.prototype.pushPending = function () {
4205 if ( this.pending
=== 0 ) {
4206 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
4207 this.updateThemeClasses();
4215 * Decrease the pending counter. The pending state will remain active until the counter is zero
4216 * (i.e., the number of calls to #pushPending and #popPending is the same).
4220 OO
.ui
.mixin
.PendingElement
.prototype.popPending = function () {
4221 if ( this.pending
=== 1 ) {
4222 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
4223 this.updateThemeClasses();
4225 this.pending
= Math
.max( 0, this.pending
- 1 );
4231 * Element that will stick adjacent to a specified container, even when it is inserted elsewhere
4232 * in the document (for example, in an OO.ui.Window's $overlay).
4234 * The elements's position is automatically calculated and maintained when window is resized or the
4235 * page is scrolled. If you reposition the container manually, you have to call #position to make
4236 * sure the element is still placed correctly.
4238 * As positioning is only possible when both the element and the container are attached to the DOM
4239 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
4240 * the #toggle method to display a floating popup, for example.
4246 * @param {Object} [config] Configuration options
4247 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
4248 * @cfg {jQuery} [$floatableContainer] Node to position adjacent to
4249 * @cfg {string} [verticalPosition='below'] Where to position $floatable vertically:
4250 * 'below': Directly below $floatableContainer, aligning f's top edge with fC's bottom edge
4251 * 'above': Directly above $floatableContainer, aligning f's bottom edge with fC's top edge
4252 * 'top': Align the top edge with $floatableContainer's top edge
4253 * 'bottom': Align the bottom edge with $floatableContainer's bottom edge
4254 * 'center': Vertically align the center with $floatableContainer's center
4255 * @cfg {string} [horizontalPosition='start'] Where to position $floatable horizontally:
4256 * 'before': Directly before $floatableContainer, aligning f's end edge with fC's start edge
4257 * 'after': Directly after $floatableContainer, algining f's start edge with fC's end edge
4258 * 'start': Align the start (left in LTR, right in RTL) edge with $floatableContainer's start edge
4259 * 'end': Align the end (right in LTR, left in RTL) edge with $floatableContainer's end edge
4260 * 'center': Horizontally align the center with $floatableContainer's center
4261 * @cfg {boolean} [hideWhenOutOfView=true] Whether to hide the floatable element if the container
4264 OO
.ui
.mixin
.FloatableElement
= function OoUiMixinFloatableElement( config
) {
4265 // Configuration initialization
4266 config
= config
|| {};
4269 this.$floatable
= null;
4270 this.$floatableContainer
= null;
4271 this.$floatableWindow
= null;
4272 this.$floatableClosestScrollable
= null;
4273 this.floatableOutOfView
= false;
4274 this.onFloatableScrollHandler
= this.position
.bind( this );
4275 this.onFloatableWindowResizeHandler
= this.position
.bind( this );
4278 this.setFloatableContainer( config
.$floatableContainer
);
4279 this.setFloatableElement( config
.$floatable
|| this.$element
);
4280 this.setVerticalPosition( config
.verticalPosition
|| 'below' );
4281 this.setHorizontalPosition( config
.horizontalPosition
|| 'start' );
4282 this.hideWhenOutOfView
= config
.hideWhenOutOfView
=== undefined ? true : !!config
.hideWhenOutOfView
;
4288 * Set floatable element.
4290 * If an element is already set, it will be cleaned up before setting up the new element.
4292 * @param {jQuery} $floatable Element to make floatable
4294 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableElement = function ( $floatable
) {
4295 if ( this.$floatable
) {
4296 this.$floatable
.removeClass( 'oo-ui-floatableElement-floatable' );
4297 this.$floatable
.css( { left
: '', top
: '' } );
4300 this.$floatable
= $floatable
.addClass( 'oo-ui-floatableElement-floatable' );
4305 * Set floatable container.
4307 * The element will be positioned relative to the specified container.
4309 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
4311 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableContainer = function ( $floatableContainer
) {
4312 this.$floatableContainer
= $floatableContainer
;
4313 if ( this.$floatable
) {
4319 * Change how the element is positioned vertically.
4321 * @param {string} position 'below', 'above', 'top', 'bottom' or 'center'
4323 OO
.ui
.mixin
.FloatableElement
.prototype.setVerticalPosition = function ( position
) {
4324 if ( [ 'below', 'above', 'top', 'bottom', 'center' ].indexOf( position
) === -1 ) {
4325 throw new Error( 'Invalid value for vertical position: ' + position
);
4327 if ( this.verticalPosition
!== position
) {
4328 this.verticalPosition
= position
;
4329 if ( this.$floatable
) {
4336 * Change how the element is positioned horizontally.
4338 * @param {string} position 'before', 'after', 'start', 'end' or 'center'
4340 OO
.ui
.mixin
.FloatableElement
.prototype.setHorizontalPosition = function ( position
) {
4341 if ( [ 'before', 'after', 'start', 'end', 'center' ].indexOf( position
) === -1 ) {
4342 throw new Error( 'Invalid value for horizontal position: ' + position
);
4344 if ( this.horizontalPosition
!== position
) {
4345 this.horizontalPosition
= position
;
4346 if ( this.$floatable
) {
4353 * Toggle positioning.
4355 * Do not turn positioning on until after the element is attached to the DOM and visible.
4357 * @param {boolean} [positioning] Enable positioning, omit to toggle
4360 OO
.ui
.mixin
.FloatableElement
.prototype.togglePositioning = function ( positioning
) {
4361 var closestScrollableOfContainer
;
4363 if ( !this.$floatable
|| !this.$floatableContainer
) {
4367 positioning
= positioning
=== undefined ? !this.positioning
: !!positioning
;
4369 if ( positioning
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
4370 OO
.ui
.warnDeprecation( 'FloatableElement#togglePositioning: Before calling this method, the element must be attached to the DOM.' );
4371 this.warnedUnattached
= true;
4374 if ( this.positioning
!== positioning
) {
4375 this.positioning
= positioning
;
4377 this.needsCustomPosition
=
4378 this.verticalPostion
!== 'below' ||
4379 this.horizontalPosition
!== 'start' ||
4380 !OO
.ui
.contains( this.$floatableContainer
[ 0 ], this.$floatable
[ 0 ] );
4382 closestScrollableOfContainer
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatableContainer
[ 0 ] );
4383 // If the scrollable is the root, we have to listen to scroll events
4384 // on the window because of browser inconsistencies.
4385 if ( $( closestScrollableOfContainer
).is( 'html, body' ) ) {
4386 closestScrollableOfContainer
= OO
.ui
.Element
.static.getWindow( closestScrollableOfContainer
);
4389 if ( positioning
) {
4390 this.$floatableWindow
= $( this.getElementWindow() );
4391 this.$floatableWindow
.on( 'resize', this.onFloatableWindowResizeHandler
);
4393 this.$floatableClosestScrollable
= $( closestScrollableOfContainer
);
4394 this.$floatableClosestScrollable
.on( 'scroll', this.onFloatableScrollHandler
);
4396 // Initial position after visible
4399 if ( this.$floatableWindow
) {
4400 this.$floatableWindow
.off( 'resize', this.onFloatableWindowResizeHandler
);
4401 this.$floatableWindow
= null;
4404 if ( this.$floatableClosestScrollable
) {
4405 this.$floatableClosestScrollable
.off( 'scroll', this.onFloatableScrollHandler
);
4406 this.$floatableClosestScrollable
= null;
4409 this.$floatable
.css( { left
: '', right
: '', top
: '' } );
4417 * Check whether the bottom edge of the given element is within the viewport of the given container.
4420 * @param {jQuery} $element
4421 * @param {jQuery} $container
4424 OO
.ui
.mixin
.FloatableElement
.prototype.isElementInViewport = function ( $element
, $container
) {
4425 var elemRect
, contRect
, topEdgeInBounds
, bottomEdgeInBounds
, leftEdgeInBounds
, rightEdgeInBounds
,
4426 startEdgeInBounds
, endEdgeInBounds
, viewportSpacing
,
4427 direction
= $element
.css( 'direction' );
4429 elemRect
= $element
[ 0 ].getBoundingClientRect();
4430 if ( $container
[ 0 ] === window
) {
4431 viewportSpacing
= OO
.ui
.getViewportSpacing();
4435 right
: document
.documentElement
.clientWidth
,
4436 bottom
: document
.documentElement
.clientHeight
4438 contRect
.top
+= viewportSpacing
.top
;
4439 contRect
.left
+= viewportSpacing
.left
;
4440 contRect
.right
-= viewportSpacing
.right
;
4441 contRect
.bottom
-= viewportSpacing
.bottom
;
4443 contRect
= $container
[ 0 ].getBoundingClientRect();
4446 topEdgeInBounds
= elemRect
.top
>= contRect
.top
&& elemRect
.top
<= contRect
.bottom
;
4447 bottomEdgeInBounds
= elemRect
.bottom
>= contRect
.top
&& elemRect
.bottom
<= contRect
.bottom
;
4448 leftEdgeInBounds
= elemRect
.left
>= contRect
.left
&& elemRect
.left
<= contRect
.right
;
4449 rightEdgeInBounds
= elemRect
.right
>= contRect
.left
&& elemRect
.right
<= contRect
.right
;
4450 if ( direction
=== 'rtl' ) {
4451 startEdgeInBounds
= rightEdgeInBounds
;
4452 endEdgeInBounds
= leftEdgeInBounds
;
4454 startEdgeInBounds
= leftEdgeInBounds
;
4455 endEdgeInBounds
= rightEdgeInBounds
;
4458 if ( this.verticalPosition
=== 'below' && !bottomEdgeInBounds
) {
4461 if ( this.verticalPosition
=== 'above' && !topEdgeInBounds
) {
4464 if ( this.horizontalPosition
=== 'before' && !startEdgeInBounds
) {
4467 if ( this.horizontalPosition
=== 'after' && !endEdgeInBounds
) {
4471 // The other positioning values are all about being inside the container,
4472 // so in those cases all we care about is that any part of the container is visible.
4473 return elemRect
.top
<= contRect
.bottom
&& elemRect
.bottom
>= contRect
.top
&&
4474 elemRect
.left
<= contRect
.right
&& elemRect
.right
>= contRect
.left
;
4478 * Check if the floatable is hidden to the user because it was offscreen.
4480 * @return {boolean} Floatable is out of view
4482 OO
.ui
.mixin
.FloatableElement
.prototype.isFloatableOutOfView = function () {
4483 return this.floatableOutOfView
;
4487 * Position the floatable below its container.
4489 * This should only be done when both of them are attached to the DOM and visible.
4493 OO
.ui
.mixin
.FloatableElement
.prototype.position = function () {
4494 if ( !this.positioning
) {
4499 // To continue, some things need to be true:
4500 // The element must actually be in the DOM
4501 this.isElementAttached() && (
4502 // The closest scrollable is the current window
4503 this.$floatableClosestScrollable
[ 0 ] === this.getElementWindow() ||
4504 // OR is an element in the element's DOM
4505 $.contains( this.getElementDocument(), this.$floatableClosestScrollable
[ 0 ] )
4508 // Abort early if important parts of the widget are no longer attached to the DOM
4512 this.floatableOutOfView
= this.hideWhenOutOfView
&& !this.isElementInViewport( this.$floatableContainer
, this.$floatableClosestScrollable
);
4513 if ( this.floatableOutOfView
) {
4514 this.$floatable
.addClass( 'oo-ui-element-hidden' );
4517 this.$floatable
.removeClass( 'oo-ui-element-hidden' );
4520 if ( !this.needsCustomPosition
) {
4524 this.$floatable
.css( this.computePosition() );
4526 // We updated the position, so re-evaluate the clipping state.
4527 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
4528 // will not notice the need to update itself.)
4529 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
4530 // it not listen to the right events in the right places?
4539 * Compute how #$floatable should be positioned based on the position of #$floatableContainer
4540 * and the positioning settings. This is a helper for #position that shouldn't be called directly,
4541 * but may be overridden by subclasses if they want to change or add to the positioning logic.
4543 * @return {Object} New position to apply with .css(). Keys are 'top', 'left', 'bottom' and 'right'.
4545 OO
.ui
.mixin
.FloatableElement
.prototype.computePosition = function () {
4546 var isBody
, scrollableX
, scrollableY
, containerPos
,
4547 horizScrollbarHeight
, vertScrollbarWidth
, scrollTop
, scrollLeft
,
4548 newPos
= { top
: '', left
: '', bottom
: '', right
: '' },
4549 direction
= this.$floatableContainer
.css( 'direction' ),
4550 $offsetParent
= this.$floatable
.offsetParent();
4552 if ( $offsetParent
.is( 'html' ) ) {
4553 // The innerHeight/Width and clientHeight/Width calculations don't work well on the
4554 // <html> element, but they do work on the <body>
4555 $offsetParent
= $( $offsetParent
[ 0 ].ownerDocument
.body
);
4557 isBody
= $offsetParent
.is( 'body' );
4558 scrollableX
= $offsetParent
.css( 'overflow-x' ) === 'scroll' || $offsetParent
.css( 'overflow-x' ) === 'auto';
4559 scrollableY
= $offsetParent
.css( 'overflow-y' ) === 'scroll' || $offsetParent
.css( 'overflow-y' ) === 'auto';
4561 vertScrollbarWidth
= $offsetParent
.innerWidth() - $offsetParent
.prop( 'clientWidth' );
4562 horizScrollbarHeight
= $offsetParent
.innerHeight() - $offsetParent
.prop( 'clientHeight' );
4563 // We don't need to compute and add scrollTop and scrollLeft if the scrollable container is the body,
4564 // or if it isn't scrollable
4565 scrollTop
= scrollableY
&& !isBody
? $offsetParent
.scrollTop() : 0;
4566 scrollLeft
= scrollableX
&& !isBody
? OO
.ui
.Element
.static.getScrollLeft( $offsetParent
[ 0 ] ) : 0;
4568 // Avoid passing the <body> to getRelativePosition(), because it won't return what we expect
4569 // if the <body> has a margin
4570 containerPos
= isBody
?
4571 this.$floatableContainer
.offset() :
4572 OO
.ui
.Element
.static.getRelativePosition( this.$floatableContainer
, $offsetParent
);
4573 containerPos
.bottom
= containerPos
.top
+ this.$floatableContainer
.outerHeight();
4574 containerPos
.right
= containerPos
.left
+ this.$floatableContainer
.outerWidth();
4575 containerPos
.start
= direction
=== 'rtl' ? containerPos
.right
: containerPos
.left
;
4576 containerPos
.end
= direction
=== 'rtl' ? containerPos
.left
: containerPos
.right
;
4578 if ( this.verticalPosition
=== 'below' ) {
4579 newPos
.top
= containerPos
.bottom
;
4580 } else if ( this.verticalPosition
=== 'above' ) {
4581 newPos
.bottom
= $offsetParent
.outerHeight() - containerPos
.top
;
4582 } else if ( this.verticalPosition
=== 'top' ) {
4583 newPos
.top
= containerPos
.top
;
4584 } else if ( this.verticalPosition
=== 'bottom' ) {
4585 newPos
.bottom
= $offsetParent
.outerHeight() - containerPos
.bottom
;
4586 } else if ( this.verticalPosition
=== 'center' ) {
4587 newPos
.top
= containerPos
.top
+
4588 ( this.$floatableContainer
.height() - this.$floatable
.height() ) / 2;
4591 if ( this.horizontalPosition
=== 'before' ) {
4592 newPos
.end
= containerPos
.start
;
4593 } else if ( this.horizontalPosition
=== 'after' ) {
4594 newPos
.start
= containerPos
.end
;
4595 } else if ( this.horizontalPosition
=== 'start' ) {
4596 newPos
.start
= containerPos
.start
;
4597 } else if ( this.horizontalPosition
=== 'end' ) {
4598 newPos
.end
= containerPos
.end
;
4599 } else if ( this.horizontalPosition
=== 'center' ) {
4600 newPos
.left
= containerPos
.left
+
4601 ( this.$floatableContainer
.width() - this.$floatable
.width() ) / 2;
4604 if ( newPos
.start
!== undefined ) {
4605 if ( direction
=== 'rtl' ) {
4606 newPos
.right
= ( isBody
? $( $offsetParent
[ 0 ].ownerDocument
.documentElement
) : $offsetParent
).outerWidth() - newPos
.start
;
4608 newPos
.left
= newPos
.start
;
4610 delete newPos
.start
;
4612 if ( newPos
.end
!== undefined ) {
4613 if ( direction
=== 'rtl' ) {
4614 newPos
.left
= newPos
.end
;
4616 newPos
.right
= ( isBody
? $( $offsetParent
[ 0 ].ownerDocument
.documentElement
) : $offsetParent
).outerWidth() - newPos
.end
;
4621 // Account for scroll position
4622 if ( newPos
.top
!== '' ) {
4623 newPos
.top
+= scrollTop
;
4625 if ( newPos
.bottom
!== '' ) {
4626 newPos
.bottom
-= scrollTop
;
4628 if ( newPos
.left
!== '' ) {
4629 newPos
.left
+= scrollLeft
;
4631 if ( newPos
.right
!== '' ) {
4632 newPos
.right
-= scrollLeft
;
4635 // Account for scrollbar gutter
4636 if ( newPos
.bottom
!== '' ) {
4637 newPos
.bottom
-= horizScrollbarHeight
;
4639 if ( direction
=== 'rtl' ) {
4640 if ( newPos
.left
!== '' ) {
4641 newPos
.left
-= vertScrollbarWidth
;
4644 if ( newPos
.right
!== '' ) {
4645 newPos
.right
-= vertScrollbarWidth
;
4653 * Element that can be automatically clipped to visible boundaries.
4655 * Whenever the element's natural height changes, you have to call
4656 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
4657 * clipping correctly.
4659 * The dimensions of #$clippableContainer will be compared to the boundaries of the
4660 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
4661 * then #$clippable will be given a fixed reduced height and/or width and will be made
4662 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
4663 * but you can build a static footer by setting #$clippableContainer to an element that contains
4664 * #$clippable and the footer.
4670 * @param {Object} [config] Configuration options
4671 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
4672 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
4673 * omit to use #$clippable
4675 OO
.ui
.mixin
.ClippableElement
= function OoUiMixinClippableElement( config
) {
4676 // Configuration initialization
4677 config
= config
|| {};
4680 this.$clippable
= null;
4681 this.$clippableContainer
= null;
4682 this.clipping
= false;
4683 this.clippedHorizontally
= false;
4684 this.clippedVertically
= false;
4685 this.$clippableScrollableContainer
= null;
4686 this.$clippableScroller
= null;
4687 this.$clippableWindow
= null;
4688 this.idealWidth
= null;
4689 this.idealHeight
= null;
4690 this.onClippableScrollHandler
= this.clip
.bind( this );
4691 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
4694 if ( config
.$clippableContainer
) {
4695 this.setClippableContainer( config
.$clippableContainer
);
4697 this.setClippableElement( config
.$clippable
|| this.$element
);
4703 * Set clippable element.
4705 * If an element is already set, it will be cleaned up before setting up the new element.
4707 * @param {jQuery} $clippable Element to make clippable
4709 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
4710 if ( this.$clippable
) {
4711 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
4712 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
4713 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4716 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
4721 * Set clippable container.
4723 * This is the container that will be measured when deciding whether to clip. When clipping,
4724 * #$clippable will be resized in order to keep the clippable container fully visible.
4726 * If the clippable container is unset, #$clippable will be used.
4728 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
4730 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableContainer = function ( $clippableContainer
) {
4731 this.$clippableContainer
= $clippableContainer
;
4732 if ( this.$clippable
) {
4740 * Do not turn clipping on until after the element is attached to the DOM and visible.
4742 * @param {boolean} [clipping] Enable clipping, omit to toggle
4745 OO
.ui
.mixin
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
4746 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
4748 if ( clipping
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
4749 OO
.ui
.warnDeprecation( 'ClippableElement#toggleClipping: Before calling this method, the element must be attached to the DOM.' );
4750 this.warnedUnattached
= true;
4753 if ( this.clipping
!== clipping
) {
4754 this.clipping
= clipping
;
4756 this.$clippableScrollableContainer
= $( this.getClosestScrollableElementContainer() );
4757 // If the clippable container is the root, we have to listen to scroll events and check
4758 // jQuery.scrollTop on the window because of browser inconsistencies
4759 this.$clippableScroller
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
4760 $( OO
.ui
.Element
.static.getWindow( this.$clippableScrollableContainer
) ) :
4761 this.$clippableScrollableContainer
;
4762 this.$clippableScroller
.on( 'scroll', this.onClippableScrollHandler
);
4763 this.$clippableWindow
= $( this.getElementWindow() )
4764 .on( 'resize', this.onClippableWindowResizeHandler
);
4765 // Initial clip after visible
4768 this.$clippable
.css( {
4776 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4778 this.$clippableScrollableContainer
= null;
4779 this.$clippableScroller
.off( 'scroll', this.onClippableScrollHandler
);
4780 this.$clippableScroller
= null;
4781 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
4782 this.$clippableWindow
= null;
4790 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
4792 * @return {boolean} Element will be clipped to the visible area
4794 OO
.ui
.mixin
.ClippableElement
.prototype.isClipping = function () {
4795 return this.clipping
;
4799 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
4801 * @return {boolean} Part of the element is being clipped
4803 OO
.ui
.mixin
.ClippableElement
.prototype.isClipped = function () {
4804 return this.clippedHorizontally
|| this.clippedVertically
;
4808 * Check if the right of the element is being clipped by the nearest scrollable container.
4810 * @return {boolean} Part of the element is being clipped
4812 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedHorizontally = function () {
4813 return this.clippedHorizontally
;
4817 * Check if the bottom of the element is being clipped by the nearest scrollable container.
4819 * @return {boolean} Part of the element is being clipped
4821 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedVertically = function () {
4822 return this.clippedVertically
;
4826 * Set the ideal size. These are the dimensions #$clippable will have when it's not being clipped.
4828 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
4829 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
4831 OO
.ui
.mixin
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
4832 this.idealWidth
= width
;
4833 this.idealHeight
= height
;
4835 if ( !this.clipping
) {
4836 // Update dimensions
4837 this.$clippable
.css( { width
: width
, height
: height
} );
4839 // While clipping, idealWidth and idealHeight are not considered
4843 * Return the side of the clippable on which it is "anchored" (aligned to something else).
4844 * ClippableElement will clip the opposite side when reducing element's width.
4846 * Classes that mix in ClippableElement should override this to return 'right' if their
4847 * clippable is absolutely positioned and using 'right: Npx' (and not using 'left').
4848 * If your class also mixes in FloatableElement, this is handled automatically.
4850 * (This can't be guessed from the actual CSS because the computed values for 'left'/'right' are
4851 * always in pixels, even if they were unset or set to 'auto'.)
4853 * When in doubt, 'left' (or 'right' in RTL) is a sane fallback.
4855 * @return {string} 'left' or 'right'
4857 OO
.ui
.mixin
.ClippableElement
.prototype.getHorizontalAnchorEdge = function () {
4858 if ( this.computePosition
&& this.positioning
&& this.computePosition().right
!== '' ) {
4865 * Return the side of the clippable on which it is "anchored" (aligned to something else).
4866 * ClippableElement will clip the opposite side when reducing element's width.
4868 * Classes that mix in ClippableElement should override this to return 'bottom' if their
4869 * clippable is absolutely positioned and using 'bottom: Npx' (and not using 'top').
4870 * If your class also mixes in FloatableElement, this is handled automatically.
4872 * (This can't be guessed from the actual CSS because the computed values for 'left'/'right' are
4873 * always in pixels, even if they were unset or set to 'auto'.)
4875 * When in doubt, 'top' is a sane fallback.
4877 * @return {string} 'top' or 'bottom'
4879 OO
.ui
.mixin
.ClippableElement
.prototype.getVerticalAnchorEdge = function () {
4880 if ( this.computePosition
&& this.positioning
&& this.computePosition().bottom
!== '' ) {
4887 * Clip element to visible boundaries and allow scrolling when needed. You should call this method
4888 * when the element's natural height changes.
4890 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
4891 * overlapped by, the visible area of the nearest scrollable container.
4893 * Because calling clip() when the natural height changes isn't always possible, we also set
4894 * max-height when the element isn't being clipped. This means that if the element tries to grow
4895 * beyond the edge, something reasonable will happen before clip() is called.
4899 OO
.ui
.mixin
.ClippableElement
.prototype.clip = function () {
4900 var extraHeight
, extraWidth
, viewportSpacing
,
4901 desiredWidth
, desiredHeight
, allotedWidth
, allotedHeight
,
4902 naturalWidth
, naturalHeight
, clipWidth
, clipHeight
,
4903 $item
, itemRect
, $viewport
, viewportRect
, availableRect
,
4904 direction
, vertScrollbarWidth
, horizScrollbarHeight
,
4905 // Extra tolerance so that the sloppy code below doesn't result in results that are off
4906 // by one or two pixels. (And also so that we have space to display drop shadows.)
4907 // Chosen by fair dice roll.
4910 if ( !this.clipping
) {
4911 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
4915 function rectIntersection( a
, b
) {
4917 out
.top
= Math
.max( a
.top
, b
.top
);
4918 out
.left
= Math
.max( a
.left
, b
.left
);
4919 out
.bottom
= Math
.min( a
.bottom
, b
.bottom
);
4920 out
.right
= Math
.min( a
.right
, b
.right
);
4924 viewportSpacing
= OO
.ui
.getViewportSpacing();
4926 if ( this.$clippableScrollableContainer
.is( 'html, body' ) ) {
4927 $viewport
= $( this.$clippableScrollableContainer
[ 0 ].ownerDocument
.body
);
4928 // Dimensions of the browser window, rather than the element!
4932 right
: document
.documentElement
.clientWidth
,
4933 bottom
: document
.documentElement
.clientHeight
4935 viewportRect
.top
+= viewportSpacing
.top
;
4936 viewportRect
.left
+= viewportSpacing
.left
;
4937 viewportRect
.right
-= viewportSpacing
.right
;
4938 viewportRect
.bottom
-= viewportSpacing
.bottom
;
4940 $viewport
= this.$clippableScrollableContainer
;
4941 viewportRect
= $viewport
[ 0 ].getBoundingClientRect();
4942 // Convert into a plain object
4943 viewportRect
= $.extend( {}, viewportRect
);
4946 // Account for scrollbar gutter
4947 direction
= $viewport
.css( 'direction' );
4948 vertScrollbarWidth
= $viewport
.innerWidth() - $viewport
.prop( 'clientWidth' );
4949 horizScrollbarHeight
= $viewport
.innerHeight() - $viewport
.prop( 'clientHeight' );
4950 viewportRect
.bottom
-= horizScrollbarHeight
;
4951 if ( direction
=== 'rtl' ) {
4952 viewportRect
.left
+= vertScrollbarWidth
;
4954 viewportRect
.right
-= vertScrollbarWidth
;
4957 // Add arbitrary tolerance
4958 viewportRect
.top
+= buffer
;
4959 viewportRect
.left
+= buffer
;
4960 viewportRect
.right
-= buffer
;
4961 viewportRect
.bottom
-= buffer
;
4963 $item
= this.$clippableContainer
|| this.$clippable
;
4965 extraHeight
= $item
.outerHeight() - this.$clippable
.outerHeight();
4966 extraWidth
= $item
.outerWidth() - this.$clippable
.outerWidth();
4968 itemRect
= $item
[ 0 ].getBoundingClientRect();
4969 // Convert into a plain object
4970 itemRect
= $.extend( {}, itemRect
);
4972 // Item might already be clipped, so we can't just use its dimensions (in case we might need to
4973 // make it larger than before). Extend the rectangle to the maximum size we are allowed to take.
4974 if ( this.getHorizontalAnchorEdge() === 'right' ) {
4975 itemRect
.left
= viewportRect
.left
;
4977 itemRect
.right
= viewportRect
.right
;
4979 if ( this.getVerticalAnchorEdge() === 'bottom' ) {
4980 itemRect
.top
= viewportRect
.top
;
4982 itemRect
.bottom
= viewportRect
.bottom
;
4985 availableRect
= rectIntersection( viewportRect
, itemRect
);
4987 desiredWidth
= Math
.max( 0, availableRect
.right
- availableRect
.left
);
4988 desiredHeight
= Math
.max( 0, availableRect
.bottom
- availableRect
.top
);
4989 // It should never be desirable to exceed the dimensions of the browser viewport... right?
4990 desiredWidth
= Math
.min( desiredWidth
,
4991 document
.documentElement
.clientWidth
- viewportSpacing
.left
- viewportSpacing
.right
);
4992 desiredHeight
= Math
.min( desiredHeight
,
4993 document
.documentElement
.clientHeight
- viewportSpacing
.top
- viewportSpacing
.right
);
4994 allotedWidth
= Math
.ceil( desiredWidth
- extraWidth
);
4995 allotedHeight
= Math
.ceil( desiredHeight
- extraHeight
);
4996 naturalWidth
= this.$clippable
.prop( 'scrollWidth' );
4997 naturalHeight
= this.$clippable
.prop( 'scrollHeight' );
4998 clipWidth
= allotedWidth
< naturalWidth
;
4999 clipHeight
= allotedHeight
< naturalHeight
;
5002 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. See T157672.
5003 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
5004 this.$clippable
.css( 'overflowX', 'scroll' );
5005 void this.$clippable
[ 0 ].offsetHeight
; // Force reflow
5006 this.$clippable
.css( {
5007 width
: Math
.max( 0, allotedWidth
),
5011 this.$clippable
.css( {
5013 width
: this.idealWidth
|| '',
5014 maxWidth
: Math
.max( 0, allotedWidth
)
5018 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. See T157672.
5019 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
5020 this.$clippable
.css( 'overflowY', 'scroll' );
5021 void this.$clippable
[ 0 ].offsetHeight
; // Force reflow
5022 this.$clippable
.css( {
5023 height
: Math
.max( 0, allotedHeight
),
5027 this.$clippable
.css( {
5029 height
: this.idealHeight
|| '',
5030 maxHeight
: Math
.max( 0, allotedHeight
)
5034 // If we stopped clipping in at least one of the dimensions
5035 if ( ( this.clippedHorizontally
&& !clipWidth
) || ( this.clippedVertically
&& !clipHeight
) ) {
5036 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
5039 this.clippedHorizontally
= clipWidth
;
5040 this.clippedVertically
= clipHeight
;
5046 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
5047 * By default, each popup has an anchor that points toward its origin.
5048 * Please see the [OOUI documentation on Mediawiki] [1] for more information and examples.
5050 * Unlike most widgets, PopupWidget is initially hidden and must be shown by calling #toggle.
5053 * // A popup widget.
5054 * var popup = new OO.ui.PopupWidget( {
5055 * $content: $( '<p>Hi there!</p>' ),
5060 * $( 'body' ).append( popup.$element );
5061 * // To display the popup, toggle the visibility to 'true'.
5062 * popup.toggle( true );
5064 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups
5067 * @extends OO.ui.Widget
5068 * @mixins OO.ui.mixin.LabelElement
5069 * @mixins OO.ui.mixin.ClippableElement
5070 * @mixins OO.ui.mixin.FloatableElement
5073 * @param {Object} [config] Configuration options
5074 * @cfg {number} [width=320] Width of popup in pixels
5075 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
5076 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
5077 * @cfg {string} [position='below'] Where to position the popup relative to $floatableContainer
5078 * 'above': Put popup above $floatableContainer; anchor points down to the horizontal center
5079 * of $floatableContainer
5080 * 'below': Put popup below $floatableContainer; anchor points up to the horizontal center
5081 * of $floatableContainer
5082 * 'before': Put popup to the left (LTR) / right (RTL) of $floatableContainer; anchor points
5083 * endwards (right/left) to the vertical center of $floatableContainer
5084 * 'after': Put popup to the right (LTR) / left (RTL) of $floatableContainer; anchor points
5085 * startwards (left/right) to the vertical center of $floatableContainer
5086 * @cfg {string} [align='center'] How to align the popup to $floatableContainer
5087 * 'forwards': If position is above/below, move the popup as far endwards (right in LTR, left in RTL)
5088 * as possible while still keeping the anchor within the popup;
5089 * if position is before/after, move the popup as far downwards as possible.
5090 * 'backwards': If position is above/below, move the popup as far startwards (left in LTR, right in RTL)
5091 * as possible while still keeping the anchor within the popup;
5092 * if position in before/after, move the popup as far upwards as possible.
5093 * 'center': Horizontally (if position is above/below) or vertically (before/after) align the center
5094 * of the popup with the center of $floatableContainer.
5095 * 'force-left': Alias for 'forwards' in LTR and 'backwards' in RTL
5096 * 'force-right': Alias for 'backwards' in RTL and 'forwards' in LTR
5097 * @cfg {boolean} [autoFlip=true] Whether to automatically switch the popup's position between
5098 * 'above' and 'below', or between 'before' and 'after', if there is not enough space in the
5099 * desired direction to display the popup without clipping
5100 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
5101 * See the [OOUI docs on MediaWiki][3] for an example.
5102 * [3]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups#containerExample
5103 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
5104 * @cfg {jQuery} [$content] Content to append to the popup's body
5105 * @cfg {jQuery} [$footer] Content to append to the popup's footer
5106 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
5107 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
5108 * This config option is only relevant if #autoClose is set to `true`. See the [OOUI documentation on MediaWiki][2]
5110 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Popups#autocloseExample
5111 * @cfg {boolean} [head=false] Show a popup header that contains a #label (if specified) and close
5113 * @cfg {boolean} [padded=false] Add padding to the popup's body
5115 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
5116 // Configuration initialization
5117 config
= config
|| {};
5119 // Parent constructor
5120 OO
.ui
.PopupWidget
.parent
.call( this, config
);
5122 // Properties (must be set before ClippableElement constructor call)
5123 this.$body
= $( '<div>' );
5124 this.$popup
= $( '<div>' );
5126 // Mixin constructors
5127 OO
.ui
.mixin
.LabelElement
.call( this, config
);
5128 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, {
5129 $clippable
: this.$body
,
5130 $clippableContainer
: this.$popup
5132 OO
.ui
.mixin
.FloatableElement
.call( this, config
);
5135 this.$anchor
= $( '<div>' );
5136 // If undefined, will be computed lazily in computePosition()
5137 this.$container
= config
.$container
;
5138 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
5139 this.autoClose
= !!config
.autoClose
;
5140 this.$autoCloseIgnore
= config
.$autoCloseIgnore
;
5141 this.transitionTimeout
= null;
5142 this.anchored
= false;
5143 this.width
= config
.width
!== undefined ? config
.width
: 320;
5144 this.height
= config
.height
!== undefined ? config
.height
: null;
5145 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
5146 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
5149 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
5150 this.setAlignment( config
.align
|| 'center' );
5151 this.setPosition( config
.position
|| 'below' );
5152 this.setAutoFlip( config
.autoFlip
=== undefined || config
.autoFlip
);
5153 this.$body
.addClass( 'oo-ui-popupWidget-body' );
5154 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
5156 .addClass( 'oo-ui-popupWidget-popup' )
5157 .append( this.$body
);
5159 .addClass( 'oo-ui-popupWidget' )
5160 .append( this.$popup
, this.$anchor
);
5161 // Move content, which was added to #$element by OO.ui.Widget, to the body
5162 // FIXME This is gross, we should use '$body' or something for the config
5163 if ( config
.$content
instanceof jQuery
) {
5164 this.$body
.append( config
.$content
);
5167 if ( config
.padded
) {
5168 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
5171 if ( config
.head
) {
5172 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
5173 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
5174 this.$head
= $( '<div>' )
5175 .addClass( 'oo-ui-popupWidget-head' )
5176 .append( this.$label
, this.closeButton
.$element
);
5177 this.$popup
.prepend( this.$head
);
5180 if ( config
.$footer
) {
5181 this.$footer
= $( '<div>' )
5182 .addClass( 'oo-ui-popupWidget-footer' )
5183 .append( config
.$footer
);
5184 this.$popup
.append( this.$footer
);
5187 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
5188 // that reference properties not initialized at that time of parent class construction
5189 // TODO: Find a better way to handle post-constructor setup
5190 this.visible
= false;
5191 this.$element
.addClass( 'oo-ui-element-hidden' );
5196 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
5197 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.LabelElement
);
5198 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.ClippableElement
);
5199 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.FloatableElement
);
5206 * The popup is ready: it is visible and has been positioned and clipped.
5212 * Handles mouse down events.
5215 * @param {MouseEvent} e Mouse down event
5217 OO
.ui
.PopupWidget
.prototype.onMouseDown = function ( e
) {
5220 !OO
.ui
.contains( this.$element
.add( this.$autoCloseIgnore
).get(), e
.target
, true )
5222 this.toggle( false );
5227 * Bind mouse down listener.
5231 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
5232 // Capture clicks outside popup
5233 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler
, true );
5237 * Handles close button click events.
5241 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
5242 if ( this.isVisible() ) {
5243 this.toggle( false );
5248 * Unbind mouse down listener.
5252 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
5253 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler
, true );
5257 * Handles key down events.
5260 * @param {KeyboardEvent} e Key down event
5262 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
5264 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
5267 this.toggle( false );
5269 e
.stopPropagation();
5274 * Bind key down listener.
5278 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
5279 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
5283 * Unbind key down listener.
5287 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
5288 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
5292 * Show, hide, or toggle the visibility of the anchor.
5294 * @param {boolean} [show] Show anchor, omit to toggle
5296 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
5297 show
= show
=== undefined ? !this.anchored
: !!show
;
5299 if ( this.anchored
!== show
) {
5301 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
5302 this.$element
.addClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
5304 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
5305 this.$element
.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
5307 this.anchored
= show
;
5312 * Change which edge the anchor appears on.
5314 * @param {string} edge 'top', 'bottom', 'start' or 'end'
5316 OO
.ui
.PopupWidget
.prototype.setAnchorEdge = function ( edge
) {
5317 if ( [ 'top', 'bottom', 'start', 'end' ].indexOf( edge
) === -1 ) {
5318 throw new Error( 'Invalid value for edge: ' + edge
);
5320 if ( this.anchorEdge
!== null ) {
5321 this.$element
.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
5323 this.anchorEdge
= edge
;
5324 if ( this.anchored
) {
5325 this.$element
.addClass( 'oo-ui-popupWidget-anchored-' + edge
);
5330 * Check if the anchor is visible.
5332 * @return {boolean} Anchor is visible
5334 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
5335 return this.anchored
;
5339 * Toggle visibility of the popup. The popup is initially hidden and must be shown by calling
5340 * `.toggle( true )` after its #$element is attached to the DOM.
5342 * Do not show the popup while it is not attached to the DOM. The calculations required to display
5343 * it in the right place and with the right dimensions only work correctly while it is attached.
5344 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
5345 * strictly enforced, so currently it only generates a warning in the browser console.
5350 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
5351 var change
, normalHeight
, oppositeHeight
, normalWidth
, oppositeWidth
;
5352 show
= show
=== undefined ? !this.isVisible() : !!show
;
5354 change
= show
!== this.isVisible();
5356 if ( show
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
5357 OO
.ui
.warnDeprecation( 'PopupWidget#toggle: Before calling this method, the popup must be attached to the DOM.' );
5358 this.warnedUnattached
= true;
5360 if ( show
&& !this.$floatableContainer
&& this.isElementAttached() ) {
5361 // Fall back to the parent node if the floatableContainer is not set
5362 this.setFloatableContainer( this.$element
.parent() );
5365 if ( change
&& show
&& this.autoFlip
) {
5366 // Reset auto-flipping before showing the popup again. It's possible we no longer need to flip
5367 // (e.g. if the user scrolled).
5368 this.isAutoFlipped
= false;
5372 OO
.ui
.PopupWidget
.parent
.prototype.toggle
.call( this, show
);
5375 this.togglePositioning( show
&& !!this.$floatableContainer
);
5378 if ( this.autoClose
) {
5379 this.bindMouseDownListener();
5380 this.bindKeyDownListener();
5382 this.updateDimensions();
5383 this.toggleClipping( true );
5385 if ( this.autoFlip
) {
5386 if ( this.popupPosition
=== 'above' || this.popupPosition
=== 'below' ) {
5387 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
5388 // If opening the popup in the normal direction causes it to be clipped, open
5389 // in the opposite one instead
5390 normalHeight
= this.$element
.height();
5391 this.isAutoFlipped
= !this.isAutoFlipped
;
5393 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
5394 // If that also causes it to be clipped, open in whichever direction
5395 // we have more space
5396 oppositeHeight
= this.$element
.height();
5397 if ( oppositeHeight
< normalHeight
) {
5398 this.isAutoFlipped
= !this.isAutoFlipped
;
5404 if ( this.popupPosition
=== 'before' || this.popupPosition
=== 'after' ) {
5405 if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) {
5406 // If opening the popup in the normal direction causes it to be clipped, open
5407 // in the opposite one instead
5408 normalWidth
= this.$element
.width();
5409 this.isAutoFlipped
= !this.isAutoFlipped
;
5410 // Due to T180173 horizontally clipped PopupWidgets have messed up dimensions,
5411 // which causes positioning to be off. Toggle clipping back and fort to work around.
5412 this.toggleClipping( false );
5414 this.toggleClipping( true );
5415 if ( this.isClippedHorizontally() || this.isFloatableOutOfView() ) {
5416 // If that also causes it to be clipped, open in whichever direction
5417 // we have more space
5418 oppositeWidth
= this.$element
.width();
5419 if ( oppositeWidth
< normalWidth
) {
5420 this.isAutoFlipped
= !this.isAutoFlipped
;
5421 // Due to T180173 horizontally clipped PopupWidgets have messed up dimensions,
5422 // which causes positioning to be off. Toggle clipping back and fort to work around.
5423 this.toggleClipping( false );
5425 this.toggleClipping( true );
5432 this.emit( 'ready' );
5434 this.toggleClipping( false );
5435 if ( this.autoClose
) {
5436 this.unbindMouseDownListener();
5437 this.unbindKeyDownListener();
5446 * Set the size of the popup.
5448 * Changing the size may also change the popup's position depending on the alignment.
5450 * @param {number} width Width in pixels
5451 * @param {number} height Height in pixels
5452 * @param {boolean} [transition=false] Use a smooth transition
5455 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
5457 this.height
= height
!== undefined ? height
: null;
5458 if ( this.isVisible() ) {
5459 this.updateDimensions( transition
);
5464 * Update the size and position.
5466 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
5467 * be called automatically.
5469 * @param {boolean} [transition=false] Use a smooth transition
5472 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
5475 // Prevent transition from being interrupted
5476 clearTimeout( this.transitionTimeout
);
5478 // Enable transition
5479 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
5485 // Prevent transitioning after transition is complete
5486 this.transitionTimeout
= setTimeout( function () {
5487 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
5490 // Prevent transitioning immediately
5491 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
5498 OO
.ui
.PopupWidget
.prototype.computePosition = function () {
5499 var direction
, align
, vertical
, start
, end
, near
, far
, sizeProp
, popupSize
, anchorSize
, anchorPos
,
5500 anchorOffset
, anchorMargin
, parentPosition
, positionProp
, positionAdjustment
, floatablePos
,
5501 offsetParentPos
, containerPos
, popupPosition
, viewportSpacing
,
5503 anchorCss
= { left
: '', right
: '', top
: '', bottom
: '' },
5504 popupPositionOppositeMap
= {
5512 'force-left': 'backwards',
5513 'force-right': 'forwards'
5516 'force-left': 'forwards',
5517 'force-right': 'backwards'
5529 backwards
: this.anchored
? 'before' : 'end'
5537 if ( !this.$container
) {
5538 // Lazy-initialize $container if not specified in constructor
5539 this.$container
= $( this.getClosestScrollableElementContainer() );
5541 direction
= this.$container
.css( 'direction' );
5543 // Set height and width before we do anything else, since it might cause our measurements
5544 // to change (e.g. due to scrollbars appearing or disappearing), and it also affects centering
5547 height
: this.height
!== null ? this.height
: 'auto'
5550 align
= alignMap
[ direction
][ this.align
] || this.align
;
5551 popupPosition
= this.popupPosition
;
5552 if ( this.isAutoFlipped
) {
5553 popupPosition
= popupPositionOppositeMap
[ popupPosition
];
5556 // If the popup is positioned before or after, then the anchor positioning is vertical, otherwise horizontal
5557 vertical
= popupPosition
=== 'before' || popupPosition
=== 'after';
5558 start
= vertical
? 'top' : ( direction
=== 'rtl' ? 'right' : 'left' );
5559 end
= vertical
? 'bottom' : ( direction
=== 'rtl' ? 'left' : 'right' );
5560 near
= vertical
? 'top' : 'left';
5561 far
= vertical
? 'bottom' : 'right';
5562 sizeProp
= vertical
? 'Height' : 'Width';
5563 popupSize
= vertical
? ( this.height
|| this.$popup
.height() ) : this.width
;
5565 this.setAnchorEdge( anchorEdgeMap
[ popupPosition
] );
5566 this.horizontalPosition
= vertical
? popupPosition
: hPosMap
[ align
];
5567 this.verticalPosition
= vertical
? vPosMap
[ align
] : popupPosition
;
5570 parentPosition
= OO
.ui
.mixin
.FloatableElement
.prototype.computePosition
.call( this );
5571 // Find out which property FloatableElement used for positioning, and adjust that value
5572 positionProp
= vertical
?
5573 ( parentPosition
.top
!== '' ? 'top' : 'bottom' ) :
5574 ( parentPosition
.left
!== '' ? 'left' : 'right' );
5576 // Figure out where the near and far edges of the popup and $floatableContainer are
5577 floatablePos
= this.$floatableContainer
.offset();
5578 floatablePos
[ far
] = floatablePos
[ near
] + this.$floatableContainer
[ 'outer' + sizeProp
]();
5579 // Measure where the offsetParent is and compute our position based on that and parentPosition
5580 offsetParentPos
= this.$element
.offsetParent()[ 0 ] === document
.documentElement
?
5581 { top
: 0, left
: 0 } :
5582 this.$element
.offsetParent().offset();
5584 if ( positionProp
=== near
) {
5585 popupPos
[ near
] = offsetParentPos
[ near
] + parentPosition
[ near
];
5586 popupPos
[ far
] = popupPos
[ near
] + popupSize
;
5588 popupPos
[ far
] = offsetParentPos
[ near
] +
5589 this.$element
.offsetParent()[ 'inner' + sizeProp
]() - parentPosition
[ far
];
5590 popupPos
[ near
] = popupPos
[ far
] - popupSize
;
5593 if ( this.anchored
) {
5594 // Position the anchor (which is positioned relative to the popup) to point to $floatableContainer
5595 anchorPos
= ( floatablePos
[ start
] + floatablePos
[ end
] ) / 2;
5596 anchorOffset
= ( start
=== far
? -1 : 1 ) * ( anchorPos
- popupPos
[ start
] );
5598 // If the anchor is less than 2*anchorSize from either edge, move the popup to make more space
5599 // this.$anchor.width()/height() returns 0 because of the CSS trickery we use, so use scrollWidth/Height
5600 anchorSize
= this.$anchor
[ 0 ][ 'scroll' + sizeProp
];
5601 anchorMargin
= parseFloat( this.$anchor
.css( 'margin-' + start
) );
5602 if ( anchorOffset
+ anchorMargin
< 2 * anchorSize
) {
5603 // Not enough space for the anchor on the start side; pull the popup startwards
5604 positionAdjustment
= ( positionProp
=== start
? -1 : 1 ) *
5605 ( 2 * anchorSize
- ( anchorOffset
+ anchorMargin
) );
5606 } else if ( anchorOffset
+ anchorMargin
> popupSize
- 2 * anchorSize
) {
5607 // Not enough space for the anchor on the end side; pull the popup endwards
5608 positionAdjustment
= ( positionProp
=== end
? -1 : 1 ) *
5609 ( anchorOffset
+ anchorMargin
- ( popupSize
- 2 * anchorSize
) );
5611 positionAdjustment
= 0;
5614 positionAdjustment
= 0;
5617 // Check if the popup will go beyond the edge of this.$container
5618 containerPos
= this.$container
[ 0 ] === document
.documentElement
?
5619 { top
: 0, left
: 0 } :
5620 this.$container
.offset();
5621 containerPos
[ far
] = containerPos
[ near
] + this.$container
[ 'inner' + sizeProp
]();
5622 if ( this.$container
[ 0 ] === document
.documentElement
) {
5623 viewportSpacing
= OO
.ui
.getViewportSpacing();
5624 containerPos
[ near
] += viewportSpacing
[ near
];
5625 containerPos
[ far
] -= viewportSpacing
[ far
];
5627 // Take into account how much the popup will move because of the adjustments we're going to make
5628 popupPos
[ near
] += ( positionProp
=== near
? 1 : -1 ) * positionAdjustment
;
5629 popupPos
[ far
] += ( positionProp
=== near
? 1 : -1 ) * positionAdjustment
;
5630 if ( containerPos
[ near
] + this.containerPadding
> popupPos
[ near
] ) {
5631 // Popup goes beyond the near (left/top) edge, move it to the right/bottom
5632 positionAdjustment
+= ( positionProp
=== near
? 1 : -1 ) *
5633 ( containerPos
[ near
] + this.containerPadding
- popupPos
[ near
] );
5634 } else if ( containerPos
[ far
] - this.containerPadding
< popupPos
[ far
] ) {
5635 // Popup goes beyond the far (right/bottom) edge, move it to the left/top
5636 positionAdjustment
+= ( positionProp
=== far
? 1 : -1 ) *
5637 ( popupPos
[ far
] - ( containerPos
[ far
] - this.containerPadding
) );
5640 if ( this.anchored
) {
5641 // Adjust anchorOffset for positionAdjustment
5642 anchorOffset
+= ( positionProp
=== start
? -1 : 1 ) * positionAdjustment
;
5644 // Position the anchor
5645 anchorCss
[ start
] = anchorOffset
;
5646 this.$anchor
.css( anchorCss
);
5649 // Move the popup if needed
5650 parentPosition
[ positionProp
] += positionAdjustment
;
5652 return parentPosition
;
5656 * Set popup alignment
5658 * @param {string} [align=center] Alignment of the popup, `center`, `force-left`, `force-right`,
5659 * `backwards` or `forwards`.
5661 OO
.ui
.PopupWidget
.prototype.setAlignment = function ( align
) {
5662 // Validate alignment
5663 if ( [ 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align
) > -1 ) {
5666 this.align
= 'center';
5672 * Get popup alignment
5674 * @return {string} Alignment of the popup, `center`, `force-left`, `force-right`,
5675 * `backwards` or `forwards`.
5677 OO
.ui
.PopupWidget
.prototype.getAlignment = function () {
5682 * Change the positioning of the popup.
5684 * @param {string} position 'above', 'below', 'before' or 'after'
5686 OO
.ui
.PopupWidget
.prototype.setPosition = function ( position
) {
5687 if ( [ 'above', 'below', 'before', 'after' ].indexOf( position
) === -1 ) {
5690 this.popupPosition
= position
;
5695 * Get popup positioning.
5697 * @return {string} 'above', 'below', 'before' or 'after'
5699 OO
.ui
.PopupWidget
.prototype.getPosition = function () {
5700 return this.popupPosition
;
5704 * Set popup auto-flipping.
5706 * @param {boolean} autoFlip Whether to automatically switch the popup's position between
5707 * 'above' and 'below', or between 'before' and 'after', if there is not enough space in the
5708 * desired direction to display the popup without clipping
5710 OO
.ui
.PopupWidget
.prototype.setAutoFlip = function ( autoFlip
) {
5711 autoFlip
= !!autoFlip
;
5713 if ( this.autoFlip
!== autoFlip
) {
5714 this.autoFlip
= autoFlip
;
5719 * Get an ID of the body element, this can be used as the
5720 * `aria-describedby` attribute for an input field.
5722 * @return {string} The ID of the body element
5724 OO
.ui
.PopupWidget
.prototype.getBodyId = function () {
5725 var id
= this.$body
.attr( 'id' );
5726 if ( id
=== undefined ) {
5727 id
= OO
.ui
.generateElementId();
5728 this.$body
.attr( 'id', id
);
5734 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5735 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5736 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5737 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5743 * @param {Object} [config] Configuration options
5744 * @cfg {Object} [popup] Configuration to pass to popup
5745 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5747 OO
.ui
.mixin
.PopupElement
= function OoUiMixinPopupElement( config
) {
5748 // Configuration initialization
5749 config
= config
|| {};
5752 this.popup
= new OO
.ui
.PopupWidget( $.extend(
5755 $floatableContainer
: this.$element
5759 $autoCloseIgnore
: this.$element
.add( config
.popup
&& config
.popup
.$autoCloseIgnore
)
5769 * @return {OO.ui.PopupWidget} Popup widget
5771 OO
.ui
.mixin
.PopupElement
.prototype.getPopup = function () {
5776 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
5777 * which is used to display additional information or options.
5780 * // Example of a popup button.
5781 * var popupButton = new OO.ui.PopupButtonWidget( {
5782 * label: 'Popup button with options',
5785 * $content: $( '<p>Additional options here.</p>' ),
5787 * align: 'force-left'
5790 * // Append the button to the DOM.
5791 * $( 'body' ).append( popupButton.$element );
5794 * @extends OO.ui.ButtonWidget
5795 * @mixins OO.ui.mixin.PopupElement
5798 * @param {Object} [config] Configuration options
5799 * @cfg {jQuery} [$overlay] Render the popup into a separate layer. This configuration is useful in cases where
5800 * the expanded popup is larger than its containing `<div>`. The specified overlay layer is usually on top of the
5801 * containing `<div>` and has a larger area. By default, the popup uses relative positioning.
5802 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
5804 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
5805 // Configuration initialization
5806 config
= config
|| {};
5808 // Parent constructor
5809 OO
.ui
.PopupButtonWidget
.parent
.call( this, config
);
5811 // Mixin constructors
5812 OO
.ui
.mixin
.PopupElement
.call( this, config
);
5815 this.$overlay
= ( config
.$overlay
=== true ? OO
.ui
.getDefaultOverlay() : config
.$overlay
) || this.$element
;
5818 this.connect( this, { click
: 'onAction' } );
5822 .addClass( 'oo-ui-popupButtonWidget' )
5823 .attr( 'aria-haspopup', 'true' );
5825 .addClass( 'oo-ui-popupButtonWidget-popup' )
5826 .toggleClass( 'oo-ui-popupButtonWidget-framed-popup', this.isFramed() )
5827 .toggleClass( 'oo-ui-popupButtonWidget-frameless-popup', !this.isFramed() );
5828 this.$overlay
.append( this.popup
.$element
);
5833 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
5834 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.mixin
.PopupElement
);
5839 * Handle the button action being triggered.
5843 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
5844 this.popup
.toggle();
5848 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
5850 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
5855 * @mixins OO.ui.mixin.GroupElement
5858 * @param {Object} [config] Configuration options
5860 OO
.ui
.mixin
.GroupWidget
= function OoUiMixinGroupWidget( config
) {
5861 // Mixin constructors
5862 OO
.ui
.mixin
.GroupElement
.call( this, config
);
5867 OO
.mixinClass( OO
.ui
.mixin
.GroupWidget
, OO
.ui
.mixin
.GroupElement
);
5872 * Set the disabled state of the widget.
5874 * This will also update the disabled state of child widgets.
5876 * @param {boolean} disabled Disable widget
5879 OO
.ui
.mixin
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
5883 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
5884 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
5886 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
5888 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5889 this.items
[ i
].updateDisabled();
5897 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
5899 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
5900 * allows bidirectional communication.
5902 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
5910 OO
.ui
.mixin
.ItemWidget
= function OoUiMixinItemWidget() {
5917 * Check if widget is disabled.
5919 * Checks parent if present, making disabled state inheritable.
5921 * @return {boolean} Widget is disabled
5923 OO
.ui
.mixin
.ItemWidget
.prototype.isDisabled = function () {
5924 return this.disabled
||
5925 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
5929 * Set group element is in.
5931 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
5934 OO
.ui
.mixin
.ItemWidget
.prototype.setElementGroup = function ( group
) {
5936 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
5937 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
5939 // Initialize item disabled states
5940 this.updateDisabled();
5946 * OptionWidgets are special elements that can be selected and configured with data. The
5947 * data is often unique for each option, but it does not have to be. OptionWidgets are used
5948 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
5949 * and examples, please see the [OOUI documentation on MediaWiki][1].
5951 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
5954 * @extends OO.ui.Widget
5955 * @mixins OO.ui.mixin.ItemWidget
5956 * @mixins OO.ui.mixin.LabelElement
5957 * @mixins OO.ui.mixin.FlaggedElement
5958 * @mixins OO.ui.mixin.AccessKeyedElement
5961 * @param {Object} [config] Configuration options
5963 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
5964 // Configuration initialization
5965 config
= config
|| {};
5967 // Parent constructor
5968 OO
.ui
.OptionWidget
.parent
.call( this, config
);
5970 // Mixin constructors
5971 OO
.ui
.mixin
.ItemWidget
.call( this );
5972 OO
.ui
.mixin
.LabelElement
.call( this, config
);
5973 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
5974 OO
.ui
.mixin
.AccessKeyedElement
.call( this, config
);
5977 this.selected
= false;
5978 this.highlighted
= false;
5979 this.pressed
= false;
5983 .data( 'oo-ui-optionWidget', this )
5984 // Allow programmatic focussing (and by accesskey), but not tabbing
5985 .attr( 'tabindex', '-1' )
5986 .attr( 'role', 'option' )
5987 .attr( 'aria-selected', 'false' )
5988 .addClass( 'oo-ui-optionWidget' )
5989 .append( this.$label
);
5994 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
5995 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.ItemWidget
);
5996 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.LabelElement
);
5997 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.FlaggedElement
);
5998 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
6000 /* Static Properties */
6003 * Whether this option can be selected. See #setSelected.
6007 * @property {boolean}
6009 OO
.ui
.OptionWidget
.static.selectable
= true;
6012 * Whether this option can be highlighted. See #setHighlighted.
6016 * @property {boolean}
6018 OO
.ui
.OptionWidget
.static.highlightable
= true;
6021 * Whether this option can be pressed. See #setPressed.
6025 * @property {boolean}
6027 OO
.ui
.OptionWidget
.static.pressable
= true;
6030 * Whether this option will be scrolled into view when it is selected.
6034 * @property {boolean}
6036 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
6041 * Check if the option can be selected.
6043 * @return {boolean} Item is selectable
6045 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
6046 return this.constructor.static.selectable
&& !this.disabled
&& this.isVisible();
6050 * Check if the option can be highlighted. A highlight indicates that the option
6051 * may be selected when a user presses enter or clicks. Disabled items cannot
6054 * @return {boolean} Item is highlightable
6056 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
6057 return this.constructor.static.highlightable
&& !this.disabled
&& this.isVisible();
6061 * Check if the option can be pressed. The pressed state occurs when a user mouses
6062 * down on an item, but has not yet let go of the mouse.
6064 * @return {boolean} Item is pressable
6066 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
6067 return this.constructor.static.pressable
&& !this.disabled
&& this.isVisible();
6071 * Check if the option is selected.
6073 * @return {boolean} Item is selected
6075 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
6076 return this.selected
;
6080 * Check if the option is highlighted. A highlight indicates that the
6081 * item may be selected when a user presses enter or clicks.
6083 * @return {boolean} Item is highlighted
6085 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
6086 return this.highlighted
;
6090 * Check if the option is pressed. The pressed state occurs when a user mouses
6091 * down on an item, but has not yet let go of the mouse. The item may appear
6092 * selected, but it will not be selected until the user releases the mouse.
6094 * @return {boolean} Item is pressed
6096 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
6097 return this.pressed
;
6101 * Set the option’s selected state. In general, all modifications to the selection
6102 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
6103 * method instead of this method.
6105 * @param {boolean} [state=false] Select option
6108 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
6109 if ( this.constructor.static.selectable
) {
6110 this.selected
= !!state
;
6112 .toggleClass( 'oo-ui-optionWidget-selected', state
)
6113 .attr( 'aria-selected', state
.toString() );
6114 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
6115 this.scrollElementIntoView();
6117 this.updateThemeClasses();
6123 * Set the option’s highlighted state. In general, all programmatic
6124 * modifications to the highlight should be handled by the
6125 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
6126 * method instead of this method.
6128 * @param {boolean} [state=false] Highlight option
6131 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
6132 if ( this.constructor.static.highlightable
) {
6133 this.highlighted
= !!state
;
6134 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
6135 this.updateThemeClasses();
6141 * Set the option’s pressed state. In general, all
6142 * programmatic modifications to the pressed state should be handled by the
6143 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
6144 * method instead of this method.
6146 * @param {boolean} [state=false] Press option
6149 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
6150 if ( this.constructor.static.pressable
) {
6151 this.pressed
= !!state
;
6152 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
6153 this.updateThemeClasses();
6159 * Get text to match search strings against.
6161 * The default implementation returns the label text, but subclasses
6162 * can override this to provide more complex behavior.
6164 * @return {string|boolean} String to match search string against
6166 OO
.ui
.OptionWidget
.prototype.getMatchText = function () {
6167 var label
= this.getLabel();
6168 return typeof label
=== 'string' ? label
: this.$label
.text();
6172 * A SelectWidget is of a generic selection of options. The OOUI library contains several types of
6173 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
6174 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
6177 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
6178 * information, please see the [OOUI documentation on MediaWiki][1].
6181 * // Example of a select widget with three options
6182 * var select = new OO.ui.SelectWidget( {
6184 * new OO.ui.OptionWidget( {
6186 * label: 'Option One',
6188 * new OO.ui.OptionWidget( {
6190 * label: 'Option Two',
6192 * new OO.ui.OptionWidget( {
6194 * label: 'Option Three',
6198 * $( 'body' ).append( select.$element );
6200 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6204 * @extends OO.ui.Widget
6205 * @mixins OO.ui.mixin.GroupWidget
6208 * @param {Object} [config] Configuration options
6209 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
6210 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
6211 * the [OOUI documentation on MediaWiki] [2] for examples.
6212 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
6214 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
6215 // Configuration initialization
6216 config
= config
|| {};
6218 // Parent constructor
6219 OO
.ui
.SelectWidget
.parent
.call( this, config
);
6221 // Mixin constructors
6222 OO
.ui
.mixin
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
6225 this.pressed
= false;
6226 this.selecting
= null;
6227 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
6228 this.onMouseMoveHandler
= this.onMouseMove
.bind( this );
6229 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
6230 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
6231 this.keyPressBuffer
= '';
6232 this.keyPressBufferTimer
= null;
6233 this.blockMouseOverEvents
= 0;
6236 this.connect( this, {
6240 focusin
: this.onFocus
.bind( this ),
6241 mousedown
: this.onMouseDown
.bind( this ),
6242 mouseover
: this.onMouseOver
.bind( this ),
6243 mouseleave
: this.onMouseLeave
.bind( this )
6248 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
6249 .attr( 'role', 'listbox' );
6250 this.setFocusOwner( this.$element
);
6251 if ( Array
.isArray( config
.items
) ) {
6252 this.addItems( config
.items
);
6258 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
6259 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupWidget
);
6266 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
6268 * @param {OO.ui.OptionWidget|null} item Highlighted item
6274 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
6275 * pressed state of an option.
6277 * @param {OO.ui.OptionWidget|null} item Pressed item
6283 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
6285 * @param {OO.ui.OptionWidget|null} item Selected item
6290 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
6291 * @param {OO.ui.OptionWidget} item Chosen item
6297 * An `add` event is emitted when options are added to the select with the #addItems method.
6299 * @param {OO.ui.OptionWidget[]} items Added items
6300 * @param {number} index Index of insertion point
6306 * A `remove` event is emitted when options are removed from the select with the #clearItems
6307 * or #removeItems methods.
6309 * @param {OO.ui.OptionWidget[]} items Removed items
6315 * Handle focus events
6318 * @param {jQuery.Event} event
6320 OO
.ui
.SelectWidget
.prototype.onFocus = function ( event
) {
6322 if ( event
.target
=== this.$element
[ 0 ] ) {
6323 // This widget was focussed, e.g. by the user tabbing to it.
6324 // The styles for focus state depend on one of the items being selected.
6325 if ( !this.findSelectedItem() ) {
6326 item
= this.findFirstSelectableItem();
6329 if ( event
.target
.tabIndex
=== -1 ) {
6330 // One of the options got focussed (and the event bubbled up here).
6331 // They can't be tabbed to, but they can be activated using accesskeys.
6332 // OptionWidgets and focusable UI elements inside them have tabindex="-1" set.
6333 item
= this.findTargetItem( event
);
6335 // There is something actually user-focusable in one of the labels of the options, and the
6336 // user focussed it (e.g. by tabbing to it). Do nothing (especially, don't change the focus).
6342 if ( item
.constructor.static.highlightable
) {
6343 this.highlightItem( item
);
6345 this.selectItem( item
);
6349 if ( event
.target
!== this.$element
[ 0 ] ) {
6350 this.$focusOwner
.focus();
6355 * Handle mouse down events.
6358 * @param {jQuery.Event} e Mouse down event
6360 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
6363 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
6364 this.togglePressed( true );
6365 item
= this.findTargetItem( e
);
6366 if ( item
&& item
.isSelectable() ) {
6367 this.pressItem( item
);
6368 this.selecting
= item
;
6369 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
6370 this.getElementDocument().addEventListener( 'mousemove', this.onMouseMoveHandler
, true );
6377 * Handle mouse up events.
6380 * @param {MouseEvent} e Mouse up event
6382 OO
.ui
.SelectWidget
.prototype.onMouseUp = function ( e
) {
6385 this.togglePressed( false );
6386 if ( !this.selecting
) {
6387 item
= this.findTargetItem( e
);
6388 if ( item
&& item
.isSelectable() ) {
6389 this.selecting
= item
;
6392 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
&& this.selecting
) {
6393 this.pressItem( null );
6394 this.chooseItem( this.selecting
);
6395 this.selecting
= null;
6398 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
6399 this.getElementDocument().removeEventListener( 'mousemove', this.onMouseMoveHandler
, true );
6405 * Handle mouse move events.
6408 * @param {MouseEvent} e Mouse move event
6410 OO
.ui
.SelectWidget
.prototype.onMouseMove = function ( e
) {
6413 if ( !this.isDisabled() && this.pressed
) {
6414 item
= this.findTargetItem( e
);
6415 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
6416 this.pressItem( item
);
6417 this.selecting
= item
;
6423 * Handle mouse over events.
6426 * @param {jQuery.Event} e Mouse over event
6428 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
6430 if ( this.blockMouseOverEvents
) {
6433 if ( !this.isDisabled() ) {
6434 item
= this.findTargetItem( e
);
6435 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
6441 * Handle mouse leave events.
6444 * @param {jQuery.Event} e Mouse over event
6446 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
6447 if ( !this.isDisabled() ) {
6448 this.highlightItem( null );
6454 * Handle key down events.
6457 * @param {KeyboardEvent} e Key down event
6459 OO
.ui
.SelectWidget
.prototype.onKeyDown = function ( e
) {
6462 currentItem
= this.findHighlightedItem() || this.findSelectedItem();
6464 if ( !this.isDisabled() && this.isVisible() ) {
6465 switch ( e
.keyCode
) {
6466 case OO
.ui
.Keys
.ENTER
:
6467 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
6468 // Was only highlighted, now let's select it. No-op if already selected.
6469 this.chooseItem( currentItem
);
6474 case OO
.ui
.Keys
.LEFT
:
6475 this.clearKeyPressBuffer();
6476 nextItem
= this.findRelativeSelectableItem( currentItem
, -1 );
6479 case OO
.ui
.Keys
.DOWN
:
6480 case OO
.ui
.Keys
.RIGHT
:
6481 this.clearKeyPressBuffer();
6482 nextItem
= this.findRelativeSelectableItem( currentItem
, 1 );
6485 case OO
.ui
.Keys
.ESCAPE
:
6486 case OO
.ui
.Keys
.TAB
:
6487 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
6488 currentItem
.setHighlighted( false );
6490 this.unbindKeyDownListener();
6491 this.unbindKeyPressListener();
6492 // Don't prevent tabbing away / defocusing
6498 if ( nextItem
.constructor.static.highlightable
) {
6499 this.highlightItem( nextItem
);
6501 this.chooseItem( nextItem
);
6503 this.scrollItemIntoView( nextItem
);
6508 e
.stopPropagation();
6514 * Bind key down listener.
6518 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
6519 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler
, true );
6523 * Unbind key down listener.
6527 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
6528 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler
, true );
6532 * Scroll item into view, preventing spurious mouse highlight actions from happening.
6534 * @param {OO.ui.OptionWidget} item Item to scroll into view
6536 OO
.ui
.SelectWidget
.prototype.scrollItemIntoView = function ( item
) {
6538 // Chromium's Blink engine will generate spurious 'mouseover' events during programmatic scrolling
6539 // and around 100-150 ms after it is finished.
6540 this.blockMouseOverEvents
++;
6541 item
.scrollElementIntoView().done( function () {
6542 setTimeout( function () {
6543 widget
.blockMouseOverEvents
--;
6549 * Clear the key-press buffer
6553 OO
.ui
.SelectWidget
.prototype.clearKeyPressBuffer = function () {
6554 if ( this.keyPressBufferTimer
) {
6555 clearTimeout( this.keyPressBufferTimer
);
6556 this.keyPressBufferTimer
= null;
6558 this.keyPressBuffer
= '';
6562 * Handle key press events.
6565 * @param {KeyboardEvent} e Key press event
6567 OO
.ui
.SelectWidget
.prototype.onKeyPress = function ( e
) {
6568 var c
, filter
, item
;
6570 if ( !e
.charCode
) {
6571 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.keyPressBuffer
!== '' ) {
6572 this.keyPressBuffer
= this.keyPressBuffer
.substr( 0, this.keyPressBuffer
.length
- 1 );
6577 if ( String
.fromCodePoint
) {
6578 c
= String
.fromCodePoint( e
.charCode
);
6580 c
= String
.fromCharCode( e
.charCode
);
6583 if ( this.keyPressBufferTimer
) {
6584 clearTimeout( this.keyPressBufferTimer
);
6586 this.keyPressBufferTimer
= setTimeout( this.clearKeyPressBuffer
.bind( this ), 1500 );
6588 item
= this.findHighlightedItem() || this.findSelectedItem();
6590 if ( this.keyPressBuffer
=== c
) {
6591 // Common (if weird) special case: typing "xxxx" will cycle through all
6592 // the items beginning with "x".
6594 item
= this.findRelativeSelectableItem( item
, 1 );
6597 this.keyPressBuffer
+= c
;
6600 filter
= this.getItemMatcher( this.keyPressBuffer
, false );
6601 if ( !item
|| !filter( item
) ) {
6602 item
= this.findRelativeSelectableItem( item
, 1, filter
);
6605 if ( this.isVisible() && item
.constructor.static.highlightable
) {
6606 this.highlightItem( item
);
6608 this.chooseItem( item
);
6610 this.scrollItemIntoView( item
);
6614 e
.stopPropagation();
6618 * Get a matcher for the specific string
6621 * @param {string} s String to match against items
6622 * @param {boolean} [exact=false] Only accept exact matches
6623 * @return {Function} function ( OO.ui.OptionWidget ) => boolean
6625 OO
.ui
.SelectWidget
.prototype.getItemMatcher = function ( s
, exact
) {
6628 if ( s
.normalize
) {
6631 s
= exact
? s
.trim() : s
.replace( /^\s+/, '' );
6632 re
= '^\\s*' + s
.replace( /([\\{}()|.?*+\-^$[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
6636 re
= new RegExp( re
, 'i' );
6637 return function ( item
) {
6638 var matchText
= item
.getMatchText();
6639 if ( matchText
.normalize
) {
6640 matchText
= matchText
.normalize();
6642 return re
.test( matchText
);
6647 * Bind key press listener.
6651 OO
.ui
.SelectWidget
.prototype.bindKeyPressListener = function () {
6652 this.getElementWindow().addEventListener( 'keypress', this.onKeyPressHandler
, true );
6656 * Unbind key down listener.
6658 * If you override this, be sure to call this.clearKeyPressBuffer() from your
6663 OO
.ui
.SelectWidget
.prototype.unbindKeyPressListener = function () {
6664 this.getElementWindow().removeEventListener( 'keypress', this.onKeyPressHandler
, true );
6665 this.clearKeyPressBuffer();
6669 * Visibility change handler
6672 * @param {boolean} visible
6674 OO
.ui
.SelectWidget
.prototype.onToggle = function ( visible
) {
6676 this.clearKeyPressBuffer();
6681 * Get the closest item to a jQuery.Event.
6684 * @param {jQuery.Event} e
6685 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
6687 OO
.ui
.SelectWidget
.prototype.findTargetItem = function ( e
) {
6688 var $option
= $( e
.target
).closest( '.oo-ui-optionWidget' );
6689 if ( !$option
.closest( '.oo-ui-selectWidget' ).is( this.$element
) ) {
6692 return $option
.data( 'oo-ui-optionWidget' ) || null;
6696 * Find selected item.
6698 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
6700 OO
.ui
.SelectWidget
.prototype.findSelectedItem = function () {
6703 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6704 if ( this.items
[ i
].isSelected() ) {
6705 return this.items
[ i
];
6712 * Find highlighted item.
6714 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
6716 OO
.ui
.SelectWidget
.prototype.findHighlightedItem = function () {
6719 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6720 if ( this.items
[ i
].isHighlighted() ) {
6721 return this.items
[ i
];
6728 * Toggle pressed state.
6730 * Press is a state that occurs when a user mouses down on an item, but
6731 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
6732 * until the user releases the mouse.
6734 * @param {boolean} pressed An option is being pressed
6736 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
6737 if ( pressed
=== undefined ) {
6738 pressed
= !this.pressed
;
6740 if ( pressed
!== this.pressed
) {
6742 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
6743 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
6744 this.pressed
= pressed
;
6749 * Highlight an option. If the `item` param is omitted, no options will be highlighted
6750 * and any existing highlight will be removed. The highlight is mutually exclusive.
6752 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
6756 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
6757 var i
, len
, highlighted
,
6760 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6761 highlighted
= this.items
[ i
] === item
;
6762 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
6763 this.items
[ i
].setHighlighted( highlighted
);
6769 this.$focusOwner
.attr( 'aria-activedescendant', item
.getElementId() );
6771 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
6773 this.emit( 'highlight', item
);
6780 * Fetch an item by its label.
6782 * @param {string} label Label of the item to select.
6783 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
6784 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
6786 OO
.ui
.SelectWidget
.prototype.getItemFromLabel = function ( label
, prefix
) {
6788 len
= this.items
.length
,
6789 filter
= this.getItemMatcher( label
, true );
6791 for ( i
= 0; i
< len
; i
++ ) {
6792 item
= this.items
[ i
];
6793 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
6800 filter
= this.getItemMatcher( label
, false );
6801 for ( i
= 0; i
< len
; i
++ ) {
6802 item
= this.items
[ i
];
6803 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
6819 * Programmatically select an option by its label. If the item does not exist,
6820 * all options will be deselected.
6822 * @param {string} [label] Label of the item to select.
6823 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
6827 OO
.ui
.SelectWidget
.prototype.selectItemByLabel = function ( label
, prefix
) {
6828 var itemFromLabel
= this.getItemFromLabel( label
, !!prefix
);
6829 if ( label
=== undefined || !itemFromLabel
) {
6830 return this.selectItem();
6832 return this.selectItem( itemFromLabel
);
6836 * Programmatically select an option by its data. If the `data` parameter is omitted,
6837 * or if the item does not exist, all options will be deselected.
6839 * @param {Object|string} [data] Value of the item to select, omit to deselect all
6843 OO
.ui
.SelectWidget
.prototype.selectItemByData = function ( data
) {
6844 var itemFromData
= this.findItemFromData( data
);
6845 if ( data
=== undefined || !itemFromData
) {
6846 return this.selectItem();
6848 return this.selectItem( itemFromData
);
6852 * Programmatically select an option by its reference. If the `item` parameter is omitted,
6853 * all options will be deselected.
6855 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
6859 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
6860 var i
, len
, selected
,
6863 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6864 selected
= this.items
[ i
] === item
;
6865 if ( this.items
[ i
].isSelected() !== selected
) {
6866 this.items
[ i
].setSelected( selected
);
6871 if ( item
&& !item
.constructor.static.highlightable
) {
6873 this.$focusOwner
.attr( 'aria-activedescendant', item
.getElementId() );
6875 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
6878 this.emit( 'select', item
);
6887 * Press is a state that occurs when a user mouses down on an item, but has not
6888 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
6889 * releases the mouse.
6891 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
6895 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
6896 var i
, len
, pressed
,
6899 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6900 pressed
= this.items
[ i
] === item
;
6901 if ( this.items
[ i
].isPressed() !== pressed
) {
6902 this.items
[ i
].setPressed( pressed
);
6907 this.emit( 'press', item
);
6916 * Note that ‘choose’ should never be modified programmatically. A user can choose
6917 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
6918 * use the #selectItem method.
6920 * This method is identical to #selectItem, but may vary in subclasses that take additional action
6921 * when users choose an item with the keyboard or mouse.
6923 * @param {OO.ui.OptionWidget} item Item to choose
6927 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
6929 this.selectItem( item
);
6930 this.emit( 'choose', item
);
6937 * Find an option by its position relative to the specified item (or to the start of the option array,
6938 * if item is `null`). The direction in which to search through the option array is specified with a
6939 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
6940 * `null` if there are no options in the array.
6942 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
6943 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
6944 * @param {Function} [filter] Only consider items for which this function returns
6945 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
6946 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
6948 OO
.ui
.SelectWidget
.prototype.findRelativeSelectableItem = function ( item
, direction
, filter
) {
6949 var currentIndex
, nextIndex
, i
,
6950 increase
= direction
> 0 ? 1 : -1,
6951 len
= this.items
.length
;
6953 if ( item
instanceof OO
.ui
.OptionWidget
) {
6954 currentIndex
= this.items
.indexOf( item
);
6955 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
6957 // If no item is selected and moving forward, start at the beginning.
6958 // If moving backward, start at the end.
6959 nextIndex
= direction
> 0 ? 0 : len
- 1;
6962 for ( i
= 0; i
< len
; i
++ ) {
6963 item
= this.items
[ nextIndex
];
6965 item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() &&
6966 ( !filter
|| filter( item
) )
6970 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
6976 * Find the next selectable item or `null` if there are no selectable items.
6977 * Disabled options and menu-section markers and breaks are not selectable.
6979 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
6981 OO
.ui
.SelectWidget
.prototype.findFirstSelectableItem = function () {
6982 return this.findRelativeSelectableItem( null, 1 );
6986 * Add an array of options to the select. Optionally, an index number can be used to
6987 * specify an insertion point.
6989 * @param {OO.ui.OptionWidget[]} items Items to add
6990 * @param {number} [index] Index to insert items after
6994 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
6996 OO
.ui
.mixin
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
6998 // Always provide an index, even if it was omitted
6999 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
7005 * Remove the specified array of options from the select. Options will be detached
7006 * from the DOM, not removed, so they can be reused later. To remove all options from
7007 * the select, you may wish to use the #clearItems method instead.
7009 * @param {OO.ui.OptionWidget[]} items Items to remove
7013 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
7016 // Deselect items being removed
7017 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
7019 if ( item
.isSelected() ) {
7020 this.selectItem( null );
7025 OO
.ui
.mixin
.GroupWidget
.prototype.removeItems
.call( this, items
);
7027 this.emit( 'remove', items
);
7033 * Clear all options from the select. Options will be detached from the DOM, not removed,
7034 * so that they can be reused later. To remove a subset of options from the select, use
7035 * the #removeItems method.
7040 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
7041 var items
= this.items
.slice();
7044 OO
.ui
.mixin
.GroupWidget
.prototype.clearItems
.call( this );
7047 this.selectItem( null );
7049 this.emit( 'remove', items
);
7055 * Set the DOM element which has focus while the user is interacting with this SelectWidget.
7057 * Currently this is just used to set `aria-activedescendant` on it.
7060 * @param {jQuery} $focusOwner
7062 OO
.ui
.SelectWidget
.prototype.setFocusOwner = function ( $focusOwner
) {
7063 this.$focusOwner
= $focusOwner
;
7067 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
7068 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
7069 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
7070 * options. For more information about options and selects, please see the
7071 * [OOUI documentation on MediaWiki][1].
7074 * // Decorated options in a select widget
7075 * var select = new OO.ui.SelectWidget( {
7077 * new OO.ui.DecoratedOptionWidget( {
7079 * label: 'Option with icon',
7082 * new OO.ui.DecoratedOptionWidget( {
7084 * label: 'Option with indicator',
7089 * $( 'body' ).append( select.$element );
7091 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7094 * @extends OO.ui.OptionWidget
7095 * @mixins OO.ui.mixin.IconElement
7096 * @mixins OO.ui.mixin.IndicatorElement
7099 * @param {Object} [config] Configuration options
7101 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
7102 // Parent constructor
7103 OO
.ui
.DecoratedOptionWidget
.parent
.call( this, config
);
7105 // Mixin constructors
7106 OO
.ui
.mixin
.IconElement
.call( this, config
);
7107 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
7111 .addClass( 'oo-ui-decoratedOptionWidget' )
7112 .prepend( this.$icon
)
7113 .append( this.$indicator
);
7118 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
7119 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IconElement
);
7120 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IndicatorElement
);
7123 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
7124 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
7125 * the [OOUI documentation on MediaWiki] [1] for more information.
7127 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
7130 * @extends OO.ui.DecoratedOptionWidget
7133 * @param {Object} [config] Configuration options
7135 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
7136 // Parent constructor
7137 OO
.ui
.MenuOptionWidget
.parent
.call( this, config
);
7140 this.checkIcon
= new OO
.ui
.IconWidget( {
7142 classes
: [ 'oo-ui-menuOptionWidget-checkIcon' ]
7147 .prepend( this.checkIcon
.$element
)
7148 .addClass( 'oo-ui-menuOptionWidget' );
7153 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
7155 /* Static Properties */
7161 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
7164 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
7165 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
7168 * var myDropdown = new OO.ui.DropdownWidget( {
7171 * new OO.ui.MenuSectionOptionWidget( {
7174 * new OO.ui.MenuOptionWidget( {
7176 * label: 'Welsh Corgi'
7178 * new OO.ui.MenuOptionWidget( {
7180 * label: 'Standard Poodle'
7182 * new OO.ui.MenuSectionOptionWidget( {
7185 * new OO.ui.MenuOptionWidget( {
7192 * $( 'body' ).append( myDropdown.$element );
7195 * @extends OO.ui.DecoratedOptionWidget
7198 * @param {Object} [config] Configuration options
7200 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
7201 // Parent constructor
7202 OO
.ui
.MenuSectionOptionWidget
.parent
.call( this, config
);
7205 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' )
7206 .removeAttr( 'role aria-selected' );
7211 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
7213 /* Static Properties */
7219 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
7225 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
7228 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
7229 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
7230 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
7231 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
7232 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
7233 * and customized to be opened, closed, and displayed as needed.
7235 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
7236 * mouse outside the menu.
7238 * Menus also have support for keyboard interaction:
7240 * - Enter/Return key: choose and select a menu option
7241 * - Up-arrow key: highlight the previous menu option
7242 * - Down-arrow key: highlight the next menu option
7243 * - Esc key: hide the menu
7245 * Unlike most widgets, MenuSelectWidget is initially hidden and must be shown by calling #toggle.
7247 * Please see the [OOUI documentation on MediaWiki][1] for more information.
7248 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7251 * @extends OO.ui.SelectWidget
7252 * @mixins OO.ui.mixin.ClippableElement
7253 * @mixins OO.ui.mixin.FloatableElement
7256 * @param {Object} [config] Configuration options
7257 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
7258 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
7259 * and {@link OO.ui.mixin.LookupElement LookupElement}
7260 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
7261 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiselectWidget CapsuleMultiselectWidget}
7262 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
7263 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
7264 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
7265 * that button, unless the button (or its parent widget) is passed in here.
7266 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
7267 * @cfg {jQuery} [$autoCloseIgnore] If these elements are clicked, don't auto-hide the menu.
7268 * @cfg {boolean} [hideOnChoose=true] Hide the menu when the user chooses an option.
7269 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
7270 * @cfg {boolean} [highlightOnFilter] Highlight the first result when filtering
7271 * @cfg {number} [width] Width of the menu
7273 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
7274 // Configuration initialization
7275 config
= config
|| {};
7277 // Parent constructor
7278 OO
.ui
.MenuSelectWidget
.parent
.call( this, config
);
7280 // Mixin constructors
7281 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
7282 OO
.ui
.mixin
.FloatableElement
.call( this, config
);
7285 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
7286 this.hideOnChoose
= config
.hideOnChoose
=== undefined || !!config
.hideOnChoose
;
7287 this.filterFromInput
= !!config
.filterFromInput
;
7288 this.$input
= config
.$input
? config
.$input
: config
.input
? config
.input
.$input
: null;
7289 this.$widget
= config
.widget
? config
.widget
.$element
: null;
7290 this.$autoCloseIgnore
= config
.$autoCloseIgnore
|| $( [] );
7291 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
7292 this.onInputEditHandler
= OO
.ui
.debounce( this.updateItemVisibility
.bind( this ), 100 );
7293 this.highlightOnFilter
= !!config
.highlightOnFilter
;
7294 this.width
= config
.width
;
7297 this.$element
.addClass( 'oo-ui-menuSelectWidget' );
7298 if ( config
.widget
) {
7299 this.setFocusOwner( config
.widget
.$tabIndexed
);
7302 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
7303 // that reference properties not initialized at that time of parent class construction
7304 // TODO: Find a better way to handle post-constructor setup
7305 this.visible
= false;
7306 this.$element
.addClass( 'oo-ui-element-hidden' );
7311 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
7312 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.ClippableElement
);
7313 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.FloatableElement
);
7320 * The menu is ready: it is visible and has been positioned and clipped.
7326 * Handles document mouse down events.
7329 * @param {MouseEvent} e Mouse down event
7331 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
7335 this.$element
.add( this.$widget
).add( this.$autoCloseIgnore
).get(),
7340 this.toggle( false );
7347 OO
.ui
.MenuSelectWidget
.prototype.onKeyDown = function ( e
) {
7348 var currentItem
= this.findHighlightedItem() || this.findSelectedItem();
7350 if ( !this.isDisabled() && this.isVisible() ) {
7351 switch ( e
.keyCode
) {
7352 case OO
.ui
.Keys
.LEFT
:
7353 case OO
.ui
.Keys
.RIGHT
:
7354 // Do nothing if a text field is associated, arrow keys will be handled natively
7355 if ( !this.$input
) {
7356 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
7359 case OO
.ui
.Keys
.ESCAPE
:
7360 case OO
.ui
.Keys
.TAB
:
7361 if ( currentItem
) {
7362 currentItem
.setHighlighted( false );
7364 this.toggle( false );
7365 // Don't prevent tabbing away, prevent defocusing
7366 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
7368 e
.stopPropagation();
7372 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
7379 * Update menu item visibility and clipping after input changes (if filterFromInput is enabled)
7380 * or after items were added/removed (always).
7384 OO
.ui
.MenuSelectWidget
.prototype.updateItemVisibility = function () {
7385 var i
, item
, visible
, section
, sectionEmpty
, filter
, exactFilter
,
7386 firstItemFound
= false,
7388 len
= this.items
.length
,
7389 showAll
= !this.isVisible(),
7392 if ( this.$input
&& this.filterFromInput
) {
7393 filter
= showAll
? null : this.getItemMatcher( this.$input
.val() );
7394 exactFilter
= this.getItemMatcher( this.$input
.val(), true );
7396 // Hide non-matching options, and also hide section headers if all options
7397 // in their section are hidden.
7398 for ( i
= 0; i
< len
; i
++ ) {
7399 item
= this.items
[ i
];
7400 if ( item
instanceof OO
.ui
.MenuSectionOptionWidget
) {
7402 // If the previous section was empty, hide its header
7403 section
.toggle( showAll
|| !sectionEmpty
);
7406 sectionEmpty
= true;
7407 } else if ( item
instanceof OO
.ui
.OptionWidget
) {
7408 visible
= showAll
|| filter( item
);
7409 exactMatch
= exactMatch
|| exactFilter( item
);
7410 anyVisible
= anyVisible
|| visible
;
7411 sectionEmpty
= sectionEmpty
&& !visible
;
7412 item
.toggle( visible
);
7413 if ( this.highlightOnFilter
&& visible
&& !firstItemFound
) {
7414 // Highlight the first item in the list
7415 this.highlightItem( item
);
7416 firstItemFound
= true;
7420 // Process the final section
7422 section
.toggle( showAll
|| !sectionEmpty
);
7425 if ( anyVisible
&& this.items
.length
&& !exactMatch
) {
7426 this.scrollItemIntoView( this.items
[ 0 ] );
7429 this.$element
.toggleClass( 'oo-ui-menuSelectWidget-invisible', !anyVisible
);
7432 // Reevaluate clipping
7439 OO
.ui
.MenuSelectWidget
.prototype.bindKeyDownListener = function () {
7440 if ( this.$input
) {
7441 this.$input
.on( 'keydown', this.onKeyDownHandler
);
7443 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyDownListener
.call( this );
7450 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyDownListener = function () {
7451 if ( this.$input
) {
7452 this.$input
.off( 'keydown', this.onKeyDownHandler
);
7454 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyDownListener
.call( this );
7461 OO
.ui
.MenuSelectWidget
.prototype.bindKeyPressListener = function () {
7462 if ( this.$input
) {
7463 if ( this.filterFromInput
) {
7464 this.$input
.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
7465 this.updateItemVisibility();
7468 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyPressListener
.call( this );
7475 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyPressListener = function () {
7476 if ( this.$input
) {
7477 if ( this.filterFromInput
) {
7478 this.$input
.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
7479 this.updateItemVisibility();
7482 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyPressListener
.call( this );
7489 * When a user chooses an item, the menu is closed, unless the hideOnChoose config option is set to false.
7491 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
7492 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
7494 * @param {OO.ui.OptionWidget} item Item to choose
7497 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
7498 OO
.ui
.MenuSelectWidget
.parent
.prototype.chooseItem
.call( this, item
);
7499 if ( this.hideOnChoose
) {
7500 this.toggle( false );
7508 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
7510 OO
.ui
.MenuSelectWidget
.parent
.prototype.addItems
.call( this, items
, index
);
7512 this.updateItemVisibility();
7520 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
7522 OO
.ui
.MenuSelectWidget
.parent
.prototype.removeItems
.call( this, items
);
7524 this.updateItemVisibility();
7532 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
7534 OO
.ui
.MenuSelectWidget
.parent
.prototype.clearItems
.call( this );
7536 this.updateItemVisibility();
7542 * Toggle visibility of the menu. The menu is initially hidden and must be shown by calling
7543 * `.toggle( true )` after its #$element is attached to the DOM.
7545 * Do not show the menu while it is not attached to the DOM. The calculations required to display
7546 * it in the right place and with the right dimensions only work correctly while it is attached.
7547 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
7548 * strictly enforced, so currently it only generates a warning in the browser console.
7553 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
7554 var change
, belowHeight
, aboveHeight
;
7556 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
7557 change
= visible
!== this.isVisible();
7559 if ( visible
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
7560 OO
.ui
.warnDeprecation( 'MenuSelectWidget#toggle: Before calling this method, the menu must be attached to the DOM.' );
7561 this.warnedUnattached
= true;
7565 if ( visible
&& ( this.width
|| this.$floatableContainer
) ) {
7566 this.setIdealSize( this.width
|| this.$floatableContainer
.width() );
7569 // Reset position before showing the popup again. It's possible we no longer need to flip
7570 // (e.g. if the user scrolled).
7571 this.setVerticalPosition( 'below' );
7576 OO
.ui
.MenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
7580 this.togglePositioning( !!this.$floatableContainer
);
7581 this.toggleClipping( true );
7583 this.bindKeyDownListener();
7584 this.bindKeyPressListener();
7586 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
7587 // If opening the menu downwards causes it to be clipped, flip it to open upwards instead
7588 belowHeight
= this.$element
.height();
7589 this.setVerticalPosition( 'above' );
7590 if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
7591 // If opening upwards also causes it to be clipped, flip it to open in whichever direction
7592 // we have more space
7593 aboveHeight
= this.$element
.height();
7594 if ( aboveHeight
< belowHeight
) {
7595 this.setVerticalPosition( 'below' );
7599 // Note that we do not flip the menu's opening direction if the clipping changes
7600 // later (e.g. after the user scrolls), that seems like it would be annoying
7602 this.$focusOwner
.attr( 'aria-expanded', 'true' );
7604 if ( this.findSelectedItem() ) {
7605 this.$focusOwner
.attr( 'aria-activedescendant', this.findSelectedItem().getElementId() );
7606 this.findSelectedItem().scrollElementIntoView( { duration
: 0 } );
7610 if ( this.autoHide
) {
7611 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
7614 this.emit( 'ready' );
7616 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
7617 this.unbindKeyDownListener();
7618 this.unbindKeyPressListener();
7619 this.$focusOwner
.attr( 'aria-expanded', 'false' );
7620 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
7621 this.togglePositioning( false );
7622 this.toggleClipping( false );
7630 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
7631 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
7632 * users can interact with it.
7634 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7635 * OO.ui.DropdownInputWidget instead.
7638 * // Example: A DropdownWidget with a menu that contains three options
7639 * var dropDown = new OO.ui.DropdownWidget( {
7640 * label: 'Dropdown menu: Select a menu option',
7643 * new OO.ui.MenuOptionWidget( {
7647 * new OO.ui.MenuOptionWidget( {
7651 * new OO.ui.MenuOptionWidget( {
7659 * $( 'body' ).append( dropDown.$element );
7661 * dropDown.getMenu().selectItemByData( 'b' );
7663 * dropDown.getMenu().findSelectedItem().getData(); // returns 'b'
7665 * For more information, please see the [OOUI documentation on MediaWiki] [1].
7667 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
7670 * @extends OO.ui.Widget
7671 * @mixins OO.ui.mixin.IconElement
7672 * @mixins OO.ui.mixin.IndicatorElement
7673 * @mixins OO.ui.mixin.LabelElement
7674 * @mixins OO.ui.mixin.TitledElement
7675 * @mixins OO.ui.mixin.TabIndexedElement
7678 * @param {Object} [config] Configuration options
7679 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.MenuSelectWidget menu select widget}
7680 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
7681 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
7682 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
7683 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
7685 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
7686 // Configuration initialization
7687 config
= $.extend( { indicator
: 'down' }, config
);
7689 // Parent constructor
7690 OO
.ui
.DropdownWidget
.parent
.call( this, config
);
7692 // Properties (must be set before TabIndexedElement constructor call)
7693 this.$handle
= $( '<span>' );
7694 this.$overlay
= ( config
.$overlay
=== true ? OO
.ui
.getDefaultOverlay() : config
.$overlay
) || this.$element
;
7696 // Mixin constructors
7697 OO
.ui
.mixin
.IconElement
.call( this, config
);
7698 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
7699 OO
.ui
.mixin
.LabelElement
.call( this, config
);
7700 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
7701 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
7704 this.menu
= new OO
.ui
.MenuSelectWidget( $.extend( {
7706 $floatableContainer
: this.$element
7711 click
: this.onClick
.bind( this ),
7712 keydown
: this.onKeyDown
.bind( this ),
7713 // Hack? Handle type-to-search when menu is not expanded and not handling its own events
7714 keypress
: this.menu
.onKeyPressHandler
,
7715 blur
: this.menu
.clearKeyPressBuffer
.bind( this.menu
)
7717 this.menu
.connect( this, {
7718 select
: 'onMenuSelect',
7719 toggle
: 'onMenuToggle'
7724 .addClass( 'oo-ui-dropdownWidget-handle' )
7727 'aria-owns': this.menu
.getElementId(),
7728 'aria-autocomplete': 'list'
7730 .append( this.$icon
, this.$label
, this.$indicator
);
7732 .addClass( 'oo-ui-dropdownWidget' )
7733 .append( this.$handle
);
7734 this.$overlay
.append( this.menu
.$element
);
7739 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
7740 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IconElement
);
7741 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IndicatorElement
);
7742 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.LabelElement
);
7743 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TitledElement
);
7744 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TabIndexedElement
);
7751 * @return {OO.ui.MenuSelectWidget} Menu of widget
7753 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
7758 * Handles menu select events.
7761 * @param {OO.ui.MenuOptionWidget} item Selected menu item
7763 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
7767 this.setLabel( null );
7771 selectedLabel
= item
.getLabel();
7773 // If the label is a DOM element, clone it, because setLabel will append() it
7774 if ( selectedLabel
instanceof jQuery
) {
7775 selectedLabel
= selectedLabel
.clone();
7778 this.setLabel( selectedLabel
);
7782 * Handle menu toggle events.
7785 * @param {boolean} isVisible Open state of the menu
7787 OO
.ui
.DropdownWidget
.prototype.onMenuToggle = function ( isVisible
) {
7788 this.$element
.toggleClass( 'oo-ui-dropdownWidget-open', isVisible
);
7791 this.$element
.hasClass( 'oo-ui-dropdownWidget-open' ).toString()
7796 * Handle mouse click events.
7799 * @param {jQuery.Event} e Mouse click event
7801 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
7802 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
7809 * Handle key down events.
7812 * @param {jQuery.Event} e Key down event
7814 OO
.ui
.DropdownWidget
.prototype.onKeyDown = function ( e
) {
7816 !this.isDisabled() &&
7818 e
.which
=== OO
.ui
.Keys
.ENTER
||
7820 e
.which
=== OO
.ui
.Keys
.SPACE
&&
7821 // Avoid conflicts with type-to-search, see SelectWidget#onKeyPress.
7822 // Space only closes the menu is the user is not typing to search.
7823 this.menu
.keyPressBuffer
=== ''
7826 !this.menu
.isVisible() &&
7828 e
.which
=== OO
.ui
.Keys
.UP
||
7829 e
.which
=== OO
.ui
.Keys
.DOWN
7840 * RadioOptionWidget is an option widget that looks like a radio button.
7841 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
7842 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
7844 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
7847 * @extends OO.ui.OptionWidget
7850 * @param {Object} [config] Configuration options
7852 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
7853 // Configuration initialization
7854 config
= config
|| {};
7856 // Properties (must be done before parent constructor which calls #setDisabled)
7857 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
7859 // Parent constructor
7860 OO
.ui
.RadioOptionWidget
.parent
.call( this, config
);
7863 // Remove implicit role, we're handling it ourselves
7864 this.radio
.$input
.attr( 'role', 'presentation' );
7866 .addClass( 'oo-ui-radioOptionWidget' )
7867 .attr( 'role', 'radio' )
7868 .attr( 'aria-checked', 'false' )
7869 .removeAttr( 'aria-selected' )
7870 .prepend( this.radio
.$element
);
7875 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
7877 /* Static Properties */
7883 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
7889 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
7895 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
7901 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
7908 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
7909 OO
.ui
.RadioOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
7911 this.radio
.setSelected( state
);
7913 .attr( 'aria-checked', state
.toString() )
7914 .removeAttr( 'aria-selected' );
7922 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
7923 OO
.ui
.RadioOptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
7925 this.radio
.setDisabled( this.isDisabled() );
7931 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
7932 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
7933 * an interface for adding, removing and selecting options.
7934 * Please see the [OOUI documentation on MediaWiki][1] for more information.
7936 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7937 * OO.ui.RadioSelectInputWidget instead.
7940 * // A RadioSelectWidget with RadioOptions.
7941 * var option1 = new OO.ui.RadioOptionWidget( {
7943 * label: 'Selected radio option'
7946 * var option2 = new OO.ui.RadioOptionWidget( {
7948 * label: 'Unselected radio option'
7951 * var radioSelect=new OO.ui.RadioSelectWidget( {
7952 * items: [ option1, option2 ]
7955 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
7956 * radioSelect.selectItem( option1 );
7958 * $( 'body' ).append( radioSelect.$element );
7960 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
7964 * @extends OO.ui.SelectWidget
7965 * @mixins OO.ui.mixin.TabIndexedElement
7968 * @param {Object} [config] Configuration options
7970 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
7971 // Parent constructor
7972 OO
.ui
.RadioSelectWidget
.parent
.call( this, config
);
7974 // Mixin constructors
7975 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
7979 focus
: this.bindKeyDownListener
.bind( this ),
7980 blur
: this.unbindKeyDownListener
.bind( this )
7985 .addClass( 'oo-ui-radioSelectWidget' )
7986 .attr( 'role', 'radiogroup' );
7991 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
7992 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
7995 * MultioptionWidgets are special elements that can be selected and configured with data. The
7996 * data is often unique for each option, but it does not have to be. MultioptionWidgets are used
7997 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
7998 * and examples, please see the [OOUI documentation on MediaWiki][1].
8000 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Multioptions
8003 * @extends OO.ui.Widget
8004 * @mixins OO.ui.mixin.ItemWidget
8005 * @mixins OO.ui.mixin.LabelElement
8008 * @param {Object} [config] Configuration options
8009 * @cfg {boolean} [selected=false] Whether the option is initially selected
8011 OO
.ui
.MultioptionWidget
= function OoUiMultioptionWidget( config
) {
8012 // Configuration initialization
8013 config
= config
|| {};
8015 // Parent constructor
8016 OO
.ui
.MultioptionWidget
.parent
.call( this, config
);
8018 // Mixin constructors
8019 OO
.ui
.mixin
.ItemWidget
.call( this );
8020 OO
.ui
.mixin
.LabelElement
.call( this, config
);
8023 this.selected
= null;
8027 .addClass( 'oo-ui-multioptionWidget' )
8028 .append( this.$label
);
8029 this.setSelected( config
.selected
);
8034 OO
.inheritClass( OO
.ui
.MultioptionWidget
, OO
.ui
.Widget
);
8035 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.ItemWidget
);
8036 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.LabelElement
);
8043 * A change event is emitted when the selected state of the option changes.
8045 * @param {boolean} selected Whether the option is now selected
8051 * Check if the option is selected.
8053 * @return {boolean} Item is selected
8055 OO
.ui
.MultioptionWidget
.prototype.isSelected = function () {
8056 return this.selected
;
8060 * Set the option’s selected state. In general, all modifications to the selection
8061 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
8062 * method instead of this method.
8064 * @param {boolean} [state=false] Select option
8067 OO
.ui
.MultioptionWidget
.prototype.setSelected = function ( state
) {
8069 if ( this.selected
!== state
) {
8070 this.selected
= state
;
8071 this.emit( 'change', state
);
8072 this.$element
.toggleClass( 'oo-ui-multioptionWidget-selected', state
);
8078 * MultiselectWidget allows selecting multiple options from a list.
8080 * For more information about menus and options, please see the [OOUI documentation on MediaWiki][1].
8082 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
8086 * @extends OO.ui.Widget
8087 * @mixins OO.ui.mixin.GroupWidget
8090 * @param {Object} [config] Configuration options
8091 * @cfg {OO.ui.MultioptionWidget[]} [items] An array of options to add to the multiselect.
8093 OO
.ui
.MultiselectWidget
= function OoUiMultiselectWidget( config
) {
8094 // Parent constructor
8095 OO
.ui
.MultiselectWidget
.parent
.call( this, config
);
8097 // Configuration initialization
8098 config
= config
|| {};
8100 // Mixin constructors
8101 OO
.ui
.mixin
.GroupWidget
.call( this, config
);
8104 this.aggregate( { change
: 'select' } );
8105 // This is mostly for compatibility with CapsuleMultiselectWidget... normally, 'change' is emitted
8106 // by GroupElement only when items are added/removed
8107 this.connect( this, { select
: [ 'emit', 'change' ] } );
8110 if ( config
.items
) {
8111 this.addItems( config
.items
);
8113 this.$group
.addClass( 'oo-ui-multiselectWidget-group' );
8114 this.$element
.addClass( 'oo-ui-multiselectWidget' )
8115 .append( this.$group
);
8120 OO
.inheritClass( OO
.ui
.MultiselectWidget
, OO
.ui
.Widget
);
8121 OO
.mixinClass( OO
.ui
.MultiselectWidget
, OO
.ui
.mixin
.GroupWidget
);
8128 * A change event is emitted when the set of items changes, or an item is selected or deselected.
8134 * A select event is emitted when an item is selected or deselected.
8140 * Find options that are selected.
8142 * @return {OO.ui.MultioptionWidget[]} Selected options
8144 OO
.ui
.MultiselectWidget
.prototype.findSelectedItems = function () {
8145 return this.items
.filter( function ( item
) {
8146 return item
.isSelected();
8151 * Find the data of options that are selected.
8153 * @return {Object[]|string[]} Values of selected options
8155 OO
.ui
.MultiselectWidget
.prototype.findSelectedItemsData = function () {
8156 return this.findSelectedItems().map( function ( item
) {
8162 * Select options by reference. Options not mentioned in the `items` array will be deselected.
8164 * @param {OO.ui.MultioptionWidget[]} items Items to select
8167 OO
.ui
.MultiselectWidget
.prototype.selectItems = function ( items
) {
8168 this.items
.forEach( function ( item
) {
8169 var selected
= items
.indexOf( item
) !== -1;
8170 item
.setSelected( selected
);
8176 * Select items by their data. Options not mentioned in the `datas` array will be deselected.
8178 * @param {Object[]|string[]} datas Values of items to select
8181 OO
.ui
.MultiselectWidget
.prototype.selectItemsByData = function ( datas
) {
8184 items
= datas
.map( function ( data
) {
8185 return widget
.findItemFromData( data
);
8187 this.selectItems( items
);
8192 * CheckboxMultioptionWidget is an option widget that looks like a checkbox.
8193 * The class is used with OO.ui.CheckboxMultiselectWidget to create a selection of checkbox options.
8194 * Please see the [OOUI documentation on MediaWiki] [1] for more information.
8196 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_option
8199 * @extends OO.ui.MultioptionWidget
8202 * @param {Object} [config] Configuration options
8204 OO
.ui
.CheckboxMultioptionWidget
= function OoUiCheckboxMultioptionWidget( config
) {
8205 // Configuration initialization
8206 config
= config
|| {};
8208 // Properties (must be done before parent constructor which calls #setDisabled)
8209 this.checkbox
= new OO
.ui
.CheckboxInputWidget();
8211 // Parent constructor
8212 OO
.ui
.CheckboxMultioptionWidget
.parent
.call( this, config
);
8215 this.checkbox
.on( 'change', this.onCheckboxChange
.bind( this ) );
8216 this.$element
.on( 'keydown', this.onKeyDown
.bind( this ) );
8220 .addClass( 'oo-ui-checkboxMultioptionWidget' )
8221 .prepend( this.checkbox
.$element
);
8226 OO
.inheritClass( OO
.ui
.CheckboxMultioptionWidget
, OO
.ui
.MultioptionWidget
);
8228 /* Static Properties */
8234 OO
.ui
.CheckboxMultioptionWidget
.static.tagName
= 'label';
8239 * Handle checkbox selected state change.
8243 OO
.ui
.CheckboxMultioptionWidget
.prototype.onCheckboxChange = function () {
8244 this.setSelected( this.checkbox
.isSelected() );
8250 OO
.ui
.CheckboxMultioptionWidget
.prototype.setSelected = function ( state
) {
8251 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setSelected
.call( this, state
);
8252 this.checkbox
.setSelected( state
);
8259 OO
.ui
.CheckboxMultioptionWidget
.prototype.setDisabled = function ( disabled
) {
8260 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
8261 this.checkbox
.setDisabled( this.isDisabled() );
8268 OO
.ui
.CheckboxMultioptionWidget
.prototype.focus = function () {
8269 this.checkbox
.focus();
8273 * Handle key down events.
8276 * @param {jQuery.Event} e
8278 OO
.ui
.CheckboxMultioptionWidget
.prototype.onKeyDown = function ( e
) {
8280 element
= this.getElementGroup(),
8283 if ( e
.keyCode
=== OO
.ui
.Keys
.LEFT
|| e
.keyCode
=== OO
.ui
.Keys
.UP
) {
8284 nextItem
= element
.getRelativeFocusableItem( this, -1 );
8285 } else if ( e
.keyCode
=== OO
.ui
.Keys
.RIGHT
|| e
.keyCode
=== OO
.ui
.Keys
.DOWN
) {
8286 nextItem
= element
.getRelativeFocusableItem( this, 1 );
8296 * CheckboxMultiselectWidget is a {@link OO.ui.MultiselectWidget multiselect widget} that contains
8297 * checkboxes and is used together with OO.ui.CheckboxMultioptionWidget. The
8298 * CheckboxMultiselectWidget provides an interface for adding, removing and selecting options.
8299 * Please see the [OOUI documentation on MediaWiki][1] for more information.
8301 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
8302 * OO.ui.CheckboxMultiselectInputWidget instead.
8305 * // A CheckboxMultiselectWidget with CheckboxMultioptions.
8306 * var option1 = new OO.ui.CheckboxMultioptionWidget( {
8309 * label: 'Selected checkbox'
8312 * var option2 = new OO.ui.CheckboxMultioptionWidget( {
8314 * label: 'Unselected checkbox'
8317 * var multiselect=new OO.ui.CheckboxMultiselectWidget( {
8318 * items: [ option1, option2 ]
8321 * $( 'body' ).append( multiselect.$element );
8323 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
8326 * @extends OO.ui.MultiselectWidget
8329 * @param {Object} [config] Configuration options
8331 OO
.ui
.CheckboxMultiselectWidget
= function OoUiCheckboxMultiselectWidget( config
) {
8332 // Parent constructor
8333 OO
.ui
.CheckboxMultiselectWidget
.parent
.call( this, config
);
8336 this.$lastClicked
= null;
8339 this.$group
.on( 'click', this.onClick
.bind( this ) );
8343 .addClass( 'oo-ui-checkboxMultiselectWidget' );
8348 OO
.inheritClass( OO
.ui
.CheckboxMultiselectWidget
, OO
.ui
.MultiselectWidget
);
8353 * Get an option by its position relative to the specified item (or to the start of the option array,
8354 * if item is `null`). The direction in which to search through the option array is specified with a
8355 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
8356 * `null` if there are no options in the array.
8358 * @param {OO.ui.CheckboxMultioptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
8359 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
8360 * @return {OO.ui.CheckboxMultioptionWidget|null} Item at position, `null` if there are no items in the select
8362 OO
.ui
.CheckboxMultiselectWidget
.prototype.getRelativeFocusableItem = function ( item
, direction
) {
8363 var currentIndex
, nextIndex
, i
,
8364 increase
= direction
> 0 ? 1 : -1,
8365 len
= this.items
.length
;
8368 currentIndex
= this.items
.indexOf( item
);
8369 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
8371 // If no item is selected and moving forward, start at the beginning.
8372 // If moving backward, start at the end.
8373 nextIndex
= direction
> 0 ? 0 : len
- 1;
8376 for ( i
= 0; i
< len
; i
++ ) {
8377 item
= this.items
[ nextIndex
];
8378 if ( item
&& !item
.isDisabled() ) {
8381 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
8387 * Handle click events on checkboxes.
8389 * @param {jQuery.Event} e
8391 OO
.ui
.CheckboxMultiselectWidget
.prototype.onClick = function ( e
) {
8392 var $options
, lastClickedIndex
, nowClickedIndex
, i
, direction
, wasSelected
, items
,
8393 $lastClicked
= this.$lastClicked
,
8394 $nowClicked
= $( e
.target
).closest( '.oo-ui-checkboxMultioptionWidget' )
8395 .not( '.oo-ui-widget-disabled' );
8397 // Allow selecting multiple options at once by Shift-clicking them
8398 if ( $lastClicked
&& $nowClicked
.length
&& e
.shiftKey
) {
8399 $options
= this.$group
.find( '.oo-ui-checkboxMultioptionWidget' );
8400 lastClickedIndex
= $options
.index( $lastClicked
);
8401 nowClickedIndex
= $options
.index( $nowClicked
);
8402 // If it's the same item, either the user is being silly, or it's a fake event generated by the
8403 // browser. In either case we don't need custom handling.
8404 if ( nowClickedIndex
!== lastClickedIndex
) {
8406 wasSelected
= items
[ nowClickedIndex
].isSelected();
8407 direction
= nowClickedIndex
> lastClickedIndex
? 1 : -1;
8409 // This depends on the DOM order of the items and the order of the .items array being the same.
8410 for ( i
= lastClickedIndex
; i
!== nowClickedIndex
; i
+= direction
) {
8411 if ( !items
[ i
].isDisabled() ) {
8412 items
[ i
].setSelected( !wasSelected
);
8415 // For the now-clicked element, use immediate timeout to allow the browser to do its own
8416 // handling first, then set our value. The order in which events happen is different for
8417 // clicks on the <input> and on the <label> and there are additional fake clicks fired for
8418 // non-click actions that change the checkboxes.
8420 setTimeout( function () {
8421 if ( !items
[ nowClickedIndex
].isDisabled() ) {
8422 items
[ nowClickedIndex
].setSelected( !wasSelected
);
8428 if ( $nowClicked
.length
) {
8429 this.$lastClicked
= $nowClicked
;
8438 OO
.ui
.CheckboxMultiselectWidget
.prototype.focus = function () {
8440 if ( !this.isDisabled() ) {
8441 item
= this.getRelativeFocusableItem( null, 1 );
8452 OO
.ui
.CheckboxMultiselectWidget
.prototype.simulateLabelClick = function () {
8457 * Progress bars visually display the status of an operation, such as a download,
8458 * and can be either determinate or indeterminate:
8460 * - **determinate** process bars show the percent of an operation that is complete.
8462 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
8463 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
8464 * not use percentages.
8466 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
8469 * // Examples of determinate and indeterminate progress bars.
8470 * var progressBar1 = new OO.ui.ProgressBarWidget( {
8473 * var progressBar2 = new OO.ui.ProgressBarWidget();
8475 * // Create a FieldsetLayout to layout progress bars
8476 * var fieldset = new OO.ui.FieldsetLayout;
8477 * fieldset.addItems( [
8478 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
8479 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
8481 * $( 'body' ).append( fieldset.$element );
8484 * @extends OO.ui.Widget
8487 * @param {Object} [config] Configuration options
8488 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
8489 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
8490 * By default, the progress bar is indeterminate.
8492 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
8493 // Configuration initialization
8494 config
= config
|| {};
8496 // Parent constructor
8497 OO
.ui
.ProgressBarWidget
.parent
.call( this, config
);
8500 this.$bar
= $( '<div>' );
8501 this.progress
= null;
8504 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
8505 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
8508 role
: 'progressbar',
8510 'aria-valuemax': 100
8512 .addClass( 'oo-ui-progressBarWidget' )
8513 .append( this.$bar
);
8518 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
8520 /* Static Properties */
8526 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
8531 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
8533 * @return {number|boolean} Progress percent
8535 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
8536 return this.progress
;
8540 * Set the percent of the process completed or `false` for an indeterminate process.
8542 * @param {number|boolean} progress Progress percent or `false` for indeterminate
8544 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
8545 this.progress
= progress
;
8547 if ( progress
!== false ) {
8548 this.$bar
.css( 'width', this.progress
+ '%' );
8549 this.$element
.attr( 'aria-valuenow', this.progress
);
8551 this.$bar
.css( 'width', '' );
8552 this.$element
.removeAttr( 'aria-valuenow' );
8554 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', progress
=== false );
8558 * InputWidget is the base class for all input widgets, which
8559 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
8560 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
8561 * See the [OOUI documentation on MediaWiki] [1] for more information and examples.
8563 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
8567 * @extends OO.ui.Widget
8568 * @mixins OO.ui.mixin.FlaggedElement
8569 * @mixins OO.ui.mixin.TabIndexedElement
8570 * @mixins OO.ui.mixin.TitledElement
8571 * @mixins OO.ui.mixin.AccessKeyedElement
8574 * @param {Object} [config] Configuration options
8575 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
8576 * @cfg {string} [value=''] The value of the input.
8577 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
8578 * @cfg {string} [inputId] The value of the input’s HTML `id` attribute.
8579 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
8580 * before it is accepted.
8582 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
8583 // Configuration initialization
8584 config
= config
|| {};
8586 // Parent constructor
8587 OO
.ui
.InputWidget
.parent
.call( this, config
);
8590 // See #reusePreInfuseDOM about config.$input
8591 this.$input
= config
.$input
|| this.getInputElement( config
);
8593 this.inputFilter
= config
.inputFilter
;
8595 // Mixin constructors
8596 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
8597 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
8598 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
8599 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$input
} ) );
8602 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
8606 .addClass( 'oo-ui-inputWidget-input' )
8607 .attr( 'name', config
.name
)
8608 .prop( 'disabled', this.isDisabled() );
8610 .addClass( 'oo-ui-inputWidget' )
8611 .append( this.$input
);
8612 this.setValue( config
.value
);
8614 this.setDir( config
.dir
);
8616 if ( config
.inputId
!== undefined ) {
8617 this.setInputId( config
.inputId
);
8623 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
8624 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.FlaggedElement
);
8625 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TabIndexedElement
);
8626 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TitledElement
);
8627 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
8629 /* Static Methods */
8634 OO
.ui
.InputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
8635 config
= OO
.ui
.InputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
8636 // Reusing `$input` lets browsers preserve inputted values across page reloads, see T114134.
8637 config
.$input
= $( node
).find( '.oo-ui-inputWidget-input' );
8644 OO
.ui
.InputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8645 var state
= OO
.ui
.InputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8646 if ( config
.$input
&& config
.$input
.length
) {
8647 state
.value
= config
.$input
.val();
8648 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
8649 state
.focus
= config
.$input
.is( ':focus' );
8659 * A change event is emitted when the value of the input changes.
8661 * @param {string} value
8667 * Get input element.
8669 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
8670 * different circumstances. The element must have a `value` property (like form elements).
8673 * @param {Object} config Configuration options
8674 * @return {jQuery} Input element
8676 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
8677 return $( '<input>' );
8681 * Handle potentially value-changing events.
8684 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
8686 OO
.ui
.InputWidget
.prototype.onEdit = function () {
8688 if ( !this.isDisabled() ) {
8689 // Allow the stack to clear so the value will be updated
8690 setTimeout( function () {
8691 widget
.setValue( widget
.$input
.val() );
8697 * Get the value of the input.
8699 * @return {string} Input value
8701 OO
.ui
.InputWidget
.prototype.getValue = function () {
8702 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
8703 // it, and we won't know unless they're kind enough to trigger a 'change' event.
8704 var value
= this.$input
.val();
8705 if ( this.value
!== value
) {
8706 this.setValue( value
);
8712 * Set the directionality of the input.
8714 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
8717 OO
.ui
.InputWidget
.prototype.setDir = function ( dir
) {
8718 this.$input
.prop( 'dir', dir
);
8723 * Set the value of the input.
8725 * @param {string} value New value
8729 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
8730 value
= this.cleanUpValue( value
);
8731 // Update the DOM if it has changed. Note that with cleanUpValue, it
8732 // is possible for the DOM value to change without this.value changing.
8733 if ( this.$input
.val() !== value
) {
8734 this.$input
.val( value
);
8736 if ( this.value
!== value
) {
8738 this.emit( 'change', this.value
);
8740 // The first time that the value is set (probably while constructing the widget),
8741 // remember it in defaultValue. This property can be later used to check whether
8742 // the value of the input has been changed since it was created.
8743 if ( this.defaultValue
=== undefined ) {
8744 this.defaultValue
= this.value
;
8745 this.$input
[ 0 ].defaultValue
= this.defaultValue
;
8751 * Clean up incoming value.
8753 * Ensures value is a string, and converts undefined and null to empty string.
8756 * @param {string} value Original value
8757 * @return {string} Cleaned up value
8759 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
8760 if ( value
=== undefined || value
=== null ) {
8762 } else if ( this.inputFilter
) {
8763 return this.inputFilter( String( value
) );
8765 return String( value
);
8772 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
8773 OO
.ui
.InputWidget
.parent
.prototype.setDisabled
.call( this, state
);
8774 if ( this.$input
) {
8775 this.$input
.prop( 'disabled', this.isDisabled() );
8781 * Set the 'id' attribute of the `<input>` element.
8783 * @param {string} id
8786 OO
.ui
.InputWidget
.prototype.setInputId = function ( id
) {
8787 this.$input
.attr( 'id', id
);
8794 OO
.ui
.InputWidget
.prototype.restorePreInfuseState = function ( state
) {
8795 OO
.ui
.InputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
8796 if ( state
.value
!== undefined && state
.value
!== this.getValue() ) {
8797 this.setValue( state
.value
);
8799 if ( state
.focus
) {
8805 * Data widget intended for creating 'hidden'-type inputs.
8808 * @extends OO.ui.Widget
8811 * @param {Object} [config] Configuration options
8812 * @cfg {string} [value=''] The value of the input.
8813 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
8815 OO
.ui
.HiddenInputWidget
= function OoUiHiddenInputWidget( config
) {
8816 // Configuration initialization
8817 config
= $.extend( { value
: '', name
: '' }, config
);
8819 // Parent constructor
8820 OO
.ui
.HiddenInputWidget
.parent
.call( this, config
);
8823 this.$element
.attr( {
8825 value
: config
.value
,
8828 this.$element
.removeAttr( 'aria-disabled' );
8833 OO
.inheritClass( OO
.ui
.HiddenInputWidget
, OO
.ui
.Widget
);
8835 /* Static Properties */
8841 OO
.ui
.HiddenInputWidget
.static.tagName
= 'input';
8844 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
8845 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
8846 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
8847 * HTML `<button>` (the default) or an HTML `<input>` tags. See the
8848 * [OOUI documentation on MediaWiki] [1] for more information.
8851 * // A ButtonInputWidget rendered as an HTML button, the default.
8852 * var button = new OO.ui.ButtonInputWidget( {
8853 * label: 'Input button',
8857 * $( 'body' ).append( button.$element );
8859 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs#Button_inputs
8862 * @extends OO.ui.InputWidget
8863 * @mixins OO.ui.mixin.ButtonElement
8864 * @mixins OO.ui.mixin.IconElement
8865 * @mixins OO.ui.mixin.IndicatorElement
8866 * @mixins OO.ui.mixin.LabelElement
8867 * @mixins OO.ui.mixin.TitledElement
8870 * @param {Object} [config] Configuration options
8871 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
8872 * @cfg {boolean} [useInputTag=false] Use an `<input>` tag instead of a `<button>` tag, the default.
8873 * Widgets configured to be an `<input>` do not support {@link #icon icons} and {@link #indicator indicators},
8874 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
8875 * be set to `true` when there’s need to support IE 6 in a form with multiple buttons.
8877 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
8878 // Configuration initialization
8879 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
8881 // See InputWidget#reusePreInfuseDOM about config.$input
8882 if ( config
.$input
) {
8883 config
.$input
.empty();
8886 // Properties (must be set before parent constructor, which calls #setValue)
8887 this.useInputTag
= config
.useInputTag
;
8889 // Parent constructor
8890 OO
.ui
.ButtonInputWidget
.parent
.call( this, config
);
8892 // Mixin constructors
8893 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
8894 OO
.ui
.mixin
.IconElement
.call( this, config
);
8895 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
8896 OO
.ui
.mixin
.LabelElement
.call( this, config
);
8897 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
8900 if ( !config
.useInputTag
) {
8901 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
8903 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
8908 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
8909 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.ButtonElement
);
8910 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IconElement
);
8911 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
8912 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.LabelElement
);
8913 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.TitledElement
);
8915 /* Static Properties */
8921 OO
.ui
.ButtonInputWidget
.static.tagName
= 'span';
8929 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
8931 type
= [ 'button', 'submit', 'reset' ].indexOf( config
.type
) !== -1 ? config
.type
: 'button';
8932 return $( '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + type
+ '">' );
8938 * If #useInputTag is `true`, the label is set as the `value` of the `<input>` tag.
8940 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
8941 * text, or `null` for no label
8944 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
8945 if ( typeof label
=== 'function' ) {
8946 label
= OO
.ui
.resolveMsg( label
);
8949 if ( this.useInputTag
) {
8950 // Discard non-plaintext labels
8951 if ( typeof label
!== 'string' ) {
8955 this.$input
.val( label
);
8958 return OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.call( this, label
);
8962 * Set the value of the input.
8964 * This method is disabled for button inputs configured as {@link #useInputTag <input> tags}, as
8965 * they do not support {@link #value values}.
8967 * @param {string} value New value
8970 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
8971 if ( !this.useInputTag
) {
8972 OO
.ui
.ButtonInputWidget
.parent
.prototype.setValue
.call( this, value
);
8980 OO
.ui
.ButtonInputWidget
.prototype.getInputId = function () {
8981 // Disable generating `<label>` elements for buttons. One would very rarely need additional label
8982 // for a button, and it's already a big clickable target, and it causes unexpected rendering.
8987 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
8988 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
8989 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
8990 * alignment. For more information, please see the [OOUI documentation on MediaWiki][1].
8992 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
8995 * // An example of selected, unselected, and disabled checkbox inputs
8996 * var checkbox1=new OO.ui.CheckboxInputWidget( {
9000 * var checkbox2=new OO.ui.CheckboxInputWidget( {
9003 * var checkbox3=new OO.ui.CheckboxInputWidget( {
9007 * // Create a fieldset layout with fields for each checkbox.
9008 * var fieldset = new OO.ui.FieldsetLayout( {
9009 * label: 'Checkboxes'
9011 * fieldset.addItems( [
9012 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
9013 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
9014 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
9016 * $( 'body' ).append( fieldset.$element );
9018 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9021 * @extends OO.ui.InputWidget
9024 * @param {Object} [config] Configuration options
9025 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
9027 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
9028 // Configuration initialization
9029 config
= config
|| {};
9031 // Parent constructor
9032 OO
.ui
.CheckboxInputWidget
.parent
.call( this, config
);
9035 this.checkIcon
= new OO
.ui
.IconWidget( {
9037 classes
: [ 'oo-ui-checkboxInputWidget-checkIcon' ]
9042 .addClass( 'oo-ui-checkboxInputWidget' )
9043 // Required for pretty styling in WikimediaUI theme
9044 .append( this.checkIcon
.$element
);
9045 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
9050 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
9052 /* Static Properties */
9058 OO
.ui
.CheckboxInputWidget
.static.tagName
= 'span';
9060 /* Static Methods */
9065 OO
.ui
.CheckboxInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9066 var state
= OO
.ui
.CheckboxInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9067 state
.checked
= config
.$input
.prop( 'checked' );
9077 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
9078 return $( '<input>' ).attr( 'type', 'checkbox' );
9084 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
9086 if ( !this.isDisabled() ) {
9087 // Allow the stack to clear so the value will be updated
9088 setTimeout( function () {
9089 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
9095 * Set selection state of this checkbox.
9097 * @param {boolean} state `true` for selected
9100 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
9102 if ( this.selected
!== state
) {
9103 this.selected
= state
;
9104 this.$input
.prop( 'checked', this.selected
);
9105 this.emit( 'change', this.selected
);
9107 // The first time that the selection state is set (probably while constructing the widget),
9108 // remember it in defaultSelected. This property can be later used to check whether
9109 // the selection state of the input has been changed since it was created.
9110 if ( this.defaultSelected
=== undefined ) {
9111 this.defaultSelected
= this.selected
;
9112 this.$input
[ 0 ].defaultChecked
= this.defaultSelected
;
9118 * Check if this checkbox is selected.
9120 * @return {boolean} Checkbox is selected
9122 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
9123 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
9124 // it, and we won't know unless they're kind enough to trigger a 'change' event.
9125 var selected
= this.$input
.prop( 'checked' );
9126 if ( this.selected
!== selected
) {
9127 this.setSelected( selected
);
9129 return this.selected
;
9135 OO
.ui
.CheckboxInputWidget
.prototype.simulateLabelClick = function () {
9136 if ( !this.isDisabled() ) {
9137 this.$input
.click();
9145 OO
.ui
.CheckboxInputWidget
.prototype.restorePreInfuseState = function ( state
) {
9146 OO
.ui
.CheckboxInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
9147 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
9148 this.setSelected( state
.checked
);
9153 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
9154 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
9155 * of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
9156 * more information about input widgets.
9158 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
9159 * are no options. If no `value` configuration option is provided, the first option is selected.
9160 * If you need a state representing no value (no option being selected), use a DropdownWidget.
9162 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
9165 * // Example: A DropdownInputWidget with three options
9166 * var dropdownInput = new OO.ui.DropdownInputWidget( {
9168 * { data: 'a', label: 'First' },
9169 * { data: 'b', label: 'Second'},
9170 * { data: 'c', label: 'Third' }
9173 * $( 'body' ).append( dropdownInput.$element );
9175 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9178 * @extends OO.ui.InputWidget
9181 * @param {Object} [config] Configuration options
9182 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
9183 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
9185 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
9186 // Configuration initialization
9187 config
= config
|| {};
9189 // Properties (must be done before parent constructor which calls #setDisabled)
9190 this.dropdownWidget
= new OO
.ui
.DropdownWidget( config
.dropdown
);
9191 // Set up the options before parent constructor, which uses them to validate config.value.
9192 // Use this instead of setOptions() because this.$input is not set up yet.
9193 this.setOptionsData( config
.options
|| [] );
9195 // Parent constructor
9196 OO
.ui
.DropdownInputWidget
.parent
.call( this, config
);
9199 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
9203 .addClass( 'oo-ui-dropdownInputWidget' )
9204 .append( this.dropdownWidget
.$element
);
9205 this.setTabIndexedElement( this.dropdownWidget
.$tabIndexed
);
9210 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
9218 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
9219 return $( '<select>' );
9223 * Handles menu select events.
9226 * @param {OO.ui.MenuOptionWidget|null} item Selected menu item
9228 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
9229 this.setValue( item
? item
.getData() : '' );
9235 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
9237 value
= this.cleanUpValue( value
);
9238 // Only allow setting values that are actually present in the dropdown
9239 selected
= this.dropdownWidget
.getMenu().findItemFromData( value
) ||
9240 this.dropdownWidget
.getMenu().findFirstSelectableItem();
9241 this.dropdownWidget
.getMenu().selectItem( selected
);
9242 value
= selected
? selected
.getData() : '';
9243 OO
.ui
.DropdownInputWidget
.parent
.prototype.setValue
.call( this, value
);
9244 if ( this.optionsDirty
) {
9245 // We reached this from the constructor or from #setOptions.
9246 // We have to update the <select> element.
9247 this.updateOptionsInterface();
9255 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
9256 this.dropdownWidget
.setDisabled( state
);
9257 OO
.ui
.DropdownInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
9262 * Set the options available for this input.
9264 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9267 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
9268 var value
= this.getValue();
9270 this.setOptionsData( options
);
9272 // Re-set the value to update the visible interface (DropdownWidget and <select>).
9273 // In case the previous value is no longer an available option, select the first valid one.
9274 this.setValue( value
);
9280 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
9282 * This method may be called before the parent constructor, so various properties may not be
9285 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9288 OO
.ui
.DropdownInputWidget
.prototype.setOptionsData = function ( options
) {
9293 this.optionsDirty
= true;
9295 optionWidgets
= options
.map( function ( opt
) {
9298 if ( opt
.optgroup
!== undefined ) {
9299 return widget
.createMenuSectionOptionWidget( opt
.optgroup
);
9302 optValue
= widget
.cleanUpValue( opt
.data
);
9303 return widget
.createMenuOptionWidget(
9305 opt
.label
!== undefined ? opt
.label
: optValue
9310 this.dropdownWidget
.getMenu().clearItems().addItems( optionWidgets
);
9314 * Create a menu option widget.
9317 * @param {string} data Item data
9318 * @param {string} label Item label
9319 * @return {OO.ui.MenuOptionWidget} Option widget
9321 OO
.ui
.DropdownInputWidget
.prototype.createMenuOptionWidget = function ( data
, label
) {
9322 return new OO
.ui
.MenuOptionWidget( {
9329 * Create a menu section option widget.
9332 * @param {string} label Section item label
9333 * @return {OO.ui.MenuSectionOptionWidget} Menu section option widget
9335 OO
.ui
.DropdownInputWidget
.prototype.createMenuSectionOptionWidget = function ( label
) {
9336 return new OO
.ui
.MenuSectionOptionWidget( {
9342 * Update the user-visible interface to match the internal list of options and value.
9344 * This method must only be called after the parent constructor.
9348 OO
.ui
.DropdownInputWidget
.prototype.updateOptionsInterface = function () {
9350 $optionsContainer
= this.$input
,
9351 defaultValue
= this.defaultValue
,
9354 this.$input
.empty();
9356 this.dropdownWidget
.getMenu().getItems().forEach( function ( optionWidget
) {
9359 if ( !( optionWidget
instanceof OO
.ui
.MenuSectionOptionWidget
) ) {
9360 $optionNode
= $( '<option>' )
9361 .attr( 'value', optionWidget
.getData() )
9362 .text( optionWidget
.getLabel() );
9364 // Remember original selection state. This property can be later used to check whether
9365 // the selection state of the input has been changed since it was created.
9366 $optionNode
[ 0 ].defaultSelected
= ( optionWidget
.getData() === defaultValue
);
9368 $optionsContainer
.append( $optionNode
);
9370 $optionNode
= $( '<optgroup>' )
9371 .attr( 'label', optionWidget
.getLabel() );
9372 widget
.$input
.append( $optionNode
);
9373 $optionsContainer
= $optionNode
;
9377 this.optionsDirty
= false;
9383 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
9384 this.dropdownWidget
.focus();
9391 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
9392 this.dropdownWidget
.blur();
9397 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
9398 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
9399 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
9400 * please see the [OOUI documentation on MediaWiki][1].
9402 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9405 * // An example of selected, unselected, and disabled radio inputs
9406 * var radio1 = new OO.ui.RadioInputWidget( {
9410 * var radio2 = new OO.ui.RadioInputWidget( {
9413 * var radio3 = new OO.ui.RadioInputWidget( {
9417 * // Create a fieldset layout with fields for each radio button.
9418 * var fieldset = new OO.ui.FieldsetLayout( {
9419 * label: 'Radio inputs'
9421 * fieldset.addItems( [
9422 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
9423 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
9424 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
9426 * $( 'body' ).append( fieldset.$element );
9428 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9431 * @extends OO.ui.InputWidget
9434 * @param {Object} [config] Configuration options
9435 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
9437 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
9438 // Configuration initialization
9439 config
= config
|| {};
9441 // Parent constructor
9442 OO
.ui
.RadioInputWidget
.parent
.call( this, config
);
9446 .addClass( 'oo-ui-radioInputWidget' )
9447 // Required for pretty styling in WikimediaUI theme
9448 .append( $( '<span>' ) );
9449 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
9454 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
9456 /* Static Properties */
9462 OO
.ui
.RadioInputWidget
.static.tagName
= 'span';
9464 /* Static Methods */
9469 OO
.ui
.RadioInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9470 var state
= OO
.ui
.RadioInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9471 state
.checked
= config
.$input
.prop( 'checked' );
9481 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
9482 return $( '<input>' ).attr( 'type', 'radio' );
9488 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
9489 // RadioInputWidget doesn't track its state.
9493 * Set selection state of this radio button.
9495 * @param {boolean} state `true` for selected
9498 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
9499 // RadioInputWidget doesn't track its state.
9500 this.$input
.prop( 'checked', state
);
9501 // The first time that the selection state is set (probably while constructing the widget),
9502 // remember it in defaultSelected. This property can be later used to check whether
9503 // the selection state of the input has been changed since it was created.
9504 if ( this.defaultSelected
=== undefined ) {
9505 this.defaultSelected
= state
;
9506 this.$input
[ 0 ].defaultChecked
= this.defaultSelected
;
9512 * Check if this radio button is selected.
9514 * @return {boolean} Radio is selected
9516 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
9517 return this.$input
.prop( 'checked' );
9523 OO
.ui
.RadioInputWidget
.prototype.simulateLabelClick = function () {
9524 if ( !this.isDisabled() ) {
9525 this.$input
.click();
9533 OO
.ui
.RadioInputWidget
.prototype.restorePreInfuseState = function ( state
) {
9534 OO
.ui
.RadioInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
9535 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
9536 this.setSelected( state
.checked
);
9541 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
9542 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
9543 * of a hidden HTML `input` tag. Please see the [OOUI documentation on MediaWiki][1] for
9544 * more information about input widgets.
9546 * This and OO.ui.DropdownInputWidget support the same configuration options.
9549 * // Example: A RadioSelectInputWidget with three options
9550 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
9552 * { data: 'a', label: 'First' },
9553 * { data: 'b', label: 'Second'},
9554 * { data: 'c', label: 'Third' }
9557 * $( 'body' ).append( radioSelectInput.$element );
9559 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9562 * @extends OO.ui.InputWidget
9565 * @param {Object} [config] Configuration options
9566 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
9568 OO
.ui
.RadioSelectInputWidget
= function OoUiRadioSelectInputWidget( config
) {
9569 // Configuration initialization
9570 config
= config
|| {};
9572 // Properties (must be done before parent constructor which calls #setDisabled)
9573 this.radioSelectWidget
= new OO
.ui
.RadioSelectWidget();
9574 // Set up the options before parent constructor, which uses them to validate config.value.
9575 // Use this instead of setOptions() because this.$input is not set up yet
9576 this.setOptionsData( config
.options
|| [] );
9578 // Parent constructor
9579 OO
.ui
.RadioSelectInputWidget
.parent
.call( this, config
);
9582 this.radioSelectWidget
.connect( this, { select
: 'onMenuSelect' } );
9586 .addClass( 'oo-ui-radioSelectInputWidget' )
9587 .append( this.radioSelectWidget
.$element
);
9588 this.setTabIndexedElement( this.radioSelectWidget
.$tabIndexed
);
9593 OO
.inheritClass( OO
.ui
.RadioSelectInputWidget
, OO
.ui
.InputWidget
);
9595 /* Static Methods */
9600 OO
.ui
.RadioSelectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9601 var state
= OO
.ui
.RadioSelectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9602 state
.value
= $( node
).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
9609 OO
.ui
.RadioSelectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
9610 config
= OO
.ui
.RadioSelectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
9611 // Cannot reuse the `<input type=radio>` set
9612 delete config
.$input
;
9622 OO
.ui
.RadioSelectInputWidget
.prototype.getInputElement = function () {
9623 // Use this instead of <input type="hidden">, because hidden inputs do not have separate
9624 // 'value' and 'defaultValue' properties, and InputWidget wants to handle 'defaultValue'.
9625 return $( '<input>' ).addClass( 'oo-ui-element-hidden' );
9629 * Handles menu select events.
9632 * @param {OO.ui.RadioOptionWidget} item Selected menu item
9634 OO
.ui
.RadioSelectInputWidget
.prototype.onMenuSelect = function ( item
) {
9635 this.setValue( item
.getData() );
9641 OO
.ui
.RadioSelectInputWidget
.prototype.setValue = function ( value
) {
9643 value
= this.cleanUpValue( value
);
9644 // Only allow setting values that are actually present in the dropdown
9645 selected
= this.radioSelectWidget
.findItemFromData( value
) ||
9646 this.radioSelectWidget
.findFirstSelectableItem();
9647 this.radioSelectWidget
.selectItem( selected
);
9648 value
= selected
? selected
.getData() : '';
9649 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setValue
.call( this, value
);
9656 OO
.ui
.RadioSelectInputWidget
.prototype.setDisabled = function ( state
) {
9657 this.radioSelectWidget
.setDisabled( state
);
9658 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
9663 * Set the options available for this input.
9665 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9668 OO
.ui
.RadioSelectInputWidget
.prototype.setOptions = function ( options
) {
9669 var value
= this.getValue();
9671 this.setOptionsData( options
);
9673 // Re-set the value to update the visible interface (RadioSelectWidget).
9674 // In case the previous value is no longer an available option, select the first valid one.
9675 this.setValue( value
);
9681 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
9683 * This method may be called before the parent constructor, so various properties may not be
9686 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9689 OO
.ui
.RadioSelectInputWidget
.prototype.setOptionsData = function ( options
) {
9692 this.radioSelectWidget
9694 .addItems( options
.map( function ( opt
) {
9695 var optValue
= widget
.cleanUpValue( opt
.data
);
9696 return new OO
.ui
.RadioOptionWidget( {
9698 label
: opt
.label
!== undefined ? opt
.label
: optValue
9706 OO
.ui
.RadioSelectInputWidget
.prototype.focus = function () {
9707 this.radioSelectWidget
.focus();
9714 OO
.ui
.RadioSelectInputWidget
.prototype.blur = function () {
9715 this.radioSelectWidget
.blur();
9720 * CheckboxMultiselectInputWidget is a
9721 * {@link OO.ui.CheckboxMultiselectWidget CheckboxMultiselectWidget} intended to be used within a
9722 * HTML form, such as a OO.ui.FormLayout. The selected values are synchronized with the value of
9723 * HTML `<input type=checkbox>` tags. Please see the [OOUI documentation on MediaWiki][1] for
9724 * more information about input widgets.
9727 * // Example: A CheckboxMultiselectInputWidget with three options
9728 * var multiselectInput = new OO.ui.CheckboxMultiselectInputWidget( {
9730 * { data: 'a', label: 'First' },
9731 * { data: 'b', label: 'Second'},
9732 * { data: 'c', label: 'Third' }
9735 * $( 'body' ).append( multiselectInput.$element );
9737 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9740 * @extends OO.ui.InputWidget
9743 * @param {Object} [config] Configuration options
9744 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: …, disabled: … }`
9746 OO
.ui
.CheckboxMultiselectInputWidget
= function OoUiCheckboxMultiselectInputWidget( config
) {
9747 // Configuration initialization
9748 config
= config
|| {};
9750 // Properties (must be done before parent constructor which calls #setDisabled)
9751 this.checkboxMultiselectWidget
= new OO
.ui
.CheckboxMultiselectWidget();
9752 // Must be set before the #setOptionsData call below
9753 this.inputName
= config
.name
;
9754 // Set up the options before parent constructor, which uses them to validate config.value.
9755 // Use this instead of setOptions() because this.$input is not set up yet
9756 this.setOptionsData( config
.options
|| [] );
9758 // Parent constructor
9759 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.call( this, config
);
9762 this.checkboxMultiselectWidget
.connect( this, { select
: 'onCheckboxesSelect' } );
9766 .addClass( 'oo-ui-checkboxMultiselectInputWidget' )
9767 .append( this.checkboxMultiselectWidget
.$element
);
9768 // We don't use this.$input, but rather the CheckboxInputWidgets inside each option
9769 this.$input
.detach();
9774 OO
.inheritClass( OO
.ui
.CheckboxMultiselectInputWidget
, OO
.ui
.InputWidget
);
9776 /* Static Methods */
9781 OO
.ui
.CheckboxMultiselectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9782 var state
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9783 state
.value
= $( node
).find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
9784 .toArray().map( function ( el
) { return el
.value
; } );
9791 OO
.ui
.CheckboxMultiselectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
9792 config
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
9793 // Cannot reuse the `<input type=checkbox>` set
9794 delete config
.$input
;
9804 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getInputElement = function () {
9806 return $( '<unused>' );
9810 * Handles CheckboxMultiselectWidget select events.
9814 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.onCheckboxesSelect = function () {
9815 this.setValue( this.checkboxMultiselectWidget
.findSelectedItemsData() );
9821 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getValue = function () {
9822 var value
= this.$element
.find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
9823 .toArray().map( function ( el
) { return el
.value
; } );
9824 if ( this.value
!== value
) {
9825 this.setValue( value
);
9833 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setValue = function ( value
) {
9834 value
= this.cleanUpValue( value
);
9835 this.checkboxMultiselectWidget
.selectItemsByData( value
);
9836 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setValue
.call( this, value
);
9837 if ( this.optionsDirty
) {
9838 // We reached this from the constructor or from #setOptions.
9839 // We have to update the <select> element.
9840 this.updateOptionsInterface();
9846 * Clean up incoming value.
9848 * @param {string[]} value Original value
9849 * @return {string[]} Cleaned up value
9851 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.cleanUpValue = function ( value
) {
9854 if ( !Array
.isArray( value
) ) {
9857 for ( i
= 0; i
< value
.length
; i
++ ) {
9859 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
.call( this, value
[ i
] );
9860 // Remove options that we don't have here
9861 if ( !this.checkboxMultiselectWidget
.findItemFromData( singleValue
) ) {
9864 cleanValue
.push( singleValue
);
9872 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setDisabled = function ( state
) {
9873 this.checkboxMultiselectWidget
.setDisabled( state
);
9874 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
9879 * Set the options available for this input.
9881 * @param {Object[]} options Array of menu options in the format `{ data: …, label: …, disabled: … }`
9884 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setOptions = function ( options
) {
9885 var value
= this.getValue();
9887 this.setOptionsData( options
);
9889 // Re-set the value to update the visible interface (CheckboxMultiselectWidget).
9890 // This will also get rid of any stale options that we just removed.
9891 this.setValue( value
);
9897 * Set the internal list of options, used e.g. by setValue() to see which options are allowed.
9899 * This method may be called before the parent constructor, so various properties may not be
9902 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9905 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setOptionsData = function ( options
) {
9908 this.optionsDirty
= true;
9910 this.checkboxMultiselectWidget
9912 .addItems( options
.map( function ( opt
) {
9913 var optValue
, item
, optDisabled
;
9915 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
.call( widget
, opt
.data
);
9916 optDisabled
= opt
.disabled
!== undefined ? opt
.disabled
: false;
9917 item
= new OO
.ui
.CheckboxMultioptionWidget( {
9919 label
: opt
.label
!== undefined ? opt
.label
: optValue
,
9920 disabled
: optDisabled
9922 // Set the 'name' and 'value' for form submission
9923 item
.checkbox
.$input
.attr( 'name', widget
.inputName
);
9924 item
.checkbox
.setValue( optValue
);
9930 * Update the user-visible interface to match the internal list of options and value.
9932 * This method must only be called after the parent constructor.
9936 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.updateOptionsInterface = function () {
9937 var defaultValue
= this.defaultValue
;
9939 this.checkboxMultiselectWidget
.getItems().forEach( function ( item
) {
9940 // Remember original selection state. This property can be later used to check whether
9941 // the selection state of the input has been changed since it was created.
9942 var isDefault
= defaultValue
.indexOf( item
.getData() ) !== -1;
9943 item
.checkbox
.defaultSelected
= isDefault
;
9944 item
.checkbox
.$input
[ 0 ].defaultChecked
= isDefault
;
9947 this.optionsDirty
= false;
9953 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.focus = function () {
9954 this.checkboxMultiselectWidget
.focus();
9959 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
9960 * size of the field as well as its presentation. In addition, these widgets can be configured
9961 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
9962 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
9963 * which modifies incoming values rather than validating them.
9964 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
9966 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9969 * // Example of a text input widget
9970 * var textInput = new OO.ui.TextInputWidget( {
9971 * value: 'Text input'
9973 * $( 'body' ).append( textInput.$element );
9975 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
9978 * @extends OO.ui.InputWidget
9979 * @mixins OO.ui.mixin.IconElement
9980 * @mixins OO.ui.mixin.IndicatorElement
9981 * @mixins OO.ui.mixin.PendingElement
9982 * @mixins OO.ui.mixin.LabelElement
9985 * @param {Object} [config] Configuration options
9986 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password'
9987 * 'email', 'url' or 'number'.
9988 * @cfg {string} [placeholder] Placeholder text
9989 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
9990 * instruct the browser to focus this widget.
9991 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
9992 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
9994 * For unfortunate historical reasons, this counts the number of UTF-16 code units rather than
9995 * Unicode codepoints, which means that codepoints outside the Basic Multilingual Plane (e.g.
9996 * many emojis) count as 2 characters each.
9997 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
9998 * the value or placeholder text: `'before'` or `'after'`
9999 * @cfg {boolean} [required=false] Mark the field as required with `true`. Implies `indicator: 'required'`.
10000 * Note that `false` & setting `indicator: 'required' will result in no indicator shown.
10001 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
10002 * @cfg {boolean} [spellcheck] Should the browser support spellcheck for this field (`undefined` means
10003 * leaving it up to the browser).
10004 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
10005 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
10006 * (the value must contain only numbers); when RegExp, a regular expression that must match the
10007 * value for it to be considered valid; when Function, a function receiving the value as parameter
10008 * that must return true, or promise resolving to true, for it to be considered valid.
10010 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
10011 // Configuration initialization
10012 config
= $.extend( {
10014 labelPosition
: 'after'
10017 if ( config
.multiline
) {
10018 OO
.ui
.warnDeprecation( 'TextInputWidget: config.multiline is deprecated. Use the MultilineTextInputWidget instead. See T130434.' );
10019 return new OO
.ui
.MultilineTextInputWidget( config
);
10022 // Parent constructor
10023 OO
.ui
.TextInputWidget
.parent
.call( this, config
);
10025 // Mixin constructors
10026 OO
.ui
.mixin
.IconElement
.call( this, config
);
10027 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
10028 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$input
} ) );
10029 OO
.ui
.mixin
.LabelElement
.call( this, config
);
10032 this.type
= this.getSaneType( config
);
10033 this.readOnly
= false;
10034 this.required
= false;
10035 this.validate
= null;
10036 this.styleHeight
= null;
10037 this.scrollWidth
= null;
10039 this.setValidation( config
.validate
);
10040 this.setLabelPosition( config
.labelPosition
);
10044 keypress
: this.onKeyPress
.bind( this ),
10045 blur
: this.onBlur
.bind( this ),
10046 focus
: this.onFocus
.bind( this )
10048 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
10049 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
10050 this.on( 'labelChange', this.updatePosition
.bind( this ) );
10051 this.on( 'change', OO
.ui
.debounce( this.onDebouncedChange
.bind( this ), 250 ) );
10055 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type
)
10056 .append( this.$icon
, this.$indicator
);
10057 this.setReadOnly( !!config
.readOnly
);
10058 this.setRequired( !!config
.required
);
10059 if ( config
.placeholder
!== undefined ) {
10060 this.$input
.attr( 'placeholder', config
.placeholder
);
10062 if ( config
.maxLength
!== undefined ) {
10063 this.$input
.attr( 'maxlength', config
.maxLength
);
10065 if ( config
.autofocus
) {
10066 this.$input
.attr( 'autofocus', 'autofocus' );
10068 if ( config
.autocomplete
=== false ) {
10069 this.$input
.attr( 'autocomplete', 'off' );
10070 // Turning off autocompletion also disables "form caching" when the user navigates to a
10071 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
10073 beforeunload: function () {
10074 this.$input
.removeAttr( 'autocomplete' );
10076 pageshow: function () {
10077 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
10078 // whole page... it shouldn't hurt, though.
10079 this.$input
.attr( 'autocomplete', 'off' );
10083 if ( config
.spellcheck
!== undefined ) {
10084 this.$input
.attr( 'spellcheck', config
.spellcheck
? 'true' : 'false' );
10086 if ( this.label
) {
10087 this.isWaitingToBeAttached
= true;
10088 this.installParentChangeDetector();
10094 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
10095 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IconElement
);
10096 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
10097 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.PendingElement
);
10098 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.LabelElement
);
10100 /* Static Properties */
10102 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
10110 * An `enter` event is emitted when the user presses 'enter' inside the text box.
10118 * Handle icon mouse down events.
10121 * @param {jQuery.Event} e Mouse down event
10123 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
10124 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
10131 * Handle indicator mouse down events.
10134 * @param {jQuery.Event} e Mouse down event
10136 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
10137 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
10144 * Handle key press events.
10147 * @param {jQuery.Event} e Key press event
10148 * @fires enter If enter key is pressed
10150 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
10151 if ( e
.which
=== OO
.ui
.Keys
.ENTER
) {
10152 this.emit( 'enter', e
);
10157 * Handle blur events.
10160 * @param {jQuery.Event} e Blur event
10162 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
10163 this.setValidityFlag();
10167 * Handle focus events.
10170 * @param {jQuery.Event} e Focus event
10172 OO
.ui
.TextInputWidget
.prototype.onFocus = function () {
10173 if ( this.isWaitingToBeAttached
) {
10174 // If we've received focus, then we must be attached to the document, and if
10175 // isWaitingToBeAttached is still true, that means the handler never fired. Fire it now.
10176 this.onElementAttach();
10178 this.setValidityFlag( true );
10182 * Handle element attach events.
10185 * @param {jQuery.Event} e Element attach event
10187 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
10188 this.isWaitingToBeAttached
= false;
10189 // Any previously calculated size is now probably invalid if we reattached elsewhere
10190 this.valCache
= null;
10191 this.positionLabel();
10195 * Handle debounced change events.
10197 * @param {string} value
10200 OO
.ui
.TextInputWidget
.prototype.onDebouncedChange = function () {
10201 this.setValidityFlag();
10205 * Check if the input is {@link #readOnly read-only}.
10207 * @return {boolean}
10209 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
10210 return this.readOnly
;
10214 * Set the {@link #readOnly read-only} state of the input.
10216 * @param {boolean} state Make input read-only
10219 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
10220 this.readOnly
= !!state
;
10221 this.$input
.prop( 'readOnly', this.readOnly
);
10226 * Check if the input is {@link #required required}.
10228 * @return {boolean}
10230 OO
.ui
.TextInputWidget
.prototype.isRequired = function () {
10231 return this.required
;
10235 * Set the {@link #required required} state of the input.
10237 * @param {boolean} state Make input required
10240 OO
.ui
.TextInputWidget
.prototype.setRequired = function ( state
) {
10241 this.required
= !!state
;
10242 if ( this.required
) {
10244 .prop( 'required', true )
10245 .attr( 'aria-required', 'true' );
10246 if ( this.getIndicator() === null ) {
10247 this.setIndicator( 'required' );
10251 .prop( 'required', false )
10252 .removeAttr( 'aria-required' );
10253 if ( this.getIndicator() === 'required' ) {
10254 this.setIndicator( null );
10261 * Support function for making #onElementAttach work across browsers.
10263 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
10264 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
10266 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
10267 * first time that the element gets attached to the documented.
10269 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
10270 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
10271 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
10274 if ( MutationObserver
) {
10275 // The new way. If only it wasn't so ugly.
10277 if ( this.isElementAttached() ) {
10278 // Widget is attached already, do nothing. This breaks the functionality of this function when
10279 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
10280 // would require observation of the whole document, which would hurt performance of other,
10281 // more important code.
10285 // Find topmost node in the tree
10286 topmostNode
= this.$element
[ 0 ];
10287 while ( topmostNode
.parentNode
) {
10288 topmostNode
= topmostNode
.parentNode
;
10291 // We have no way to detect the $element being attached somewhere without observing the entire
10292 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
10293 // parent node of $element, and instead detect when $element is removed from it (and thus
10294 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
10295 // doesn't get attached, we end up back here and create the parent.
10297 mutationObserver
= new MutationObserver( function ( mutations
) {
10298 var i
, j
, removedNodes
;
10299 for ( i
= 0; i
< mutations
.length
; i
++ ) {
10300 removedNodes
= mutations
[ i
].removedNodes
;
10301 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
10302 if ( removedNodes
[ j
] === topmostNode
) {
10303 setTimeout( onRemove
, 0 );
10310 onRemove = function () {
10311 // If the node was attached somewhere else, report it
10312 if ( widget
.isElementAttached() ) {
10313 widget
.onElementAttach();
10315 mutationObserver
.disconnect();
10316 widget
.installParentChangeDetector();
10319 // Create a fake parent and observe it
10320 fakeParentNode
= $( '<div>' ).append( topmostNode
)[ 0 ];
10321 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
10323 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
10324 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
10325 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
10333 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
10334 if ( this.getSaneType( config
) === 'number' ) {
10335 return $( '<input>' )
10336 .attr( 'step', 'any' )
10337 .attr( 'type', 'number' );
10339 return $( '<input>' ).attr( 'type', this.getSaneType( config
) );
10344 * Get sanitized value for 'type' for given config.
10346 * @param {Object} config Configuration options
10347 * @return {string|null}
10350 OO
.ui
.TextInputWidget
.prototype.getSaneType = function ( config
) {
10351 var allowedTypes
= [
10358 return allowedTypes
.indexOf( config
.type
) !== -1 ? config
.type
: 'text';
10362 * Focus the input and select a specified range within the text.
10364 * @param {number} from Select from offset
10365 * @param {number} [to] Select to offset, defaults to from
10368 OO
.ui
.TextInputWidget
.prototype.selectRange = function ( from, to
) {
10369 var isBackwards
, start
, end
,
10370 input
= this.$input
[ 0 ];
10374 isBackwards
= to
< from;
10375 start
= isBackwards
? to
: from;
10376 end
= isBackwards
? from : to
;
10381 input
.setSelectionRange( start
, end
, isBackwards
? 'backward' : 'forward' );
10383 // IE throws an exception if you call setSelectionRange on a unattached DOM node.
10384 // Rather than expensively check if the input is attached every time, just check
10385 // if it was the cause of an error being thrown. If not, rethrow the error.
10386 if ( this.getElementDocument().body
.contains( input
) ) {
10394 * Get an object describing the current selection range in a directional manner
10396 * @return {Object} Object containing 'from' and 'to' offsets
10398 OO
.ui
.TextInputWidget
.prototype.getRange = function () {
10399 var input
= this.$input
[ 0 ],
10400 start
= input
.selectionStart
,
10401 end
= input
.selectionEnd
,
10402 isBackwards
= input
.selectionDirection
=== 'backward';
10405 from: isBackwards
? end
: start
,
10406 to
: isBackwards
? start
: end
10411 * Get the length of the text input value.
10413 * This could differ from the length of #getValue if the
10414 * value gets filtered
10416 * @return {number} Input length
10418 OO
.ui
.TextInputWidget
.prototype.getInputLength = function () {
10419 return this.$input
[ 0 ].value
.length
;
10423 * Focus the input and select the entire text.
10427 OO
.ui
.TextInputWidget
.prototype.select = function () {
10428 return this.selectRange( 0, this.getInputLength() );
10432 * Focus the input and move the cursor to the start.
10436 OO
.ui
.TextInputWidget
.prototype.moveCursorToStart = function () {
10437 return this.selectRange( 0 );
10441 * Focus the input and move the cursor to the end.
10445 OO
.ui
.TextInputWidget
.prototype.moveCursorToEnd = function () {
10446 return this.selectRange( this.getInputLength() );
10450 * Insert new content into the input.
10452 * @param {string} content Content to be inserted
10455 OO
.ui
.TextInputWidget
.prototype.insertContent = function ( content
) {
10457 range
= this.getRange(),
10458 value
= this.getValue();
10460 start
= Math
.min( range
.from, range
.to
);
10461 end
= Math
.max( range
.from, range
.to
);
10463 this.setValue( value
.slice( 0, start
) + content
+ value
.slice( end
) );
10464 this.selectRange( start
+ content
.length
);
10469 * Insert new content either side of a selection.
10471 * @param {string} pre Content to be inserted before the selection
10472 * @param {string} post Content to be inserted after the selection
10475 OO
.ui
.TextInputWidget
.prototype.encapsulateContent = function ( pre
, post
) {
10477 range
= this.getRange(),
10478 offset
= pre
.length
;
10480 start
= Math
.min( range
.from, range
.to
);
10481 end
= Math
.max( range
.from, range
.to
);
10483 this.selectRange( start
).insertContent( pre
);
10484 this.selectRange( offset
+ end
).insertContent( post
);
10486 this.selectRange( offset
+ start
, offset
+ end
);
10491 * Set the validation pattern.
10493 * The validation pattern is either a regular expression, a function, or the symbolic name of a
10494 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
10495 * value must contain only numbers).
10497 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
10498 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
10500 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
10501 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
10502 this.validate
= validate
;
10504 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
10509 * Sets the 'invalid' flag appropriately.
10511 * @param {boolean} [isValid] Optionally override validation result
10513 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
10515 setFlag = function ( valid
) {
10517 widget
.$input
.attr( 'aria-invalid', 'true' );
10519 widget
.$input
.removeAttr( 'aria-invalid' );
10521 widget
.setFlags( { invalid
: !valid
} );
10524 if ( isValid
!== undefined ) {
10525 setFlag( isValid
);
10527 this.getValidity().then( function () {
10536 * Get the validity of current value.
10538 * This method returns a promise that resolves if the value is valid and rejects if
10539 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
10541 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
10543 OO
.ui
.TextInputWidget
.prototype.getValidity = function () {
10546 function rejectOrResolve( valid
) {
10548 return $.Deferred().resolve().promise();
10550 return $.Deferred().reject().promise();
10554 // Check browser validity and reject if it is invalid
10556 this.$input
[ 0 ].checkValidity
!== undefined &&
10557 this.$input
[ 0 ].checkValidity() === false
10559 return rejectOrResolve( false );
10562 // Run our checks if the browser thinks the field is valid
10563 if ( this.validate
instanceof Function
) {
10564 result
= this.validate( this.getValue() );
10565 if ( result
&& $.isFunction( result
.promise
) ) {
10566 return result
.promise().then( function ( valid
) {
10567 return rejectOrResolve( valid
);
10570 return rejectOrResolve( result
);
10573 return rejectOrResolve( this.getValue().match( this.validate
) );
10578 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
10580 * @param {string} labelPosition Label position, 'before' or 'after'
10583 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
10584 this.labelPosition
= labelPosition
;
10585 if ( this.label
) {
10586 // If there is no label and we only change the position, #updatePosition is a no-op,
10587 // but it takes really a lot of work to do nothing.
10588 this.updatePosition();
10594 * Update the position of the inline label.
10596 * This method is called by #setLabelPosition, and can also be called on its own if
10597 * something causes the label to be mispositioned.
10601 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
10602 var after
= this.labelPosition
=== 'after';
10605 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
10606 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
10608 this.valCache
= null;
10609 this.scrollWidth
= null;
10610 this.positionLabel();
10616 * Position the label by setting the correct padding on the input.
10621 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
10622 var after
, rtl
, property
, newCss
;
10624 if ( this.isWaitingToBeAttached
) {
10625 // #onElementAttach will be called soon, which calls this method
10630 'padding-right': '',
10634 if ( this.label
) {
10635 this.$element
.append( this.$label
);
10637 this.$label
.detach();
10638 // Clear old values if present
10639 this.$input
.css( newCss
);
10643 after
= this.labelPosition
=== 'after';
10644 rtl
= this.$element
.css( 'direction' ) === 'rtl';
10645 property
= after
=== rtl
? 'padding-left' : 'padding-right';
10647 newCss
[ property
] = this.$label
.outerWidth( true ) + ( after
? this.scrollWidth
: 0 );
10648 // We have to clear the padding on the other side, in case the element direction changed
10649 this.$input
.css( newCss
);
10656 * @extends OO.ui.TextInputWidget
10659 * @param {Object} [config] Configuration options
10661 OO
.ui
.SearchInputWidget
= function OoUiSearchInputWidget( config
) {
10662 config
= $.extend( {
10666 // Parent constructor
10667 OO
.ui
.SearchInputWidget
.parent
.call( this, config
);
10670 this.connect( this, {
10675 this.updateSearchIndicator();
10676 this.connect( this, {
10677 disable
: 'onDisable'
10683 OO
.inheritClass( OO
.ui
.SearchInputWidget
, OO
.ui
.TextInputWidget
);
10691 OO
.ui
.SearchInputWidget
.prototype.getSaneType = function () {
10698 OO
.ui
.SearchInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
10699 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
10700 // Clear the text field
10701 this.setValue( '' );
10708 * Update the 'clear' indicator displayed on type: 'search' text
10709 * fields, hiding it when the field is already empty or when it's not
10712 OO
.ui
.SearchInputWidget
.prototype.updateSearchIndicator = function () {
10713 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
10714 this.setIndicator( null );
10716 this.setIndicator( 'clear' );
10721 * Handle change events.
10725 OO
.ui
.SearchInputWidget
.prototype.onChange = function () {
10726 this.updateSearchIndicator();
10730 * Handle disable events.
10732 * @param {boolean} disabled Element is disabled
10735 OO
.ui
.SearchInputWidget
.prototype.onDisable = function () {
10736 this.updateSearchIndicator();
10742 OO
.ui
.SearchInputWidget
.prototype.setReadOnly = function ( state
) {
10743 OO
.ui
.SearchInputWidget
.parent
.prototype.setReadOnly
.call( this, state
);
10744 this.updateSearchIndicator();
10750 * @extends OO.ui.TextInputWidget
10753 * @param {Object} [config] Configuration options
10754 * @cfg {number} [rows] Number of visible lines in textarea. If used with `autosize`,
10755 * specifies minimum number of rows to display.
10756 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
10757 * Use the #maxRows config to specify a maximum number of displayed rows.
10758 * @cfg {number} [maxRows] Maximum number of rows to display when #autosize is set to true.
10759 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
10761 OO
.ui
.MultilineTextInputWidget
= function OoUiMultilineTextInputWidget( config
) {
10762 config
= $.extend( {
10765 config
.multiline
= false;
10766 // Parent constructor
10767 OO
.ui
.MultilineTextInputWidget
.parent
.call( this, config
);
10770 this.multiline
= true;
10771 this.autosize
= !!config
.autosize
;
10772 this.minRows
= config
.rows
!== undefined ? config
.rows
: '';
10773 this.maxRows
= config
.maxRows
|| Math
.max( 2 * ( this.minRows
|| 0 ), 10 );
10775 // Clone for resizing
10776 if ( this.autosize
) {
10777 this.$clone
= this.$input
10779 .insertAfter( this.$input
)
10780 .attr( 'aria-hidden', 'true' )
10781 .addClass( 'oo-ui-element-hidden' );
10785 this.connect( this, {
10790 if ( this.multiline
&& config
.rows
) {
10791 this.$input
.attr( 'rows', config
.rows
);
10793 if ( this.autosize
) {
10794 this.$input
.addClass( 'oo-ui-textInputWidget-autosized' );
10795 this.isWaitingToBeAttached
= true;
10796 this.installParentChangeDetector();
10802 OO
.inheritClass( OO
.ui
.MultilineTextInputWidget
, OO
.ui
.TextInputWidget
);
10804 /* Static Methods */
10809 OO
.ui
.MultilineTextInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
10810 var state
= OO
.ui
.MultilineTextInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
10811 state
.scrollTop
= config
.$input
.scrollTop();
10820 OO
.ui
.MultilineTextInputWidget
.prototype.onElementAttach = function () {
10821 OO
.ui
.MultilineTextInputWidget
.parent
.prototype.onElementAttach
.call( this );
10826 * Handle change events.
10830 OO
.ui
.MultilineTextInputWidget
.prototype.onChange = function () {
10837 OO
.ui
.MultilineTextInputWidget
.prototype.updatePosition = function () {
10838 OO
.ui
.MultilineTextInputWidget
.parent
.prototype.updatePosition
.call( this );
10845 * Modify to emit 'enter' on Ctrl/Meta+Enter, instead of plain Enter
10847 OO
.ui
.MultilineTextInputWidget
.prototype.onKeyPress = function ( e
) {
10849 ( e
.which
=== OO
.ui
.Keys
.ENTER
&& ( e
.ctrlKey
|| e
.metaKey
) ) ||
10850 // Some platforms emit keycode 10 for ctrl+enter in a textarea
10853 this.emit( 'enter', e
);
10858 * Automatically adjust the size of the text input.
10860 * This only affects multiline inputs that are {@link #autosize autosized}.
10865 OO
.ui
.MultilineTextInputWidget
.prototype.adjustSize = function () {
10866 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
,
10867 idealHeight
, newHeight
, scrollWidth
, property
;
10869 if ( this.$input
.val() !== this.valCache
) {
10870 if ( this.autosize
) {
10872 .val( this.$input
.val() )
10873 .attr( 'rows', this.minRows
)
10874 // Set inline height property to 0 to measure scroll height
10875 .css( 'height', 0 );
10877 this.$clone
.removeClass( 'oo-ui-element-hidden' );
10879 this.valCache
= this.$input
.val();
10881 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
10883 // Remove inline height property to measure natural heights
10884 this.$clone
.css( 'height', '' );
10885 innerHeight
= this.$clone
.innerHeight();
10886 outerHeight
= this.$clone
.outerHeight();
10888 // Measure max rows height
10890 .attr( 'rows', this.maxRows
)
10891 .css( 'height', 'auto' )
10893 maxInnerHeight
= this.$clone
.innerHeight();
10895 // Difference between reported innerHeight and scrollHeight with no scrollbars present.
10896 // This is sometimes non-zero on Blink-based browsers, depending on zoom level.
10897 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
10898 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
10900 this.$clone
.addClass( 'oo-ui-element-hidden' );
10902 // Only apply inline height when expansion beyond natural height is needed
10903 // Use the difference between the inner and outer height as a buffer
10904 newHeight
= idealHeight
> innerHeight
? idealHeight
+ ( outerHeight
- innerHeight
) : '';
10905 if ( newHeight
!== this.styleHeight
) {
10906 this.$input
.css( 'height', newHeight
);
10907 this.styleHeight
= newHeight
;
10908 this.emit( 'resize' );
10911 scrollWidth
= this.$input
[ 0 ].offsetWidth
- this.$input
[ 0 ].clientWidth
;
10912 if ( scrollWidth
!== this.scrollWidth
) {
10913 property
= this.$element
.css( 'direction' ) === 'rtl' ? 'left' : 'right';
10915 this.$label
.css( { right
: '', left
: '' } );
10916 this.$indicator
.css( { right
: '', left
: '' } );
10918 if ( scrollWidth
) {
10919 this.$indicator
.css( property
, scrollWidth
);
10920 if ( this.labelPosition
=== 'after' ) {
10921 this.$label
.css( property
, scrollWidth
);
10925 this.scrollWidth
= scrollWidth
;
10926 this.positionLabel();
10936 OO
.ui
.MultilineTextInputWidget
.prototype.getInputElement = function () {
10937 return $( '<textarea>' );
10941 * Check if the input supports multiple lines.
10943 * @return {boolean}
10945 OO
.ui
.MultilineTextInputWidget
.prototype.isMultiline = function () {
10946 return !!this.multiline
;
10950 * Check if the input automatically adjusts its size.
10952 * @return {boolean}
10954 OO
.ui
.MultilineTextInputWidget
.prototype.isAutosizing = function () {
10955 return !!this.autosize
;
10961 OO
.ui
.MultilineTextInputWidget
.prototype.restorePreInfuseState = function ( state
) {
10962 OO
.ui
.MultilineTextInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
10963 if ( state
.scrollTop
!== undefined ) {
10964 this.$input
.scrollTop( state
.scrollTop
);
10969 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
10970 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
10971 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
10973 * - by typing a value in the text input field. If the value exactly matches the value of a menu
10974 * option, that option will appear to be selected.
10975 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
10978 * After the user chooses an option, its `data` will be used as a new value for the widget.
10979 * A `label` also can be specified for each option: if given, it will be shown instead of the
10980 * `data` in the dropdown menu.
10982 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
10984 * For more information about menus and options, please see the [OOUI documentation on MediaWiki][1].
10987 * // Example: A ComboBoxInputWidget.
10988 * var comboBox = new OO.ui.ComboBoxInputWidget( {
10989 * value: 'Option 1',
10991 * { data: 'Option 1' },
10992 * { data: 'Option 2' },
10993 * { data: 'Option 3' }
10996 * $( 'body' ).append( comboBox.$element );
10999 * // Example: A ComboBoxInputWidget with additional option labels.
11000 * var comboBox = new OO.ui.ComboBoxInputWidget( {
11001 * value: 'Option 1',
11004 * data: 'Option 1',
11005 * label: 'Option One'
11008 * data: 'Option 2',
11009 * label: 'Option Two'
11012 * data: 'Option 3',
11013 * label: 'Option Three'
11017 * $( 'body' ).append( comboBox.$element );
11019 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
11022 * @extends OO.ui.TextInputWidget
11025 * @param {Object} [config] Configuration options
11026 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
11027 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
11028 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
11029 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
11030 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
11031 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11033 OO
.ui
.ComboBoxInputWidget
= function OoUiComboBoxInputWidget( config
) {
11034 // Configuration initialization
11035 config
= $.extend( {
11036 autocomplete
: false
11039 // ComboBoxInputWidget shouldn't support `multiline`
11040 config
.multiline
= false;
11042 // See InputWidget#reusePreInfuseDOM about `config.$input`
11043 if ( config
.$input
) {
11044 config
.$input
.removeAttr( 'list' );
11047 // Parent constructor
11048 OO
.ui
.ComboBoxInputWidget
.parent
.call( this, config
);
11051 this.$overlay
= ( config
.$overlay
=== true ? OO
.ui
.getDefaultOverlay() : config
.$overlay
) || this.$element
;
11052 this.dropdownButton
= new OO
.ui
.ButtonWidget( {
11053 classes
: [ 'oo-ui-comboBoxInputWidget-dropdownButton' ],
11055 disabled
: this.disabled
11057 this.menu
= new OO
.ui
.MenuSelectWidget( $.extend(
11061 $floatableContainer
: this.$element
,
11062 disabled
: this.isDisabled()
11068 this.connect( this, {
11069 change
: 'onInputChange',
11070 enter
: 'onInputEnter'
11072 this.dropdownButton
.connect( this, {
11073 click
: 'onDropdownButtonClick'
11075 this.menu
.connect( this, {
11076 choose
: 'onMenuChoose',
11077 add
: 'onMenuItemsChange',
11078 remove
: 'onMenuItemsChange',
11079 toggle
: 'onMenuToggle'
11083 this.$input
.attr( {
11085 'aria-owns': this.menu
.getElementId(),
11086 'aria-autocomplete': 'list'
11088 // Do not override options set via config.menu.items
11089 if ( config
.options
!== undefined ) {
11090 this.setOptions( config
.options
);
11092 this.$field
= $( '<div>' )
11093 .addClass( 'oo-ui-comboBoxInputWidget-field' )
11094 .append( this.$input
, this.dropdownButton
.$element
);
11096 .addClass( 'oo-ui-comboBoxInputWidget' )
11097 .append( this.$field
);
11098 this.$overlay
.append( this.menu
.$element
);
11099 this.onMenuItemsChange();
11104 OO
.inheritClass( OO
.ui
.ComboBoxInputWidget
, OO
.ui
.TextInputWidget
);
11109 * Get the combobox's menu.
11111 * @return {OO.ui.MenuSelectWidget} Menu widget
11113 OO
.ui
.ComboBoxInputWidget
.prototype.getMenu = function () {
11118 * Get the combobox's text input widget.
11120 * @return {OO.ui.TextInputWidget} Text input widget
11122 OO
.ui
.ComboBoxInputWidget
.prototype.getInput = function () {
11127 * Handle input change events.
11130 * @param {string} value New value
11132 OO
.ui
.ComboBoxInputWidget
.prototype.onInputChange = function ( value
) {
11133 var match
= this.menu
.findItemFromData( value
);
11135 this.menu
.selectItem( match
);
11136 if ( this.menu
.findHighlightedItem() ) {
11137 this.menu
.highlightItem( match
);
11140 if ( !this.isDisabled() ) {
11141 this.menu
.toggle( true );
11146 * Handle input enter events.
11150 OO
.ui
.ComboBoxInputWidget
.prototype.onInputEnter = function () {
11151 if ( !this.isDisabled() ) {
11152 this.menu
.toggle( false );
11157 * Handle button click events.
11161 OO
.ui
.ComboBoxInputWidget
.prototype.onDropdownButtonClick = function () {
11162 this.menu
.toggle();
11167 * Handle menu choose events.
11170 * @param {OO.ui.OptionWidget} item Chosen item
11172 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuChoose = function ( item
) {
11173 this.setValue( item
.getData() );
11177 * Handle menu item change events.
11181 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuItemsChange = function () {
11182 var match
= this.menu
.findItemFromData( this.getValue() );
11183 this.menu
.selectItem( match
);
11184 if ( this.menu
.findHighlightedItem() ) {
11185 this.menu
.highlightItem( match
);
11187 this.$element
.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu
.isEmpty() );
11191 * Handle menu toggle events.
11194 * @param {boolean} isVisible Open state of the menu
11196 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuToggle = function ( isVisible
) {
11197 this.$element
.toggleClass( 'oo-ui-comboBoxInputWidget-open', isVisible
);
11203 OO
.ui
.ComboBoxInputWidget
.prototype.setDisabled = function ( disabled
) {
11205 OO
.ui
.ComboBoxInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
11207 if ( this.dropdownButton
) {
11208 this.dropdownButton
.setDisabled( this.isDisabled() );
11211 this.menu
.setDisabled( this.isDisabled() );
11218 * Set the options available for this input.
11220 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
11223 OO
.ui
.ComboBoxInputWidget
.prototype.setOptions = function ( options
) {
11226 .addItems( options
.map( function ( opt
) {
11227 return new OO
.ui
.MenuOptionWidget( {
11229 label
: opt
.label
!== undefined ? opt
.label
: opt
.data
11237 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
11238 * which is a widget that is specified by reference before any optional configuration settings.
11240 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
11242 * - **left**: The label is placed before the field-widget and aligned with the left margin.
11243 * A left-alignment is used for forms with many fields.
11244 * - **right**: The label is placed before the field-widget and aligned to the right margin.
11245 * A right-alignment is used for long but familiar forms which users tab through,
11246 * verifying the current field with a quick glance at the label.
11247 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
11248 * that users fill out from top to bottom.
11249 * - **inline**: The label is placed after the field-widget and aligned to the left.
11250 * An inline-alignment is best used with checkboxes or radio buttons.
11252 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
11253 * Please see the [OOUI documentation on MediaWiki] [1] for examples and more information.
11255 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
11258 * @extends OO.ui.Layout
11259 * @mixins OO.ui.mixin.LabelElement
11260 * @mixins OO.ui.mixin.TitledElement
11263 * @param {OO.ui.Widget} fieldWidget Field widget
11264 * @param {Object} [config] Configuration options
11265 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
11266 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
11267 * The array may contain strings or OO.ui.HtmlSnippet instances.
11268 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
11269 * The array may contain strings or OO.ui.HtmlSnippet instances.
11270 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
11271 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
11272 * For important messages, you are advised to use `notices`, as they are always shown.
11273 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
11274 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11276 * @throws {Error} An error is thrown if no widget is specified
11278 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
11279 // Allow passing positional parameters inside the config object
11280 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
11281 config
= fieldWidget
;
11282 fieldWidget
= config
.fieldWidget
;
11285 // Make sure we have required constructor arguments
11286 if ( fieldWidget
=== undefined ) {
11287 throw new Error( 'Widget not found' );
11290 // Configuration initialization
11291 config
= $.extend( { align
: 'left' }, config
);
11293 // Parent constructor
11294 OO
.ui
.FieldLayout
.parent
.call( this, config
);
11296 // Mixin constructors
11297 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, {
11298 $label
: $( '<label>' )
11300 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
11303 this.fieldWidget
= fieldWidget
;
11306 this.$field
= this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
11307 this.$messages
= $( '<ul>' );
11308 this.$header
= $( '<span>' );
11309 this.$body
= $( '<div>' );
11311 if ( config
.help
) {
11312 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
11313 $overlay
: config
.$overlay
,
11317 classes
: [ 'oo-ui-fieldLayout-help' ],
11320 label
: OO
.ui
.msg( 'ooui-field-help' )
11322 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
11323 this.popupButtonWidget
.getPopup().$body
.html( config
.help
.toString() );
11325 this.popupButtonWidget
.getPopup().$body
.text( config
.help
);
11327 this.$help
= this.popupButtonWidget
.$element
;
11329 this.$help
= $( [] );
11333 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
11336 if ( config
.help
) {
11337 // Set the 'aria-describedby' attribute on the fieldWidget
11338 // Preference given to an input or a button
11340 this.fieldWidget
.$input
||
11341 this.fieldWidget
.$button
||
11342 this.fieldWidget
.$element
11344 'aria-describedby',
11345 this.popupButtonWidget
.getPopup().getBodyId()
11348 if ( this.fieldWidget
.getInputId() ) {
11349 this.$label
.attr( 'for', this.fieldWidget
.getInputId() );
11351 this.$label
.on( 'click', function () {
11352 this.fieldWidget
.simulateLabelClick();
11356 .addClass( 'oo-ui-fieldLayout' )
11357 .toggleClass( 'oo-ui-fieldLayout-disabled', this.fieldWidget
.isDisabled() )
11358 .append( this.$body
);
11359 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
11360 this.$header
.addClass( 'oo-ui-fieldLayout-header' );
11361 this.$messages
.addClass( 'oo-ui-fieldLayout-messages' );
11363 .addClass( 'oo-ui-fieldLayout-field' )
11364 .append( this.fieldWidget
.$element
);
11366 this.setErrors( config
.errors
|| [] );
11367 this.setNotices( config
.notices
|| [] );
11368 this.setAlignment( config
.align
);
11369 // Call this again to take into account the widget's accessKey
11370 this.updateTitle();
11375 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
11376 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.LabelElement
);
11377 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.TitledElement
);
11382 * Handle field disable events.
11385 * @param {boolean} value Field is disabled
11387 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
11388 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
11392 * Get the widget contained by the field.
11394 * @return {OO.ui.Widget} Field widget
11396 OO
.ui
.FieldLayout
.prototype.getField = function () {
11397 return this.fieldWidget
;
11401 * Return `true` if the given field widget can be used with `'inline'` alignment (see
11402 * #setAlignment). Return `false` if it can't or if this can't be determined.
11404 * @return {boolean}
11406 OO
.ui
.FieldLayout
.prototype.isFieldInline = function () {
11407 // This is very simplistic, but should be good enough.
11408 return this.getField().$element
.prop( 'tagName' ).toLowerCase() === 'span';
11413 * @param {string} kind 'error' or 'notice'
11414 * @param {string|OO.ui.HtmlSnippet} text
11417 OO
.ui
.FieldLayout
.prototype.makeMessage = function ( kind
, text
) {
11418 var $listItem
, $icon
, message
;
11419 $listItem
= $( '<li>' );
11420 if ( kind
=== 'error' ) {
11421 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'warning' ] } ).$element
;
11422 $listItem
.attr( 'role', 'alert' );
11423 } else if ( kind
=== 'notice' ) {
11424 $icon
= new OO
.ui
.IconWidget( { icon
: 'notice' } ).$element
;
11428 message
= new OO
.ui
.LabelWidget( { label
: text
} );
11430 .append( $icon
, message
.$element
)
11431 .addClass( 'oo-ui-fieldLayout-messages-' + kind
);
11436 * Set the field alignment mode.
11439 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
11442 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
11443 if ( value
!== this.align
) {
11444 // Default to 'left'
11445 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
11449 if ( value
=== 'inline' && !this.isFieldInline() ) {
11452 // Reorder elements
11453 if ( value
=== 'top' ) {
11454 this.$header
.append( this.$help
, this.$label
);
11455 this.$body
.append( this.$header
, this.$field
);
11456 } else if ( value
=== 'inline' ) {
11457 this.$header
.append( this.$help
, this.$label
);
11458 this.$body
.append( this.$field
, this.$header
);
11460 this.$header
.append( this.$label
);
11461 this.$body
.append( this.$header
, this.$help
, this.$field
);
11463 // Set classes. The following classes can be used here:
11464 // * oo-ui-fieldLayout-align-left
11465 // * oo-ui-fieldLayout-align-right
11466 // * oo-ui-fieldLayout-align-top
11467 // * oo-ui-fieldLayout-align-inline
11468 if ( this.align
) {
11469 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
11471 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
11472 this.align
= value
;
11479 * Set the list of error messages.
11481 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
11482 * The array may contain strings or OO.ui.HtmlSnippet instances.
11485 OO
.ui
.FieldLayout
.prototype.setErrors = function ( errors
) {
11486 this.errors
= errors
.slice();
11487 this.updateMessages();
11492 * Set the list of notice messages.
11494 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
11495 * The array may contain strings or OO.ui.HtmlSnippet instances.
11498 OO
.ui
.FieldLayout
.prototype.setNotices = function ( notices
) {
11499 this.notices
= notices
.slice();
11500 this.updateMessages();
11505 * Update the rendering of error and notice messages.
11509 OO
.ui
.FieldLayout
.prototype.updateMessages = function () {
11511 this.$messages
.empty();
11513 if ( this.errors
.length
|| this.notices
.length
) {
11514 this.$body
.after( this.$messages
);
11516 this.$messages
.remove();
11520 for ( i
= 0; i
< this.notices
.length
; i
++ ) {
11521 this.$messages
.append( this.makeMessage( 'notice', this.notices
[ i
] ) );
11523 for ( i
= 0; i
< this.errors
.length
; i
++ ) {
11524 this.$messages
.append( this.makeMessage( 'error', this.errors
[ i
] ) );
11529 * Include information about the widget's accessKey in our title. TitledElement calls this method.
11530 * (This is a bit of a hack.)
11533 * @param {string} title Tooltip label for 'title' attribute
11536 OO
.ui
.FieldLayout
.prototype.formatTitleWithAccessKey = function ( title
) {
11537 if ( this.fieldWidget
&& this.fieldWidget
.formatTitleWithAccessKey
) {
11538 return this.fieldWidget
.formatTitleWithAccessKey( title
);
11544 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
11545 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
11546 * is required and is specified before any optional configuration settings.
11548 * Labels can be aligned in one of four ways:
11550 * - **left**: The label is placed before the field-widget and aligned with the left margin.
11551 * A left-alignment is used for forms with many fields.
11552 * - **right**: The label is placed before the field-widget and aligned to the right margin.
11553 * A right-alignment is used for long but familiar forms which users tab through,
11554 * verifying the current field with a quick glance at the label.
11555 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
11556 * that users fill out from top to bottom.
11557 * - **inline**: The label is placed after the field-widget and aligned to the left.
11558 * An inline-alignment is best used with checkboxes or radio buttons.
11560 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
11561 * text is specified.
11564 * // Example of an ActionFieldLayout
11565 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
11566 * new OO.ui.TextInputWidget( {
11567 * placeholder: 'Field widget'
11569 * new OO.ui.ButtonWidget( {
11573 * label: 'An ActionFieldLayout. This label is aligned top',
11575 * help: 'This is help text'
11579 * $( 'body' ).append( actionFieldLayout.$element );
11582 * @extends OO.ui.FieldLayout
11585 * @param {OO.ui.Widget} fieldWidget Field widget
11586 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
11587 * @param {Object} config
11589 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
11590 // Allow passing positional parameters inside the config object
11591 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
11592 config
= fieldWidget
;
11593 fieldWidget
= config
.fieldWidget
;
11594 buttonWidget
= config
.buttonWidget
;
11597 // Parent constructor
11598 OO
.ui
.ActionFieldLayout
.parent
.call( this, fieldWidget
, config
);
11601 this.buttonWidget
= buttonWidget
;
11602 this.$button
= $( '<span>' );
11603 this.$input
= this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
11607 .addClass( 'oo-ui-actionFieldLayout' );
11609 .addClass( 'oo-ui-actionFieldLayout-button' )
11610 .append( this.buttonWidget
.$element
);
11612 .addClass( 'oo-ui-actionFieldLayout-input' )
11613 .append( this.fieldWidget
.$element
);
11615 .append( this.$input
, this.$button
);
11620 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
11623 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
11624 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
11625 * configured with a label as well. For more information and examples,
11626 * please see the [OOUI documentation on MediaWiki][1].
11629 * // Example of a fieldset layout
11630 * var input1 = new OO.ui.TextInputWidget( {
11631 * placeholder: 'A text input field'
11634 * var input2 = new OO.ui.TextInputWidget( {
11635 * placeholder: 'A text input field'
11638 * var fieldset = new OO.ui.FieldsetLayout( {
11639 * label: 'Example of a fieldset layout'
11642 * fieldset.addItems( [
11643 * new OO.ui.FieldLayout( input1, {
11644 * label: 'Field One'
11646 * new OO.ui.FieldLayout( input2, {
11647 * label: 'Field Two'
11650 * $( 'body' ).append( fieldset.$element );
11652 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Fields_and_Fieldsets
11655 * @extends OO.ui.Layout
11656 * @mixins OO.ui.mixin.IconElement
11657 * @mixins OO.ui.mixin.LabelElement
11658 * @mixins OO.ui.mixin.GroupElement
11661 * @param {Object} [config] Configuration options
11662 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
11663 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
11664 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
11665 * For important messages, you are advised to use `notices`, as they are always shown.
11666 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
11667 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
11669 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
11670 // Configuration initialization
11671 config
= config
|| {};
11673 // Parent constructor
11674 OO
.ui
.FieldsetLayout
.parent
.call( this, config
);
11676 // Mixin constructors
11677 OO
.ui
.mixin
.IconElement
.call( this, config
);
11678 OO
.ui
.mixin
.LabelElement
.call( this, config
);
11679 OO
.ui
.mixin
.GroupElement
.call( this, config
);
11682 this.$header
= $( '<legend>' );
11683 if ( config
.help
) {
11684 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
11685 $overlay
: config
.$overlay
,
11689 classes
: [ 'oo-ui-fieldsetLayout-help' ],
11692 label
: OO
.ui
.msg( 'ooui-field-help' )
11694 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
11695 this.popupButtonWidget
.getPopup().$body
.html( config
.help
.toString() );
11697 this.popupButtonWidget
.getPopup().$body
.text( config
.help
);
11699 this.$help
= this.popupButtonWidget
.$element
;
11701 this.$help
= $( [] );
11706 .addClass( 'oo-ui-fieldsetLayout-header' )
11707 .append( this.$icon
, this.$label
, this.$help
);
11708 this.$group
.addClass( 'oo-ui-fieldsetLayout-group' );
11710 .addClass( 'oo-ui-fieldsetLayout' )
11711 .prepend( this.$header
, this.$group
);
11712 if ( Array
.isArray( config
.items
) ) {
11713 this.addItems( config
.items
);
11719 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
11720 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.IconElement
);
11721 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.LabelElement
);
11722 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.GroupElement
);
11724 /* Static Properties */
11730 OO
.ui
.FieldsetLayout
.static.tagName
= 'fieldset';
11733 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
11734 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
11735 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
11736 * See the [OOUI documentation on MediaWiki] [1] for more information and examples.
11738 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
11739 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
11740 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
11741 * some fancier controls. Some controls have both regular and InputWidget variants, for example
11742 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
11743 * often have simplified APIs to match the capabilities of HTML forms.
11744 * See the [OOUI documentation on MediaWiki] [2] for more information about InputWidgets.
11746 * [1]: https://www.mediawiki.org/wiki/OOUI/Layouts/Forms
11747 * [2]: https://www.mediawiki.org/wiki/OOUI/Widgets/Inputs
11750 * // Example of a form layout that wraps a fieldset layout
11751 * var input1 = new OO.ui.TextInputWidget( {
11752 * placeholder: 'Username'
11754 * var input2 = new OO.ui.TextInputWidget( {
11755 * placeholder: 'Password',
11758 * var submit = new OO.ui.ButtonInputWidget( {
11762 * var fieldset = new OO.ui.FieldsetLayout( {
11763 * label: 'A form layout'
11765 * fieldset.addItems( [
11766 * new OO.ui.FieldLayout( input1, {
11767 * label: 'Username',
11770 * new OO.ui.FieldLayout( input2, {
11771 * label: 'Password',
11774 * new OO.ui.FieldLayout( submit )
11776 * var form = new OO.ui.FormLayout( {
11777 * items: [ fieldset ],
11778 * action: '/api/formhandler',
11781 * $( 'body' ).append( form.$element );
11784 * @extends OO.ui.Layout
11785 * @mixins OO.ui.mixin.GroupElement
11788 * @param {Object} [config] Configuration options
11789 * @cfg {string} [method] HTML form `method` attribute
11790 * @cfg {string} [action] HTML form `action` attribute
11791 * @cfg {string} [enctype] HTML form `enctype` attribute
11792 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
11794 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
11797 // Configuration initialization
11798 config
= config
|| {};
11800 // Parent constructor
11801 OO
.ui
.FormLayout
.parent
.call( this, config
);
11803 // Mixin constructors
11804 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
11807 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
11809 // Make sure the action is safe
11810 action
= config
.action
;
11811 if ( action
!== undefined && !OO
.ui
.isSafeUrl( action
) ) {
11812 action
= './' + action
;
11817 .addClass( 'oo-ui-formLayout' )
11819 method
: config
.method
,
11821 enctype
: config
.enctype
11823 if ( Array
.isArray( config
.items
) ) {
11824 this.addItems( config
.items
);
11830 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
11831 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.mixin
.GroupElement
);
11836 * A 'submit' event is emitted when the form is submitted.
11841 /* Static Properties */
11847 OO
.ui
.FormLayout
.static.tagName
= 'form';
11852 * Handle form submit events.
11855 * @param {jQuery.Event} e Submit event
11858 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
11859 if ( this.emit( 'submit' ) ) {
11865 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
11866 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
11869 * // Example of a panel layout
11870 * var panel = new OO.ui.PanelLayout( {
11874 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
11876 * $( 'body' ).append( panel.$element );
11879 * @extends OO.ui.Layout
11882 * @param {Object} [config] Configuration options
11883 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
11884 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
11885 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
11886 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
11888 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
11889 // Configuration initialization
11890 config
= $.extend( {
11897 // Parent constructor
11898 OO
.ui
.PanelLayout
.parent
.call( this, config
);
11901 this.$element
.addClass( 'oo-ui-panelLayout' );
11902 if ( config
.scrollable
) {
11903 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
11905 if ( config
.padded
) {
11906 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
11908 if ( config
.expanded
) {
11909 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
11911 if ( config
.framed
) {
11912 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
11918 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
11923 * Focus the panel layout
11925 * The default implementation just focuses the first focusable element in the panel
11927 OO
.ui
.PanelLayout
.prototype.focus = function () {
11928 OO
.ui
.findFocusable( this.$element
).focus();
11932 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
11933 * items), with small margins between them. Convenient when you need to put a number of block-level
11934 * widgets on a single line next to each other.
11936 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
11939 * // HorizontalLayout with a text input and a label
11940 * var layout = new OO.ui.HorizontalLayout( {
11942 * new OO.ui.LabelWidget( { label: 'Label' } ),
11943 * new OO.ui.TextInputWidget( { value: 'Text' } )
11946 * $( 'body' ).append( layout.$element );
11949 * @extends OO.ui.Layout
11950 * @mixins OO.ui.mixin.GroupElement
11953 * @param {Object} [config] Configuration options
11954 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
11956 OO
.ui
.HorizontalLayout
= function OoUiHorizontalLayout( config
) {
11957 // Configuration initialization
11958 config
= config
|| {};
11960 // Parent constructor
11961 OO
.ui
.HorizontalLayout
.parent
.call( this, config
);
11963 // Mixin constructors
11964 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
11967 this.$element
.addClass( 'oo-ui-horizontalLayout' );
11968 if ( Array
.isArray( config
.items
) ) {
11969 this.addItems( config
.items
);
11975 OO
.inheritClass( OO
.ui
.HorizontalLayout
, OO
.ui
.Layout
);
11976 OO
.mixinClass( OO
.ui
.HorizontalLayout
, OO
.ui
.mixin
.GroupElement
);
11979 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
11980 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
11981 * (to adjust the value in increments) to allow the user to enter a number.
11984 * // Example: A NumberInputWidget.
11985 * var numberInput = new OO.ui.NumberInputWidget( {
11986 * label: 'NumberInputWidget',
11987 * input: { value: 5 },
11991 * $( 'body' ).append( numberInput.$element );
11994 * @extends OO.ui.TextInputWidget
11997 * @param {Object} [config] Configuration options
11998 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
11999 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
12000 * @cfg {boolean} [allowInteger=false] Whether the field accepts only integer values.
12001 * @cfg {number} [min=-Infinity] Minimum allowed value
12002 * @cfg {number} [max=Infinity] Maximum allowed value
12003 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
12004 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
12005 * @cfg {boolean} [showButtons=true] Whether to show the plus and minus buttons.
12007 OO
.ui
.NumberInputWidget
= function OoUiNumberInputWidget( config
) {
12008 var $field
= $( '<div>' )
12009 .addClass( 'oo-ui-numberInputWidget-field' );
12011 // Configuration initialization
12012 config
= $.extend( {
12013 allowInteger
: false,
12021 // For backward compatibility
12022 $.extend( config
, config
.input
);
12025 // Parent constructor
12026 OO
.ui
.NumberInputWidget
.parent
.call( this, $.extend( config
, {
12030 if ( config
.showButtons
) {
12031 this.minusButton
= new OO
.ui
.ButtonWidget( $.extend(
12033 disabled
: this.isDisabled(),
12035 classes
: [ 'oo-ui-numberInputWidget-minusButton' ],
12040 this.minusButton
.$element
.attr( 'aria-hidden', 'true' );
12041 this.plusButton
= new OO
.ui
.ButtonWidget( $.extend(
12043 disabled
: this.isDisabled(),
12045 classes
: [ 'oo-ui-numberInputWidget-plusButton' ],
12050 this.plusButton
.$element
.attr( 'aria-hidden', 'true' );
12055 keydown
: this.onKeyDown
.bind( this ),
12056 'wheel mousewheel DOMMouseScroll': this.onWheel
.bind( this )
12058 if ( config
.showButtons
) {
12059 this.plusButton
.connect( this, {
12060 click
: [ 'onButtonClick', +1 ]
12062 this.minusButton
.connect( this, {
12063 click
: [ 'onButtonClick', -1 ]
12068 $field
.append( this.$input
);
12069 if ( config
.showButtons
) {
12071 .prepend( this.minusButton
.$element
)
12072 .append( this.plusButton
.$element
);
12076 this.setAllowInteger( config
.allowInteger
|| config
.isInteger
);
12077 this.setRange( config
.min
, config
.max
);
12078 this.setStep( config
.step
, config
.pageStep
);
12079 // Set the validation method after we set allowInteger and range
12080 // so that it doesn't immediately call setValidityFlag
12081 this.setValidation( this.validateNumber
.bind( this ) );
12084 .addClass( 'oo-ui-numberInputWidget' )
12085 .toggleClass( 'oo-ui-numberInputWidget-buttoned', config
.showButtons
)
12091 OO
.inheritClass( OO
.ui
.NumberInputWidget
, OO
.ui
.TextInputWidget
);
12096 * Set whether only integers are allowed
12098 * @param {boolean} flag
12100 OO
.ui
.NumberInputWidget
.prototype.setAllowInteger = function ( flag
) {
12101 this.allowInteger
= !!flag
;
12102 this.setValidityFlag();
12104 // Backward compatibility
12105 OO
.ui
.NumberInputWidget
.prototype.setIsInteger
= OO
.ui
.NumberInputWidget
.prototype.setAllowInteger
;
12108 * Get whether only integers are allowed
12110 * @return {boolean} Flag value
12112 OO
.ui
.NumberInputWidget
.prototype.getAllowInteger = function () {
12113 return this.allowInteger
;
12115 // Backward compatibility
12116 OO
.ui
.NumberInputWidget
.prototype.getIsInteger
= OO
.ui
.NumberInputWidget
.prototype.getAllowInteger
;
12119 * Set the range of allowed values
12121 * @param {number} min Minimum allowed value
12122 * @param {number} max Maximum allowed value
12124 OO
.ui
.NumberInputWidget
.prototype.setRange = function ( min
, max
) {
12126 throw new Error( 'Minimum (' + min
+ ') must not be greater than maximum (' + max
+ ')' );
12130 this.$input
.attr( 'min', this.min
);
12131 this.$input
.attr( 'max', this.max
);
12132 this.setValidityFlag();
12136 * Get the current range
12138 * @return {number[]} Minimum and maximum values
12140 OO
.ui
.NumberInputWidget
.prototype.getRange = function () {
12141 return [ this.min
, this.max
];
12145 * Set the stepping deltas
12147 * @param {number} step Normal step
12148 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
12150 OO
.ui
.NumberInputWidget
.prototype.setStep = function ( step
, pageStep
) {
12152 throw new Error( 'Step value must be positive' );
12154 if ( pageStep
=== null ) {
12155 pageStep
= step
* 10;
12156 } else if ( pageStep
<= 0 ) {
12157 throw new Error( 'Page step value must be positive' );
12160 this.pageStep
= pageStep
;
12161 this.$input
.attr( 'step', this.step
);
12167 OO
.ui
.NumberInputWidget
.prototype.setValue = function ( value
) {
12168 if ( value
=== '' ) {
12169 // Some browsers allow a value in the input even if there isn't one reported by $input.val()
12170 // so here we make sure an 'empty' value is actually displayed as such.
12171 this.$input
.val( '' );
12173 return OO
.ui
.NumberInputWidget
.parent
.prototype.setValue
.call( this, value
);
12177 * Get the current stepping values
12179 * @return {number[]} Step and page step
12181 OO
.ui
.NumberInputWidget
.prototype.getStep = function () {
12182 return [ this.step
, this.pageStep
];
12186 * Get the current value of the widget as a number
12188 * @return {number} May be NaN, or an invalid number
12190 OO
.ui
.NumberInputWidget
.prototype.getNumericValue = function () {
12191 return +this.getValue();
12195 * Adjust the value of the widget
12197 * @param {number} delta Adjustment amount
12199 OO
.ui
.NumberInputWidget
.prototype.adjustValue = function ( delta
) {
12200 var n
, v
= this.getNumericValue();
12203 if ( isNaN( delta
) || !isFinite( delta
) ) {
12204 throw new Error( 'Delta must be a finite number' );
12207 if ( isNaN( v
) ) {
12211 n
= Math
.max( Math
.min( n
, this.max
), this.min
);
12212 if ( this.allowInteger
) {
12213 n
= Math
.round( n
);
12218 this.setValue( n
);
12225 * @param {string} value Field value
12226 * @return {boolean}
12228 OO
.ui
.NumberInputWidget
.prototype.validateNumber = function ( value
) {
12230 if ( value
=== '' ) {
12231 return !this.isRequired();
12234 if ( isNaN( n
) || !isFinite( n
) ) {
12238 if ( this.allowInteger
&& Math
.floor( n
) !== n
) {
12242 if ( n
< this.min
|| n
> this.max
) {
12250 * Handle mouse click events.
12253 * @param {number} dir +1 or -1
12255 OO
.ui
.NumberInputWidget
.prototype.onButtonClick = function ( dir
) {
12256 this.adjustValue( dir
* this.step
);
12260 * Handle mouse wheel events.
12263 * @param {jQuery.Event} event
12265 OO
.ui
.NumberInputWidget
.prototype.onWheel = function ( event
) {
12268 if ( !this.isDisabled() && this.$input
.is( ':focus' ) ) {
12269 // Standard 'wheel' event
12270 if ( event
.originalEvent
.deltaMode
!== undefined ) {
12271 this.sawWheelEvent
= true;
12273 if ( event
.originalEvent
.deltaY
) {
12274 delta
= -event
.originalEvent
.deltaY
;
12275 } else if ( event
.originalEvent
.deltaX
) {
12276 delta
= event
.originalEvent
.deltaX
;
12279 // Non-standard events
12280 if ( !this.sawWheelEvent
) {
12281 if ( event
.originalEvent
.wheelDeltaX
) {
12282 delta
= -event
.originalEvent
.wheelDeltaX
;
12283 } else if ( event
.originalEvent
.wheelDeltaY
) {
12284 delta
= event
.originalEvent
.wheelDeltaY
;
12285 } else if ( event
.originalEvent
.wheelDelta
) {
12286 delta
= event
.originalEvent
.wheelDelta
;
12287 } else if ( event
.originalEvent
.detail
) {
12288 delta
= -event
.originalEvent
.detail
;
12293 delta
= delta
< 0 ? -1 : 1;
12294 this.adjustValue( delta
* this.step
);
12302 * Handle key down events.
12305 * @param {jQuery.Event} e Key down event
12307 OO
.ui
.NumberInputWidget
.prototype.onKeyDown = function ( e
) {
12308 if ( !this.isDisabled() ) {
12309 switch ( e
.which
) {
12310 case OO
.ui
.Keys
.UP
:
12311 this.adjustValue( this.step
);
12313 case OO
.ui
.Keys
.DOWN
:
12314 this.adjustValue( -this.step
);
12316 case OO
.ui
.Keys
.PAGEUP
:
12317 this.adjustValue( this.pageStep
);
12319 case OO
.ui
.Keys
.PAGEDOWN
:
12320 this.adjustValue( -this.pageStep
);
12329 OO
.ui
.NumberInputWidget
.prototype.setDisabled = function ( disabled
) {
12331 OO
.ui
.NumberInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
12333 if ( this.minusButton
) {
12334 this.minusButton
.setDisabled( this.isDisabled() );
12336 if ( this.plusButton
) {
12337 this.plusButton
.setDisabled( this.isDisabled() );
12345 //# sourceMappingURL=oojs-ui-core.js.map