3 * https://www.mediawiki.org/wiki/OOjs_UI
5 * Copyright 2011–2017 OOjs UI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
9 * Date: 2017-06-28T19:51:59Z
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 'oojsui-' + 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 accept button of a confirmation dialog
366 'ooui-dialog-message-accept': 'OK',
367 // Default label for the reject button of a confirmation dialog
368 'ooui-dialog-message-reject': 'Cancel',
369 // Title for process dialog error description
370 'ooui-dialog-process-error': 'Something went wrong',
371 // Label for process dialog dismiss error button, visible when describing errors
372 'ooui-dialog-process-dismiss': 'Dismiss',
373 // Label for process dialog retry action button, visible when describing only recoverable errors
374 'ooui-dialog-process-retry': 'Try again',
375 // Label for process dialog retry action button, visible when describing only warnings
376 'ooui-dialog-process-continue': 'Continue',
377 // Label for the file selection widget's select file button
378 'ooui-selectfile-button-select': 'Select a file',
379 // Label for the file selection widget if file selection is not supported
380 'ooui-selectfile-not-supported': 'File selection is not supported',
381 // Label for the file selection widget when no file is currently selected
382 'ooui-selectfile-placeholder': 'No file is selected',
383 // Label for the file selection widget's drop target
384 'ooui-selectfile-dragdrop-placeholder': 'Drop file here'
388 * Get a localized message.
390 * After the message key, message parameters may optionally be passed. In the default implementation,
391 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
392 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
393 * they support unnamed, ordered message parameters.
395 * In environments that provide a localization system, this function should be overridden to
396 * return the message translated in the user's language. The default implementation always returns
397 * English messages. An example of doing this with [jQuery.i18n](https://github.com/wikimedia/jquery.i18n)
401 * var i, iLen, button,
402 * messagePath = 'oojs-ui/dist/i18n/',
403 * languages = [ $.i18n().locale, 'ur', 'en' ],
406 * for ( i = 0, iLen = languages.length; i < iLen; i++ ) {
407 * languageMap[ languages[ i ] ] = messagePath + languages[ i ].toLowerCase() + '.json';
410 * $.i18n().load( languageMap ).done( function() {
411 * // Replace the built-in `msg` only once we've loaded the internationalization.
412 * // OOjs UI uses `OO.ui.deferMsg` for all initially-loaded messages. So long as
413 * // you put off creating any widgets until this promise is complete, no English
414 * // will be displayed.
415 * OO.ui.msg = $.i18n;
417 * // A button displaying "OK" in the default locale
418 * button = new OO.ui.ButtonWidget( {
419 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
422 * $( 'body' ).append( button.$element );
424 * // A button displaying "OK" in Urdu
425 * $.i18n().locale = 'ur';
426 * button = new OO.ui.ButtonWidget( {
427 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
430 * $( 'body' ).append( button.$element );
433 * @param {string} key Message key
434 * @param {...Mixed} [params] Message parameters
435 * @return {string} Translated message with parameters substituted
437 OO
.ui
.msg = function ( key
) {
438 var message
= messages
[ key
],
439 params
= Array
.prototype.slice
.call( arguments
, 1 );
440 if ( typeof message
=== 'string' ) {
441 // Perform $1 substitution
442 message
= message
.replace( /\$(\d+)/g, function ( unused
, n
) {
443 var i
= parseInt( n
, 10 );
444 return params
[ i
- 1 ] !== undefined ? params
[ i
- 1 ] : '$' + n
;
447 // Return placeholder if message not found
448 message
= '[' + key
+ ']';
455 * Package a message and arguments for deferred resolution.
457 * Use this when you are statically specifying a message and the message may not yet be present.
459 * @param {string} key Message key
460 * @param {...Mixed} [params] Message parameters
461 * @return {Function} Function that returns the resolved message when executed
463 OO
.ui
.deferMsg = function () {
464 var args
= arguments
;
466 return OO
.ui
.msg
.apply( OO
.ui
, args
);
473 * If the message is a function it will be executed, otherwise it will pass through directly.
475 * @param {Function|string} msg Deferred message, or message text
476 * @return {string} Resolved message
478 OO
.ui
.resolveMsg = function ( msg
) {
479 if ( $.isFunction( msg
) ) {
486 * @param {string} url
489 OO
.ui
.isSafeUrl = function ( url
) {
490 // Keep this function in sync with php/Tag.php
491 var i
, protocolWhitelist
;
493 function stringStartsWith( haystack
, needle
) {
494 return haystack
.substr( 0, needle
.length
) === needle
;
497 protocolWhitelist
= [
498 'bitcoin', 'ftp', 'ftps', 'geo', 'git', 'gopher', 'http', 'https', 'irc', 'ircs',
499 'magnet', 'mailto', 'mms', 'news', 'nntp', 'redis', 'sftp', 'sip', 'sips', 'sms', 'ssh',
500 'svn', 'tel', 'telnet', 'urn', 'worldwind', 'xmpp'
507 for ( i
= 0; i
< protocolWhitelist
.length
; i
++ ) {
508 if ( stringStartsWith( url
, protocolWhitelist
[ i
] + ':' ) ) {
513 // This matches '//' too
514 if ( stringStartsWith( url
, '/' ) || stringStartsWith( url
, './' ) ) {
517 if ( stringStartsWith( url
, '?' ) || stringStartsWith( url
, '#' ) ) {
525 * Check if the user has a 'mobile' device.
527 * For our purposes this means the user is primarily using an
528 * on-screen keyboard, touch input instead of a mouse and may
529 * have a physically small display.
531 * It is left up to implementors to decide how to compute this
532 * so the default implementation always returns false.
534 * @return {boolean} Use is on a mobile device
536 OO
.ui
.isMobile = function () {
545 * Namespace for OOjs UI mixins.
547 * Mixins are named according to the type of object they are intended to
548 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
549 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
550 * is intended to be mixed in to an instance of OO.ui.Widget.
558 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
559 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
560 * connected to them and can't be interacted with.
566 * @param {Object} [config] Configuration options
567 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
568 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
570 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
571 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
572 * @cfg {string} [text] Text to insert
573 * @cfg {Array} [content] An array of content elements to append (after #text).
574 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
575 * Instances of OO.ui.Element will have their $element appended.
576 * @cfg {jQuery} [$content] Content elements to append (after #text).
577 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
578 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
579 * Data can also be specified with the #setData method.
581 OO
.ui
.Element
= function OoUiElement( config
) {
582 this.initialConfig
= config
;
583 // Configuration initialization
584 config
= config
|| {};
588 this.elementId
= null;
590 this.data
= config
.data
;
591 this.$element
= config
.$element
||
592 $( document
.createElement( this.getTagName() ) );
593 this.elementGroup
= null;
596 if ( Array
.isArray( config
.classes
) ) {
597 this.$element
.addClass( config
.classes
.join( ' ' ) );
600 this.setElementId( config
.id
);
603 this.$element
.text( config
.text
);
605 if ( config
.content
) {
606 // The `content` property treats plain strings as text; use an
607 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
608 // appropriate $element appended.
609 this.$element
.append( config
.content
.map( function ( v
) {
610 if ( typeof v
=== 'string' ) {
611 // Escape string so it is properly represented in HTML.
612 return document
.createTextNode( v
);
613 } else if ( v
instanceof OO
.ui
.HtmlSnippet
) {
616 } else if ( v
instanceof OO
.ui
.Element
) {
622 if ( config
.$content
) {
623 // The `$content` property treats plain strings as HTML.
624 this.$element
.append( config
.$content
);
630 OO
.initClass( OO
.ui
.Element
);
632 /* Static Properties */
635 * The name of the HTML tag used by the element.
637 * The static value may be ignored if the #getTagName method is overridden.
643 OO
.ui
.Element
.static.tagName
= 'div';
648 * Reconstitute a JavaScript object corresponding to a widget created
649 * by the PHP implementation.
651 * @param {string|HTMLElement|jQuery} idOrNode
652 * A DOM id (if a string) or node for the widget to infuse.
653 * @return {OO.ui.Element}
654 * The `OO.ui.Element` corresponding to this (infusable) document node.
655 * For `Tag` objects emitted on the HTML side (used occasionally for content)
656 * the value returned is a newly-created Element wrapping around the existing
659 OO
.ui
.Element
.static.infuse = function ( idOrNode
) {
660 var obj
= OO
.ui
.Element
.static.unsafeInfuse( idOrNode
, false );
661 // Verify that the type matches up.
662 // FIXME: uncomment after T89721 is fixed (see T90929)
664 if ( !( obj instanceof this['class'] ) ) {
665 throw new Error( 'Infusion type mismatch!' );
672 * Implementation helper for `infuse`; skips the type check and has an
673 * extra property so that only the top-level invocation touches the DOM.
676 * @param {string|HTMLElement|jQuery} idOrNode
677 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
678 * when the top-level widget of this infusion is inserted into DOM,
679 * replacing the original node; or false for top-level invocation.
680 * @return {OO.ui.Element}
682 OO
.ui
.Element
.static.unsafeInfuse = function ( idOrNode
, domPromise
) {
683 // look for a cached result of a previous infusion.
684 var id
, $elem
, data
, cls
, parts
, parent
, obj
, top
, state
, infusedChildren
;
685 if ( typeof idOrNode
=== 'string' ) {
687 $elem
= $( document
.getElementById( id
) );
689 $elem
= $( idOrNode
);
690 id
= $elem
.attr( 'id' );
692 if ( !$elem
.length
) {
693 throw new Error( 'Widget not found: ' + id
);
695 if ( $elem
[ 0 ].oouiInfused
) {
696 $elem
= $elem
[ 0 ].oouiInfused
;
698 data
= $elem
.data( 'ooui-infused' );
701 if ( data
=== true ) {
702 throw new Error( 'Circular dependency! ' + id
);
705 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
706 state
= data
.constructor.static.gatherPreInfuseState( $elem
, data
);
707 // restore dynamic state after the new element is re-inserted into DOM under infused parent
708 domPromise
.done( data
.restorePreInfuseState
.bind( data
, state
) );
709 infusedChildren
= $elem
.data( 'ooui-infused-children' );
710 if ( infusedChildren
&& infusedChildren
.length
) {
711 infusedChildren
.forEach( function ( data
) {
712 var state
= data
.constructor.static.gatherPreInfuseState( $elem
, data
);
713 domPromise
.done( data
.restorePreInfuseState
.bind( data
, state
) );
719 data
= $elem
.attr( 'data-ooui' );
721 throw new Error( 'No infusion data found: ' + id
);
724 data
= JSON
.parse( data
);
728 if ( !( data
&& data
._
) ) {
729 throw new Error( 'No valid infusion data found: ' + id
);
731 if ( data
._
=== 'Tag' ) {
732 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
733 return new OO
.ui
.Element( { $element
: $elem
} );
735 parts
= data
._
.split( '.' );
736 cls
= OO
.getProp
.apply( OO
, [ window
].concat( parts
) );
737 if ( cls
=== undefined ) {
738 // The PHP output might be old and not including the "OO.ui" prefix
739 // TODO: Remove this back-compat after next major release
740 cls
= OO
.getProp
.apply( OO
, [ OO
.ui
].concat( parts
) );
741 if ( cls
=== undefined ) {
742 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
746 // Verify that we're creating an OO.ui.Element instance
749 while ( parent
!== undefined ) {
750 if ( parent
=== OO
.ui
.Element
) {
755 parent
= parent
.parent
;
758 if ( parent
!== OO
.ui
.Element
) {
759 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
762 if ( domPromise
=== false ) {
764 domPromise
= top
.promise();
766 $elem
.data( 'ooui-infused', true ); // prevent loops
767 data
.id
= id
; // implicit
768 infusedChildren
= [];
769 data
= OO
.copy( data
, null, function deserialize( value
) {
771 if ( OO
.isPlainObject( value
) ) {
773 infused
= OO
.ui
.Element
.static.unsafeInfuse( value
.tag
, domPromise
);
774 infusedChildren
.push( infused
);
775 // Flatten the structure
776 infusedChildren
.push
.apply( infusedChildren
, infused
.$element
.data( 'ooui-infused-children' ) || [] );
777 infused
.$element
.removeData( 'ooui-infused-children' );
780 if ( value
.html
!== undefined ) {
781 return new OO
.ui
.HtmlSnippet( value
.html
);
785 // allow widgets to reuse parts of the DOM
786 data
= cls
.static.reusePreInfuseDOM( $elem
[ 0 ], data
);
787 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
788 state
= cls
.static.gatherPreInfuseState( $elem
[ 0 ], data
);
790 // eslint-disable-next-line new-cap
791 obj
= new cls( data
);
792 // now replace old DOM with this new DOM.
794 // An efficient constructor might be able to reuse the entire DOM tree of the original element,
795 // so only mutate the DOM if we need to.
796 if ( $elem
[ 0 ] !== obj
.$element
[ 0 ] ) {
797 $elem
.replaceWith( obj
.$element
);
798 // This element is now gone from the DOM, but if anyone is holding a reference to it,
799 // let's allow them to OO.ui.infuse() it and do what they expect (T105828).
800 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
801 $elem
[ 0 ].oouiInfused
= obj
.$element
;
805 obj
.$element
.data( 'ooui-infused', obj
);
806 obj
.$element
.data( 'ooui-infused-children', infusedChildren
);
807 // set the 'data-ooui' attribute so we can identify infused widgets
808 obj
.$element
.attr( 'data-ooui', '' );
809 // restore dynamic state after the new element is inserted into DOM
810 domPromise
.done( obj
.restorePreInfuseState
.bind( obj
, state
) );
815 * Pick out parts of `node`'s DOM to be reused when infusing a widget.
817 * This method **must not** make any changes to the DOM, only find interesting pieces and add them
818 * to `config` (which should then be returned). Actual DOM juggling should then be done by the
819 * constructor, which will be given the enhanced config.
822 * @param {HTMLElement} node
823 * @param {Object} config
826 OO
.ui
.Element
.static.reusePreInfuseDOM = function ( node
, config
) {
831 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of an HTML DOM node
832 * (and its children) that represent an Element of the same class and the given configuration,
833 * generated by the PHP implementation.
835 * This method is called just before `node` is detached from the DOM. The return value of this
836 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
837 * is inserted into DOM to replace `node`.
840 * @param {HTMLElement} node
841 * @param {Object} config
844 OO
.ui
.Element
.static.gatherPreInfuseState = function () {
849 * Get a jQuery function within a specific document.
852 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
853 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
855 * @return {Function} Bound jQuery function
857 OO
.ui
.Element
.static.getJQuery = function ( context
, $iframe
) {
858 function wrapper( selector
) {
859 return $( selector
, wrapper
.context
);
862 wrapper
.context
= this.getDocument( context
);
865 wrapper
.$iframe
= $iframe
;
872 * Get the document of an element.
875 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
876 * @return {HTMLDocument|null} Document object
878 OO
.ui
.Element
.static.getDocument = function ( obj
) {
879 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
880 return ( obj
[ 0 ] && obj
[ 0 ].ownerDocument
) ||
881 // Empty jQuery selections might have a context
888 ( obj
.nodeType
=== Node
.DOCUMENT_NODE
&& obj
) ||
893 * Get the window of an element or document.
896 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
897 * @return {Window} Window object
899 OO
.ui
.Element
.static.getWindow = function ( obj
) {
900 var doc
= this.getDocument( obj
);
901 return doc
.defaultView
;
905 * Get the direction of an element or document.
908 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
909 * @return {string} Text direction, either 'ltr' or 'rtl'
911 OO
.ui
.Element
.static.getDir = function ( obj
) {
914 if ( obj
instanceof jQuery
) {
917 isDoc
= obj
.nodeType
=== Node
.DOCUMENT_NODE
;
918 isWin
= obj
.document
!== undefined;
919 if ( isDoc
|| isWin
) {
925 return $( obj
).css( 'direction' );
929 * Get the offset between two frames.
931 * TODO: Make this function not use recursion.
934 * @param {Window} from Window of the child frame
935 * @param {Window} [to=window] Window of the parent frame
936 * @param {Object} [offset] Offset to start with, used internally
937 * @return {Object} Offset object, containing left and top properties
939 OO
.ui
.Element
.static.getFrameOffset = function ( from, to
, offset
) {
940 var i
, len
, frames
, frame
, rect
;
946 offset
= { top
: 0, left
: 0 };
948 if ( from.parent
=== from ) {
952 // Get iframe element
953 frames
= from.parent
.document
.getElementsByTagName( 'iframe' );
954 for ( i
= 0, len
= frames
.length
; i
< len
; i
++ ) {
955 if ( frames
[ i
].contentWindow
=== from ) {
961 // Recursively accumulate offset values
963 rect
= frame
.getBoundingClientRect();
964 offset
.left
+= rect
.left
;
965 offset
.top
+= rect
.top
;
967 this.getFrameOffset( from.parent
, offset
);
974 * Get the offset between two elements.
976 * The two elements may be in a different frame, but in that case the frame $element is in must
977 * be contained in the frame $anchor is in.
980 * @param {jQuery} $element Element whose position to get
981 * @param {jQuery} $anchor Element to get $element's position relative to
982 * @return {Object} Translated position coordinates, containing top and left properties
984 OO
.ui
.Element
.static.getRelativePosition = function ( $element
, $anchor
) {
985 var iframe
, iframePos
,
986 pos
= $element
.offset(),
987 anchorPos
= $anchor
.offset(),
988 elementDocument
= this.getDocument( $element
),
989 anchorDocument
= this.getDocument( $anchor
);
991 // If $element isn't in the same document as $anchor, traverse up
992 while ( elementDocument
!== anchorDocument
) {
993 iframe
= elementDocument
.defaultView
.frameElement
;
995 throw new Error( '$element frame is not contained in $anchor frame' );
997 iframePos
= $( iframe
).offset();
998 pos
.left
+= iframePos
.left
;
999 pos
.top
+= iframePos
.top
;
1000 elementDocument
= iframe
.ownerDocument
;
1002 pos
.left
-= anchorPos
.left
;
1003 pos
.top
-= anchorPos
.top
;
1008 * Get element border sizes.
1011 * @param {HTMLElement} el Element to measure
1012 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1014 OO
.ui
.Element
.static.getBorders = function ( el
) {
1015 var doc
= el
.ownerDocument
,
1016 win
= doc
.defaultView
,
1017 style
= win
.getComputedStyle( el
, null ),
1019 top
= parseFloat( style
? style
.borderTopWidth
: $el
.css( 'borderTopWidth' ) ) || 0,
1020 left
= parseFloat( style
? style
.borderLeftWidth
: $el
.css( 'borderLeftWidth' ) ) || 0,
1021 bottom
= parseFloat( style
? style
.borderBottomWidth
: $el
.css( 'borderBottomWidth' ) ) || 0,
1022 right
= parseFloat( style
? style
.borderRightWidth
: $el
.css( 'borderRightWidth' ) ) || 0;
1033 * Get dimensions of an element or window.
1036 * @param {HTMLElement|Window} el Element to measure
1037 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1039 OO
.ui
.Element
.static.getDimensions = function ( el
) {
1041 doc
= el
.ownerDocument
|| el
.document
,
1042 win
= doc
.defaultView
;
1044 if ( win
=== el
|| el
=== doc
.documentElement
) {
1047 borders
: { top
: 0, left
: 0, bottom
: 0, right
: 0 },
1049 top
: $win
.scrollTop(),
1050 left
: $win
.scrollLeft()
1052 scrollbar
: { right
: 0, bottom
: 0 },
1056 bottom
: $win
.innerHeight(),
1057 right
: $win
.innerWidth()
1063 borders
: this.getBorders( el
),
1065 top
: $el
.scrollTop(),
1066 left
: $el
.scrollLeft()
1069 right
: $el
.innerWidth() - el
.clientWidth
,
1070 bottom
: $el
.innerHeight() - el
.clientHeight
1072 rect
: el
.getBoundingClientRect()
1078 * Get the number of pixels that an element's content is scrolled to the left.
1080 * Adapted from <https://github.com/othree/jquery.rtl-scroll-type>.
1081 * Original code copyright 2012 Wei-Ko Kao, licensed under the MIT License.
1083 * This function smooths out browser inconsistencies (nicely described in the README at
1084 * <https://github.com/othree/jquery.rtl-scroll-type>) and produces a result consistent
1085 * with Firefox's 'scrollLeft', which seems the sanest.
1089 * @param {HTMLElement|Window} el Element to measure
1090 * @return {number} Scroll position from the left.
1091 * If the element's direction is LTR, this is a positive number between `0` (initial scroll position)
1092 * and `el.scrollWidth - el.clientWidth` (furthest possible scroll position).
1093 * If the element's direction is RTL, this is a negative number between `0` (initial scroll position)
1094 * and `-el.scrollWidth + el.clientWidth` (furthest possible scroll position).
1096 OO
.ui
.Element
.static.getScrollLeft
= ( function () {
1097 var rtlScrollType
= null;
1100 var $definer
= $( '<div dir="rtl" style="font-size: 14px; width: 1px; height: 1px; position: absolute; top: -1000px; overflow: scroll">A</div>' ),
1101 definer
= $definer
[ 0 ];
1103 $definer
.appendTo( 'body' );
1104 if ( definer
.scrollLeft
> 0 ) {
1106 rtlScrollType
= 'default';
1108 definer
.scrollLeft
= 1;
1109 if ( definer
.scrollLeft
=== 0 ) {
1110 // Firefox, old Opera
1111 rtlScrollType
= 'negative';
1113 // Internet Explorer, Edge
1114 rtlScrollType
= 'reverse';
1120 return function getScrollLeft( el
) {
1121 var isRoot
= el
.window
=== el
||
1122 el
=== el
.ownerDocument
.body
||
1123 el
=== el
.ownerDocument
.documentElement
,
1124 scrollLeft
= isRoot
? $( window
).scrollLeft() : el
.scrollLeft
,
1125 // All browsers use the correct scroll type ('negative') on the root, so don't
1126 // do any fixups when looking at the root element
1127 direction
= isRoot
? 'ltr' : $( el
).css( 'direction' );
1129 if ( direction
=== 'rtl' ) {
1130 if ( rtlScrollType
=== null ) {
1133 if ( rtlScrollType
=== 'reverse' ) {
1134 scrollLeft
= -scrollLeft
;
1135 } else if ( rtlScrollType
=== 'default' ) {
1136 scrollLeft
= scrollLeft
- el
.scrollWidth
+ el
.clientWidth
;
1145 * Get the root scrollable element of given element's document.
1147 * On Blink-based browsers (Chrome etc.), `document.documentElement` can't be used to get or set
1148 * the scrollTop property; instead we have to use `document.body`. Changing and testing the value
1149 * lets us use 'body' or 'documentElement' based on what is working.
1151 * https://code.google.com/p/chromium/issues/detail?id=303131
1154 * @param {HTMLElement} el Element to find root scrollable parent for
1155 * @return {HTMLElement} Scrollable parent, `document.body` or `document.documentElement`
1156 * depending on browser
1158 OO
.ui
.Element
.static.getRootScrollableElement = function ( el
) {
1159 var scrollTop
, body
;
1161 if ( OO
.ui
.scrollableElement
=== undefined ) {
1162 body
= el
.ownerDocument
.body
;
1163 scrollTop
= body
.scrollTop
;
1166 // In some browsers (observed in Chrome 56 on Linux Mint 18.1),
1167 // body.scrollTop doesn't become exactly 1, but a fractional value like 0.76
1168 if ( Math
.round( body
.scrollTop
) === 1 ) {
1169 body
.scrollTop
= scrollTop
;
1170 OO
.ui
.scrollableElement
= 'body';
1172 OO
.ui
.scrollableElement
= 'documentElement';
1176 return el
.ownerDocument
[ OO
.ui
.scrollableElement
];
1180 * Get closest scrollable container.
1182 * Traverses up until either a scrollable element or the root is reached, in which case the root
1183 * scrollable element will be returned (see #getRootScrollableElement).
1186 * @param {HTMLElement} el Element to find scrollable container for
1187 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1188 * @return {HTMLElement} Closest scrollable container
1190 OO
.ui
.Element
.static.getClosestScrollableContainer = function ( el
, dimension
) {
1192 // Browsers do not correctly return the computed value of 'overflow' when 'overflow-x' and
1193 // 'overflow-y' have different values, so we need to check the separate properties.
1194 props
= [ 'overflow-x', 'overflow-y' ],
1195 $parent
= $( el
).parent();
1197 if ( dimension
=== 'x' || dimension
=== 'y' ) {
1198 props
= [ 'overflow-' + dimension
];
1201 // Special case for the document root (which doesn't really have any scrollable container, since
1202 // it is the ultimate scrollable container, but this is probably saner than null or exception)
1203 if ( $( el
).is( 'html, body' ) ) {
1204 return this.getRootScrollableElement( el
);
1207 while ( $parent
.length
) {
1208 if ( $parent
[ 0 ] === this.getRootScrollableElement( el
) ) {
1209 return $parent
[ 0 ];
1213 val
= $parent
.css( props
[ i
] );
1214 // We assume that elements with 'overflow' (in any direction) set to 'hidden' will never be
1215 // scrolled in that direction, but they can actually be scrolled programatically. The user can
1216 // unintentionally perform a scroll in such case even if the application doesn't scroll
1217 // programatically, e.g. when jumping to an anchor, or when using built-in find functionality.
1218 // This could cause funny issues...
1219 if ( val
=== 'auto' || val
=== 'scroll' ) {
1220 return $parent
[ 0 ];
1223 $parent
= $parent
.parent();
1225 // The element is unattached... return something mostly sane
1226 return this.getRootScrollableElement( el
);
1230 * Scroll element into view.
1233 * @param {HTMLElement} el Element to scroll into view
1234 * @param {Object} [config] Configuration options
1235 * @param {string} [config.duration='fast'] jQuery animation duration value
1236 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1237 * to scroll in both directions
1238 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1240 OO
.ui
.Element
.static.scrollIntoView = function ( el
, config
) {
1241 var position
, animations
, container
, $container
, elementDimensions
, containerDimensions
, $window
,
1242 deferred
= $.Deferred();
1244 // Configuration initialization
1245 config
= config
|| {};
1248 container
= this.getClosestScrollableContainer( el
, config
.direction
);
1249 $container
= $( container
);
1250 elementDimensions
= this.getDimensions( el
);
1251 containerDimensions
= this.getDimensions( container
);
1252 $window
= $( this.getWindow( el
) );
1254 // Compute the element's position relative to the container
1255 if ( $container
.is( 'html, body' ) ) {
1256 // If the scrollable container is the root, this is easy
1258 top
: elementDimensions
.rect
.top
,
1259 bottom
: $window
.innerHeight() - elementDimensions
.rect
.bottom
,
1260 left
: elementDimensions
.rect
.left
,
1261 right
: $window
.innerWidth() - elementDimensions
.rect
.right
1264 // Otherwise, we have to subtract el's coordinates from container's coordinates
1266 top
: elementDimensions
.rect
.top
- ( containerDimensions
.rect
.top
+ containerDimensions
.borders
.top
),
1267 bottom
: containerDimensions
.rect
.bottom
- containerDimensions
.borders
.bottom
- containerDimensions
.scrollbar
.bottom
- elementDimensions
.rect
.bottom
,
1268 left
: elementDimensions
.rect
.left
- ( containerDimensions
.rect
.left
+ containerDimensions
.borders
.left
),
1269 right
: containerDimensions
.rect
.right
- containerDimensions
.borders
.right
- containerDimensions
.scrollbar
.right
- elementDimensions
.rect
.right
1273 if ( !config
.direction
|| config
.direction
=== 'y' ) {
1274 if ( position
.top
< 0 ) {
1275 animations
.scrollTop
= containerDimensions
.scroll
.top
+ position
.top
;
1276 } else if ( position
.top
> 0 && position
.bottom
< 0 ) {
1277 animations
.scrollTop
= containerDimensions
.scroll
.top
+ Math
.min( position
.top
, -position
.bottom
);
1280 if ( !config
.direction
|| config
.direction
=== 'x' ) {
1281 if ( position
.left
< 0 ) {
1282 animations
.scrollLeft
= containerDimensions
.scroll
.left
+ position
.left
;
1283 } else if ( position
.left
> 0 && position
.right
< 0 ) {
1284 animations
.scrollLeft
= containerDimensions
.scroll
.left
+ Math
.min( position
.left
, -position
.right
);
1287 if ( !$.isEmptyObject( animations
) ) {
1288 $container
.stop( true ).animate( animations
, config
.duration
=== undefined ? 'fast' : config
.duration
);
1289 $container
.queue( function ( next
) {
1296 return deferred
.promise();
1300 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1301 * and reserve space for them, because it probably doesn't.
1303 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1304 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1305 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1306 * and then reattach (or show) them back.
1309 * @param {HTMLElement} el Element to reconsider the scrollbars on
1311 OO
.ui
.Element
.static.reconsiderScrollbars = function ( el
) {
1312 var i
, len
, scrollLeft
, scrollTop
, nodes
= [];
1313 // Save scroll position
1314 scrollLeft
= el
.scrollLeft
;
1315 scrollTop
= el
.scrollTop
;
1316 // Detach all children
1317 while ( el
.firstChild
) {
1318 nodes
.push( el
.firstChild
);
1319 el
.removeChild( el
.firstChild
);
1322 void el
.offsetHeight
;
1323 // Reattach all children
1324 for ( i
= 0, len
= nodes
.length
; i
< len
; i
++ ) {
1325 el
.appendChild( nodes
[ i
] );
1327 // Restore scroll position (no-op if scrollbars disappeared)
1328 el
.scrollLeft
= scrollLeft
;
1329 el
.scrollTop
= scrollTop
;
1335 * Toggle visibility of an element.
1337 * @param {boolean} [show] Make element visible, omit to toggle visibility
1341 OO
.ui
.Element
.prototype.toggle = function ( show
) {
1342 show
= show
=== undefined ? !this.visible
: !!show
;
1344 if ( show
!== this.isVisible() ) {
1345 this.visible
= show
;
1346 this.$element
.toggleClass( 'oo-ui-element-hidden', !this.visible
);
1347 this.emit( 'toggle', show
);
1354 * Check if element is visible.
1356 * @return {boolean} element is visible
1358 OO
.ui
.Element
.prototype.isVisible = function () {
1359 return this.visible
;
1365 * @return {Mixed} Element data
1367 OO
.ui
.Element
.prototype.getData = function () {
1374 * @param {Mixed} data Element data
1377 OO
.ui
.Element
.prototype.setData = function ( data
) {
1383 * Set the element has an 'id' attribute.
1385 * @param {string} id
1388 OO
.ui
.Element
.prototype.setElementId = function ( id
) {
1389 this.elementId
= id
;
1390 this.$element
.attr( 'id', id
);
1395 * Ensure that the element has an 'id' attribute, setting it to an unique value if it's missing,
1396 * and return its value.
1400 OO
.ui
.Element
.prototype.getElementId = function () {
1401 if ( this.elementId
=== null ) {
1402 this.setElementId( OO
.ui
.generateElementId() );
1404 return this.elementId
;
1408 * Check if element supports one or more methods.
1410 * @param {string|string[]} methods Method or list of methods to check
1411 * @return {boolean} All methods are supported
1413 OO
.ui
.Element
.prototype.supports = function ( methods
) {
1417 methods
= Array
.isArray( methods
) ? methods
: [ methods
];
1418 for ( i
= 0, len
= methods
.length
; i
< len
; i
++ ) {
1419 if ( $.isFunction( this[ methods
[ i
] ] ) ) {
1424 return methods
.length
=== support
;
1428 * Update the theme-provided classes.
1430 * @localdoc This is called in element mixins and widget classes any time state changes.
1431 * Updating is debounced, minimizing overhead of changing multiple attributes and
1432 * guaranteeing that theme updates do not occur within an element's constructor
1434 OO
.ui
.Element
.prototype.updateThemeClasses = function () {
1435 OO
.ui
.theme
.queueUpdateElementClasses( this );
1439 * Get the HTML tag name.
1441 * Override this method to base the result on instance information.
1443 * @return {string} HTML tag name
1445 OO
.ui
.Element
.prototype.getTagName = function () {
1446 return this.constructor.static.tagName
;
1450 * Check if the element is attached to the DOM
1452 * @return {boolean} The element is attached to the DOM
1454 OO
.ui
.Element
.prototype.isElementAttached = function () {
1455 return $.contains( this.getElementDocument(), this.$element
[ 0 ] );
1459 * Get the DOM document.
1461 * @return {HTMLDocument} Document object
1463 OO
.ui
.Element
.prototype.getElementDocument = function () {
1464 // Don't cache this in other ways either because subclasses could can change this.$element
1465 return OO
.ui
.Element
.static.getDocument( this.$element
);
1469 * Get the DOM window.
1471 * @return {Window} Window object
1473 OO
.ui
.Element
.prototype.getElementWindow = function () {
1474 return OO
.ui
.Element
.static.getWindow( this.$element
);
1478 * Get closest scrollable container.
1480 * @return {HTMLElement} Closest scrollable container
1482 OO
.ui
.Element
.prototype.getClosestScrollableElementContainer = function () {
1483 return OO
.ui
.Element
.static.getClosestScrollableContainer( this.$element
[ 0 ] );
1487 * Get group element is in.
1489 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1491 OO
.ui
.Element
.prototype.getElementGroup = function () {
1492 return this.elementGroup
;
1496 * Set group element is in.
1498 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1501 OO
.ui
.Element
.prototype.setElementGroup = function ( group
) {
1502 this.elementGroup
= group
;
1507 * Scroll element into view.
1509 * @param {Object} [config] Configuration options
1510 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1512 OO
.ui
.Element
.prototype.scrollElementIntoView = function ( config
) {
1514 !this.isElementAttached() ||
1515 !this.isVisible() ||
1516 ( this.getElementGroup() && !this.getElementGroup().isVisible() )
1518 return $.Deferred().resolve();
1520 return OO
.ui
.Element
.static.scrollIntoView( this.$element
[ 0 ], config
);
1524 * Restore the pre-infusion dynamic state for this widget.
1526 * This method is called after #$element has been inserted into DOM. The parameter is the return
1527 * value of #gatherPreInfuseState.
1530 * @param {Object} state
1532 OO
.ui
.Element
.prototype.restorePreInfuseState = function () {
1536 * Wraps an HTML snippet for use with configuration values which default
1537 * to strings. This bypasses the default html-escaping done to string
1543 * @param {string} [content] HTML content
1545 OO
.ui
.HtmlSnippet
= function OoUiHtmlSnippet( content
) {
1547 this.content
= content
;
1552 OO
.initClass( OO
.ui
.HtmlSnippet
);
1559 * @return {string} Unchanged HTML snippet.
1561 OO
.ui
.HtmlSnippet
.prototype.toString = function () {
1562 return this.content
;
1566 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1567 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1568 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1569 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1570 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1574 * @extends OO.ui.Element
1575 * @mixins OO.EventEmitter
1578 * @param {Object} [config] Configuration options
1580 OO
.ui
.Layout
= function OoUiLayout( config
) {
1581 // Configuration initialization
1582 config
= config
|| {};
1584 // Parent constructor
1585 OO
.ui
.Layout
.parent
.call( this, config
);
1587 // Mixin constructors
1588 OO
.EventEmitter
.call( this );
1591 this.$element
.addClass( 'oo-ui-layout' );
1596 OO
.inheritClass( OO
.ui
.Layout
, OO
.ui
.Element
);
1597 OO
.mixinClass( OO
.ui
.Layout
, OO
.EventEmitter
);
1600 * Widgets are compositions of one or more OOjs UI elements that users can both view
1601 * and interact with. All widgets can be configured and modified via a standard API,
1602 * and their state can change dynamically according to a model.
1606 * @extends OO.ui.Element
1607 * @mixins OO.EventEmitter
1610 * @param {Object} [config] Configuration options
1611 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1612 * appearance reflects this state.
1614 OO
.ui
.Widget
= function OoUiWidget( config
) {
1615 // Initialize config
1616 config
= $.extend( { disabled
: false }, config
);
1618 // Parent constructor
1619 OO
.ui
.Widget
.parent
.call( this, config
);
1621 // Mixin constructors
1622 OO
.EventEmitter
.call( this );
1625 this.disabled
= null;
1626 this.wasDisabled
= null;
1629 this.$element
.addClass( 'oo-ui-widget' );
1630 this.setDisabled( !!config
.disabled
);
1635 OO
.inheritClass( OO
.ui
.Widget
, OO
.ui
.Element
);
1636 OO
.mixinClass( OO
.ui
.Widget
, OO
.EventEmitter
);
1643 * A 'disable' event is emitted when the disabled state of the widget changes
1644 * (i.e. on disable **and** enable).
1646 * @param {boolean} disabled Widget is disabled
1652 * A 'toggle' event is emitted when the visibility of the widget changes.
1654 * @param {boolean} visible Widget is visible
1660 * Check if the widget is disabled.
1662 * @return {boolean} Widget is disabled
1664 OO
.ui
.Widget
.prototype.isDisabled = function () {
1665 return this.disabled
;
1669 * Set the 'disabled' state of the widget.
1671 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1673 * @param {boolean} disabled Disable widget
1676 OO
.ui
.Widget
.prototype.setDisabled = function ( disabled
) {
1679 this.disabled
= !!disabled
;
1680 isDisabled
= this.isDisabled();
1681 if ( isDisabled
!== this.wasDisabled
) {
1682 this.$element
.toggleClass( 'oo-ui-widget-disabled', isDisabled
);
1683 this.$element
.toggleClass( 'oo-ui-widget-enabled', !isDisabled
);
1684 this.$element
.attr( 'aria-disabled', isDisabled
.toString() );
1685 this.emit( 'disable', isDisabled
);
1686 this.updateThemeClasses();
1688 this.wasDisabled
= isDisabled
;
1694 * Update the disabled state, in case of changes in parent widget.
1698 OO
.ui
.Widget
.prototype.updateDisabled = function () {
1699 this.setDisabled( this.disabled
);
1704 * Get an ID of a labelable node which is part of this widget, if any, to be used for `<label for>`
1707 * If this function returns null, the widget should have a meaningful #simulateLabelClick method
1710 * @return {string|null} The ID of the labelable element
1712 OO
.ui
.Widget
.prototype.getInputId = function () {
1717 * Simulate the behavior of clicking on a label (a HTML `<label>` element) bound to this input.
1718 * HTML only allows `<label>` to act on specific "labelable" elements; complex widgets might need to
1719 * override this method to provide intuitive, accessible behavior.
1721 * By default, this does nothing. OO.ui.mixin.TabIndexedElement overrides it for focusable widgets.
1722 * Individual widgets may override it too.
1724 * This method is called by OO.ui.LabelWidget and OO.ui.FieldLayout. It should not be called
1727 OO
.ui
.Widget
.prototype.simulateLabelClick = function () {
1738 OO
.ui
.Theme
= function OoUiTheme() {
1739 this.elementClassesQueue
= [];
1740 this.debouncedUpdateQueuedElementClasses
= OO
.ui
.debounce( this.updateQueuedElementClasses
);
1745 OO
.initClass( OO
.ui
.Theme
);
1750 * Get a list of classes to be applied to a widget.
1752 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
1753 * otherwise state transitions will not work properly.
1755 * @param {OO.ui.Element} element Element for which to get classes
1756 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
1758 OO
.ui
.Theme
.prototype.getElementClasses = function () {
1759 return { on
: [], off
: [] };
1763 * Update CSS classes provided by the theme.
1765 * For elements with theme logic hooks, this should be called any time there's a state change.
1767 * @param {OO.ui.Element} element Element for which to update classes
1769 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
1770 var $elements
= $( [] ),
1771 classes
= this.getElementClasses( element
);
1773 if ( element
.$icon
) {
1774 $elements
= $elements
.add( element
.$icon
);
1776 if ( element
.$indicator
) {
1777 $elements
= $elements
.add( element
.$indicator
);
1781 .removeClass( classes
.off
.join( ' ' ) )
1782 .addClass( classes
.on
.join( ' ' ) );
1788 OO
.ui
.Theme
.prototype.updateQueuedElementClasses = function () {
1790 for ( i
= 0; i
< this.elementClassesQueue
.length
; i
++ ) {
1791 this.updateElementClasses( this.elementClassesQueue
[ i
] );
1794 this.elementClassesQueue
= [];
1798 * Queue #updateElementClasses to be called for this element.
1800 * @localdoc QUnit tests override this method to directly call #queueUpdateElementClasses,
1801 * to make them synchronous.
1803 * @param {OO.ui.Element} element Element for which to update classes
1805 OO
.ui
.Theme
.prototype.queueUpdateElementClasses = function ( element
) {
1806 // Keep items in the queue unique. Use lastIndexOf to start checking from the end because that's
1807 // the most common case (this method is often called repeatedly for the same element).
1808 if ( this.elementClassesQueue
.lastIndexOf( element
) !== -1 ) {
1811 this.elementClassesQueue
.push( element
);
1812 this.debouncedUpdateQueuedElementClasses();
1816 * Get the transition duration in milliseconds for dialogs opening/closing
1818 * The dialog should be fully rendered this many milliseconds after the
1819 * ready process has executed.
1821 * @return {number} Transition duration in milliseconds
1823 OO
.ui
.Theme
.prototype.getDialogTransitionDuration = function () {
1828 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
1829 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
1830 * order in which users will navigate through the focusable elements via the "tab" key.
1833 * // TabIndexedElement is mixed into the ButtonWidget class
1834 * // to provide a tabIndex property.
1835 * var button1 = new OO.ui.ButtonWidget( {
1839 * var button2 = new OO.ui.ButtonWidget( {
1843 * var button3 = new OO.ui.ButtonWidget( {
1847 * var button4 = new OO.ui.ButtonWidget( {
1851 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
1857 * @param {Object} [config] Configuration options
1858 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
1859 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
1860 * functionality will be applied to it instead.
1861 * @cfg {string|number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
1862 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
1863 * to remove the element from the tab-navigation flow.
1865 OO
.ui
.mixin
.TabIndexedElement
= function OoUiMixinTabIndexedElement( config
) {
1866 // Configuration initialization
1867 config
= $.extend( { tabIndex
: 0 }, config
);
1870 this.$tabIndexed
= null;
1871 this.tabIndex
= null;
1874 this.connect( this, { disable
: 'onTabIndexedElementDisable' } );
1877 this.setTabIndex( config
.tabIndex
);
1878 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
1883 OO
.initClass( OO
.ui
.mixin
.TabIndexedElement
);
1888 * Set the element that should use the tabindex functionality.
1890 * This method is used to retarget a tabindex mixin so that its functionality applies
1891 * to the specified element. If an element is currently using the functionality, the mixin’s
1892 * effect on that element is removed before the new element is set up.
1894 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
1897 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
1898 var tabIndex
= this.tabIndex
;
1899 // Remove attributes from old $tabIndexed
1900 this.setTabIndex( null );
1901 // Force update of new $tabIndexed
1902 this.$tabIndexed
= $tabIndexed
;
1903 this.tabIndex
= tabIndex
;
1904 return this.updateTabIndex();
1908 * Set the value of the tabindex.
1910 * @param {string|number|null} tabIndex Tabindex value, or `null` for no tabindex
1913 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
1914 tabIndex
= /^-?\d+$/.test( tabIndex
) ? Number( tabIndex
) : null;
1916 if ( this.tabIndex
!== tabIndex
) {
1917 this.tabIndex
= tabIndex
;
1918 this.updateTabIndex();
1925 * Update the `tabindex` attribute, in case of changes to tab index or
1931 OO
.ui
.mixin
.TabIndexedElement
.prototype.updateTabIndex = function () {
1932 if ( this.$tabIndexed
) {
1933 if ( this.tabIndex
!== null ) {
1934 // Do not index over disabled elements
1935 this.$tabIndexed
.attr( {
1936 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
1937 // Support: ChromeVox and NVDA
1938 // These do not seem to inherit aria-disabled from parent elements
1939 'aria-disabled': this.isDisabled().toString()
1942 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
1949 * Handle disable events.
1952 * @param {boolean} disabled Element is disabled
1954 OO
.ui
.mixin
.TabIndexedElement
.prototype.onTabIndexedElementDisable = function () {
1955 this.updateTabIndex();
1959 * Get the value of the tabindex.
1961 * @return {number|null} Tabindex value
1963 OO
.ui
.mixin
.TabIndexedElement
.prototype.getTabIndex = function () {
1964 return this.tabIndex
;
1968 * Get an ID of a focusable element of this widget, if any, to be used for `<label for>` value.
1970 * If the element already has an ID then that is returned, otherwise unique ID is
1971 * generated, set on the element, and returned.
1973 * @return {string|null} The ID of the focusable element
1975 OO
.ui
.mixin
.TabIndexedElement
.prototype.getInputId = function () {
1978 if ( !this.$tabIndexed
) {
1981 if ( !this.isLabelableNode( this.$tabIndexed
) ) {
1985 id
= this.$tabIndexed
.attr( 'id' );
1986 if ( id
=== undefined ) {
1987 id
= OO
.ui
.generateElementId();
1988 this.$tabIndexed
.attr( 'id', id
);
1995 * Whether the node is 'labelable' according to the HTML spec
1996 * (i.e., whether it can be interacted with through a `<label for="…">`).
1997 * See: <https://html.spec.whatwg.org/multipage/forms.html#category-label>.
2000 * @param {jQuery} $node
2003 OO
.ui
.mixin
.TabIndexedElement
.prototype.isLabelableNode = function ( $node
) {
2005 labelableTags
= [ 'button', 'meter', 'output', 'progress', 'select', 'textarea' ],
2006 tagName
= $node
.prop( 'tagName' ).toLowerCase();
2008 if ( tagName
=== 'input' && $node
.attr( 'type' ) !== 'hidden' ) {
2011 if ( labelableTags
.indexOf( tagName
) !== -1 ) {
2018 * Focus this element.
2022 OO
.ui
.mixin
.TabIndexedElement
.prototype.focus = function () {
2023 if ( !this.isDisabled() ) {
2024 this.$tabIndexed
.focus();
2030 * Blur this element.
2034 OO
.ui
.mixin
.TabIndexedElement
.prototype.blur = function () {
2035 this.$tabIndexed
.blur();
2040 * @inheritdoc OO.ui.Widget
2042 OO
.ui
.mixin
.TabIndexedElement
.prototype.simulateLabelClick = function () {
2047 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
2048 * interface element that can be configured with access keys for accessibility.
2049 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
2051 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
2057 * @param {Object} [config] Configuration options
2058 * @cfg {jQuery} [$button] The button element created by the class.
2059 * If this configuration is omitted, the button element will use a generated `<a>`.
2060 * @cfg {boolean} [framed=true] Render the button with a frame
2062 OO
.ui
.mixin
.ButtonElement
= function OoUiMixinButtonElement( config
) {
2063 // Configuration initialization
2064 config
= config
|| {};
2067 this.$button
= null;
2069 this.active
= config
.active
!== undefined && config
.active
;
2070 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
2071 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
2072 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
2073 this.onKeyUpHandler
= this.onKeyUp
.bind( this );
2074 this.onClickHandler
= this.onClick
.bind( this );
2075 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
2078 this.$element
.addClass( 'oo-ui-buttonElement' );
2079 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
2080 this.setButtonElement( config
.$button
|| $( '<a>' ) );
2085 OO
.initClass( OO
.ui
.mixin
.ButtonElement
);
2087 /* Static Properties */
2090 * Cancel mouse down events.
2092 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
2093 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
2094 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
2099 * @property {boolean}
2101 OO
.ui
.mixin
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
2106 * A 'click' event is emitted when the button element is clicked.
2114 * Set the button element.
2116 * This method is used to retarget a button mixin so that its functionality applies to
2117 * the specified button element instead of the one created by the class. If a button element
2118 * is already set, the method will remove the mixin’s effect on that element.
2120 * @param {jQuery} $button Element to use as button
2122 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
2123 if ( this.$button
) {
2125 .removeClass( 'oo-ui-buttonElement-button' )
2126 .removeAttr( 'role accesskey' )
2128 mousedown
: this.onMouseDownHandler
,
2129 keydown
: this.onKeyDownHandler
,
2130 click
: this.onClickHandler
,
2131 keypress
: this.onKeyPressHandler
2135 this.$button
= $button
2136 .addClass( 'oo-ui-buttonElement-button' )
2138 mousedown
: this.onMouseDownHandler
,
2139 keydown
: this.onKeyDownHandler
,
2140 click
: this.onClickHandler
,
2141 keypress
: this.onKeyPressHandler
2144 // Add `role="button"` on `<a>` elements, where it's needed
2145 // `toUppercase()` is added for XHTML documents
2146 if ( this.$button
.prop( 'tagName' ).toUpperCase() === 'A' ) {
2147 this.$button
.attr( 'role', 'button' );
2152 * Handles mouse down events.
2155 * @param {jQuery.Event} e Mouse down event
2157 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown = function ( e
) {
2158 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
2161 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
2162 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
2163 // reliably remove the pressed class
2164 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
2165 // Prevent change of focus unless specifically configured otherwise
2166 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
2172 * Handles mouse up events.
2175 * @param {MouseEvent} e Mouse up event
2177 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp = function ( e
) {
2178 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
2181 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
2182 // Stop listening for mouseup, since we only needed this once
2183 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
2187 * Handles mouse click events.
2190 * @param {jQuery.Event} e Mouse click event
2193 OO
.ui
.mixin
.ButtonElement
.prototype.onClick = function ( e
) {
2194 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
2195 if ( this.emit( 'click' ) ) {
2202 * Handles key down events.
2205 * @param {jQuery.Event} e Key down event
2207 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyDown = function ( e
) {
2208 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
2211 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
2212 // Run the keyup handler no matter where the key is when the button is let go, so we can
2213 // reliably remove the pressed class
2214 this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler
, true );
2218 * Handles key up events.
2221 * @param {KeyboardEvent} e Key up event
2223 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyUp = function ( e
) {
2224 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
2227 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
2228 // Stop listening for keyup, since we only needed this once
2229 this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler
, true );
2233 * Handles key press events.
2236 * @param {jQuery.Event} e Key press event
2239 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyPress = function ( e
) {
2240 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
2241 if ( this.emit( 'click' ) ) {
2248 * Check if button has a frame.
2250 * @return {boolean} Button is framed
2252 OO
.ui
.mixin
.ButtonElement
.prototype.isFramed = function () {
2257 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
2259 * @param {boolean} [framed] Make button framed, omit to toggle
2262 OO
.ui
.mixin
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
2263 framed
= framed
=== undefined ? !this.framed
: !!framed
;
2264 if ( framed
!== this.framed
) {
2265 this.framed
= framed
;
2267 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
2268 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
2269 this.updateThemeClasses();
2276 * Set the button's active state.
2278 * The active state can be set on:
2280 * - {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} when it is selected
2281 * - {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} when it is toggle on
2282 * - {@link OO.ui.ButtonWidget ButtonWidget} when clicking the button would only refresh the page
2285 * @param {boolean} value Make button active
2288 OO
.ui
.mixin
.ButtonElement
.prototype.setActive = function ( value
) {
2289 this.active
= !!value
;
2290 this.$element
.toggleClass( 'oo-ui-buttonElement-active', this.active
);
2291 this.updateThemeClasses();
2296 * Check if the button is active
2299 * @return {boolean} The button is active
2301 OO
.ui
.mixin
.ButtonElement
.prototype.isActive = function () {
2306 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
2307 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
2308 * items from the group is done through the interface the class provides.
2309 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2311 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
2314 * @mixins OO.EmitterList
2318 * @param {Object} [config] Configuration options
2319 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
2320 * is omitted, the group element will use a generated `<div>`.
2322 OO
.ui
.mixin
.GroupElement
= function OoUiMixinGroupElement( config
) {
2323 // Configuration initialization
2324 config
= config
|| {};
2326 // Mixin constructors
2327 OO
.EmitterList
.call( this, config
);
2333 this.setGroupElement( config
.$group
|| $( '<div>' ) );
2338 OO
.mixinClass( OO
.ui
.mixin
.GroupElement
, OO
.EmitterList
);
2345 * A change event is emitted when the set of selected items changes.
2347 * @param {OO.ui.Element[]} items Items currently in the group
2353 * Set the group element.
2355 * If an element is already set, items will be moved to the new element.
2357 * @param {jQuery} $group Element to use as group
2359 OO
.ui
.mixin
.GroupElement
.prototype.setGroupElement = function ( $group
) {
2362 this.$group
= $group
;
2363 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2364 this.$group
.append( this.items
[ i
].$element
);
2369 * Get an item by its data.
2371 * Only the first item with matching data will be returned. To return all matching items,
2372 * use the #getItemsFromData method.
2374 * @param {Object} data Item data to search for
2375 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
2377 OO
.ui
.mixin
.GroupElement
.prototype.getItemFromData = function ( data
) {
2379 hash
= OO
.getHash( data
);
2381 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2382 item
= this.items
[ i
];
2383 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2392 * Get items by their data.
2394 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
2396 * @param {Object} data Item data to search for
2397 * @return {OO.ui.Element[]} Items with equivalent data
2399 OO
.ui
.mixin
.GroupElement
.prototype.getItemsFromData = function ( data
) {
2401 hash
= OO
.getHash( data
),
2404 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2405 item
= this.items
[ i
];
2406 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2415 * Add items to the group.
2417 * Items will be added to the end of the group array unless the optional `index` parameter specifies
2418 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
2420 * @param {OO.ui.Element[]} items An array of items to add to the group
2421 * @param {number} [index] Index of the insertion point
2424 OO
.ui
.mixin
.GroupElement
.prototype.addItems = function ( items
, index
) {
2426 OO
.EmitterList
.prototype.addItems
.call( this, items
, index
);
2428 this.emit( 'change', this.getItems() );
2435 OO
.ui
.mixin
.GroupElement
.prototype.moveItem = function ( items
, newIndex
) {
2436 // insertItemElements expects this.items to not have been modified yet, so call before the mixin
2437 this.insertItemElements( items
, newIndex
);
2440 newIndex
= OO
.EmitterList
.prototype.moveItem
.call( this, items
, newIndex
);
2448 OO
.ui
.mixin
.GroupElement
.prototype.insertItem = function ( item
, index
) {
2449 item
.setElementGroup( this );
2450 this.insertItemElements( item
, index
);
2453 index
= OO
.EmitterList
.prototype.insertItem
.call( this, item
, index
);
2459 * Insert elements into the group
2462 * @param {OO.ui.Element} itemWidget Item to insert
2463 * @param {number} index Insertion index
2465 OO
.ui
.mixin
.GroupElement
.prototype.insertItemElements = function ( itemWidget
, index
) {
2466 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
2467 this.$group
.append( itemWidget
.$element
);
2468 } else if ( index
=== 0 ) {
2469 this.$group
.prepend( itemWidget
.$element
);
2471 this.items
[ index
].$element
.before( itemWidget
.$element
);
2476 * Remove the specified items from a group.
2478 * Removed items are detached (not removed) from the DOM so that they may be reused.
2479 * To remove all items from a group, you may wish to use the #clearItems method instead.
2481 * @param {OO.ui.Element[]} items An array of items to remove
2484 OO
.ui
.mixin
.GroupElement
.prototype.removeItems = function ( items
) {
2485 var i
, len
, item
, index
;
2487 // Remove specific items elements
2488 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
2490 index
= this.items
.indexOf( item
);
2491 if ( index
!== -1 ) {
2492 item
.setElementGroup( null );
2493 item
.$element
.detach();
2498 OO
.EmitterList
.prototype.removeItems
.call( this, items
);
2500 this.emit( 'change', this.getItems() );
2505 * Clear all items from the group.
2507 * Cleared items are detached from the DOM, not removed, so that they may be reused.
2508 * To remove only a subset of items from a group, use the #removeItems method.
2512 OO
.ui
.mixin
.GroupElement
.prototype.clearItems = function () {
2515 // Remove all item elements
2516 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2517 this.items
[ i
].setElementGroup( null );
2518 this.items
[ i
].$element
.detach();
2522 OO
.EmitterList
.prototype.clearItems
.call( this );
2524 this.emit( 'change', this.getItems() );
2529 * IconElement is often mixed into other classes to generate an icon.
2530 * Icons are graphics, about the size of normal text. They are used to aid the user
2531 * in locating a control or to convey information in a space-efficient way. See the
2532 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
2533 * included in the library.
2535 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
2541 * @param {Object} [config] Configuration options
2542 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
2543 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
2544 * the icon element be set to an existing icon instead of the one generated by this class, set a
2545 * value using a jQuery selection. For example:
2547 * // Use a <div> tag instead of a <span>
2549 * // Use an existing icon element instead of the one generated by the class
2550 * $icon: this.$element
2551 * // Use an icon element from a child widget
2552 * $icon: this.childwidget.$element
2553 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
2554 * symbolic names. A map is used for i18n purposes and contains a `default` icon
2555 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
2556 * by the user's language.
2558 * Example of an i18n map:
2560 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2561 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
2562 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
2563 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
2564 * text. The icon title is displayed when users move the mouse over the icon.
2566 OO
.ui
.mixin
.IconElement
= function OoUiMixinIconElement( config
) {
2567 // Configuration initialization
2568 config
= config
|| {};
2573 this.iconTitle
= null;
2576 this.setIcon( config
.icon
|| this.constructor.static.icon
);
2577 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
2578 this.setIconElement( config
.$icon
|| $( '<span>' ) );
2583 OO
.initClass( OO
.ui
.mixin
.IconElement
);
2585 /* Static Properties */
2588 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
2589 * for i18n purposes and contains a `default` icon name and additional names keyed by
2590 * language code. The `default` name is used when no icon is keyed by the user's language.
2592 * Example of an i18n map:
2594 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2596 * Note: the static property will be overridden if the #icon configuration is used.
2600 * @property {Object|string}
2602 OO
.ui
.mixin
.IconElement
.static.icon
= null;
2605 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
2606 * function that returns title text, or `null` for no title.
2608 * The static property will be overridden if the #iconTitle configuration is used.
2612 * @property {string|Function|null}
2614 OO
.ui
.mixin
.IconElement
.static.iconTitle
= null;
2619 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
2620 * applies to the specified icon element instead of the one created by the class. If an icon
2621 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
2622 * and mixin methods will no longer affect the element.
2624 * @param {jQuery} $icon Element to use as icon
2626 OO
.ui
.mixin
.IconElement
.prototype.setIconElement = function ( $icon
) {
2629 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
2630 .removeAttr( 'title' );
2634 .addClass( 'oo-ui-iconElement-icon' )
2635 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
2636 if ( this.iconTitle
!== null ) {
2637 this.$icon
.attr( 'title', this.iconTitle
);
2640 this.updateThemeClasses();
2644 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
2645 * The icon parameter can also be set to a map of icon names. See the #icon config setting
2648 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
2649 * by language code, or `null` to remove the icon.
2652 OO
.ui
.mixin
.IconElement
.prototype.setIcon = function ( icon
) {
2653 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
2654 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
2656 if ( this.icon
!== icon
) {
2658 if ( this.icon
!== null ) {
2659 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
2661 if ( icon
!== null ) {
2662 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
2668 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
2669 this.updateThemeClasses();
2675 * Set the icon title. Use `null` to remove the title.
2677 * @param {string|Function|null} iconTitle A text string used as the icon title,
2678 * a function that returns title text, or `null` for no title.
2681 OO
.ui
.mixin
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
2682 iconTitle
= typeof iconTitle
=== 'function' ||
2683 ( typeof iconTitle
=== 'string' && iconTitle
.length
) ?
2684 OO
.ui
.resolveMsg( iconTitle
) : null;
2686 if ( this.iconTitle
!== iconTitle
) {
2687 this.iconTitle
= iconTitle
;
2689 if ( this.iconTitle
!== null ) {
2690 this.$icon
.attr( 'title', iconTitle
);
2692 this.$icon
.removeAttr( 'title' );
2701 * Get the symbolic name of the icon.
2703 * @return {string} Icon name
2705 OO
.ui
.mixin
.IconElement
.prototype.getIcon = function () {
2710 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
2712 * @return {string} Icon title text
2714 OO
.ui
.mixin
.IconElement
.prototype.getIconTitle = function () {
2715 return this.iconTitle
;
2719 * IndicatorElement is often mixed into other classes to generate an indicator.
2720 * Indicators are small graphics that are generally used in two ways:
2722 * - To draw attention to the status of an item. For example, an indicator might be
2723 * used to show that an item in a list has errors that need to be resolved.
2724 * - To clarify the function of a control that acts in an exceptional way (a button
2725 * that opens a menu instead of performing an action directly, for example).
2727 * For a list of indicators included in the library, please see the
2728 * [OOjs UI documentation on MediaWiki] [1].
2730 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2736 * @param {Object} [config] Configuration options
2737 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
2738 * configuration is omitted, the indicator element will use a generated `<span>`.
2739 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2740 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
2742 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2743 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
2744 * or a function that returns title text. The indicator title is displayed when users move
2745 * the mouse over the indicator.
2747 OO
.ui
.mixin
.IndicatorElement
= function OoUiMixinIndicatorElement( config
) {
2748 // Configuration initialization
2749 config
= config
|| {};
2752 this.$indicator
= null;
2753 this.indicator
= null;
2754 this.indicatorTitle
= null;
2757 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
2758 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
2759 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
2764 OO
.initClass( OO
.ui
.mixin
.IndicatorElement
);
2766 /* Static Properties */
2769 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2770 * The static property will be overridden if the #indicator configuration is used.
2774 * @property {string|null}
2776 OO
.ui
.mixin
.IndicatorElement
.static.indicator
= null;
2779 * A text string used as the indicator title, a function that returns title text, or `null`
2780 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
2784 * @property {string|Function|null}
2786 OO
.ui
.mixin
.IndicatorElement
.static.indicatorTitle
= null;
2791 * Set the indicator element.
2793 * If an element is already set, it will be cleaned up before setting up the new element.
2795 * @param {jQuery} $indicator Element to use as indicator
2797 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
2798 if ( this.$indicator
) {
2800 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
2801 .removeAttr( 'title' );
2804 this.$indicator
= $indicator
2805 .addClass( 'oo-ui-indicatorElement-indicator' )
2806 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
2807 if ( this.indicatorTitle
!== null ) {
2808 this.$indicator
.attr( 'title', this.indicatorTitle
);
2811 this.updateThemeClasses();
2815 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
2817 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
2820 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
2821 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
2823 if ( this.indicator
!== indicator
) {
2824 if ( this.$indicator
) {
2825 if ( this.indicator
!== null ) {
2826 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
2828 if ( indicator
!== null ) {
2829 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
2832 this.indicator
= indicator
;
2835 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
2836 this.updateThemeClasses();
2842 * Set the indicator title.
2844 * The title is displayed when a user moves the mouse over the indicator.
2846 * @param {string|Function|null} indicatorTitle Indicator title text, a function that returns text, or
2847 * `null` for no indicator title
2850 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorTitle = function ( indicatorTitle
) {
2851 indicatorTitle
= typeof indicatorTitle
=== 'function' ||
2852 ( typeof indicatorTitle
=== 'string' && indicatorTitle
.length
) ?
2853 OO
.ui
.resolveMsg( indicatorTitle
) : null;
2855 if ( this.indicatorTitle
!== indicatorTitle
) {
2856 this.indicatorTitle
= indicatorTitle
;
2857 if ( this.$indicator
) {
2858 if ( this.indicatorTitle
!== null ) {
2859 this.$indicator
.attr( 'title', indicatorTitle
);
2861 this.$indicator
.removeAttr( 'title' );
2870 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2872 * @return {string} Symbolic name of indicator
2874 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicator = function () {
2875 return this.indicator
;
2879 * Get the indicator title.
2881 * The title is displayed when a user moves the mouse over the indicator.
2883 * @return {string} Indicator title text
2885 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicatorTitle = function () {
2886 return this.indicatorTitle
;
2890 * LabelElement is often mixed into other classes to generate a label, which
2891 * helps identify the function of an interface element.
2892 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
2894 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
2900 * @param {Object} [config] Configuration options
2901 * @cfg {jQuery} [$label] The label element created by the class. If this
2902 * configuration is omitted, the label element will use a generated `<span>`.
2903 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
2904 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
2905 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
2906 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
2908 OO
.ui
.mixin
.LabelElement
= function OoUiMixinLabelElement( config
) {
2909 // Configuration initialization
2910 config
= config
|| {};
2917 this.setLabel( config
.label
|| this.constructor.static.label
);
2918 this.setLabelElement( config
.$label
|| $( '<span>' ) );
2923 OO
.initClass( OO
.ui
.mixin
.LabelElement
);
2928 * @event labelChange
2929 * @param {string} value
2932 /* Static Properties */
2935 * The label text. The label can be specified as a plaintext string, a function that will
2936 * produce a string in the future, or `null` for no label. The static value will
2937 * be overridden if a label is specified with the #label config option.
2941 * @property {string|Function|null}
2943 OO
.ui
.mixin
.LabelElement
.static.label
= null;
2945 /* Static methods */
2948 * Highlight the first occurrence of the query in the given text
2950 * @param {string} text Text
2951 * @param {string} query Query to find
2952 * @return {jQuery} Text with the first match of the query
2953 * sub-string wrapped in highlighted span
2955 OO
.ui
.mixin
.LabelElement
.static.highlightQuery = function ( text
, query
) {
2956 var $result
= $( '<span>' ),
2957 offset
= text
.toLowerCase().indexOf( query
.toLowerCase() );
2959 if ( !query
.length
|| offset
=== -1 ) {
2960 return $result
.text( text
);
2963 document
.createTextNode( text
.slice( 0, offset
) ),
2965 .addClass( 'oo-ui-labelElement-label-highlight' )
2966 .text( text
.slice( offset
, offset
+ query
.length
) ),
2967 document
.createTextNode( text
.slice( offset
+ query
.length
) )
2969 return $result
.contents();
2975 * Set the label element.
2977 * If an element is already set, it will be cleaned up before setting up the new element.
2979 * @param {jQuery} $label Element to use as label
2981 OO
.ui
.mixin
.LabelElement
.prototype.setLabelElement = function ( $label
) {
2982 if ( this.$label
) {
2983 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
2986 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
2987 this.setLabelContent( this.label
);
2993 * An empty string will result in the label being hidden. A string containing only whitespace will
2994 * be converted to a single ` `.
2996 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
2997 * text; or null for no label
3000 OO
.ui
.mixin
.LabelElement
.prototype.setLabel = function ( label
) {
3001 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
3002 label
= ( ( typeof label
=== 'string' || label
instanceof jQuery
) && label
.length
) || ( label
instanceof OO
.ui
.HtmlSnippet
&& label
.toString().length
) ? label
: null;
3004 if ( this.label
!== label
) {
3005 if ( this.$label
) {
3006 this.setLabelContent( label
);
3009 this.emit( 'labelChange' );
3012 this.$element
.toggleClass( 'oo-ui-labelElement', !!this.label
);
3018 * Set the label as plain text with a highlighted query
3020 * @param {string} text Text label to set
3021 * @param {string} query Substring of text to highlight
3024 OO
.ui
.mixin
.LabelElement
.prototype.setHighlightedQuery = function ( text
, query
) {
3025 return this.setLabel( this.constructor.static.highlightQuery( text
, query
) );
3031 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
3032 * text; or null for no label
3034 OO
.ui
.mixin
.LabelElement
.prototype.getLabel = function () {
3039 * Set the content of the label.
3041 * Do not call this method until after the label element has been set by #setLabelElement.
3044 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
3045 * text; or null for no label
3047 OO
.ui
.mixin
.LabelElement
.prototype.setLabelContent = function ( label
) {
3048 if ( typeof label
=== 'string' ) {
3049 if ( label
.match( /^\s*$/ ) ) {
3050 // Convert whitespace only string to a single non-breaking space
3051 this.$label
.html( ' ' );
3053 this.$label
.text( label
);
3055 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
3056 this.$label
.html( label
.toString() );
3057 } else if ( label
instanceof jQuery
) {
3058 this.$label
.empty().append( label
);
3060 this.$label
.empty();
3065 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
3066 * additional functionality to an element created by another class. The class provides
3067 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
3068 * which are used to customize the look and feel of a widget to better describe its
3069 * importance and functionality.
3071 * The library currently contains the following styling flags for general use:
3073 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
3074 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
3075 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
3077 * The flags affect the appearance of the buttons:
3080 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
3081 * var button1 = new OO.ui.ButtonWidget( {
3082 * label: 'Constructive',
3083 * flags: 'constructive'
3085 * var button2 = new OO.ui.ButtonWidget( {
3086 * label: 'Destructive',
3087 * flags: 'destructive'
3089 * var button3 = new OO.ui.ButtonWidget( {
3090 * label: 'Progressive',
3091 * flags: 'progressive'
3093 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
3095 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
3096 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
3098 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
3104 * @param {Object} [config] Configuration options
3105 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
3106 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
3107 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
3108 * @cfg {jQuery} [$flagged] The flagged element. By default,
3109 * the flagged functionality is applied to the element created by the class ($element).
3110 * If a different element is specified, the flagged functionality will be applied to it instead.
3112 OO
.ui
.mixin
.FlaggedElement
= function OoUiMixinFlaggedElement( config
) {
3113 // Configuration initialization
3114 config
= config
|| {};
3118 this.$flagged
= null;
3121 this.setFlags( config
.flags
);
3122 this.setFlaggedElement( config
.$flagged
|| this.$element
);
3129 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
3130 * parameter contains the name of each modified flag and indicates whether it was
3133 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
3134 * that the flag was added, `false` that the flag was removed.
3140 * Set the flagged element.
3142 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
3143 * If an element is already set, the method will remove the mixin’s effect on that element.
3145 * @param {jQuery} $flagged Element that should be flagged
3147 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
3148 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
3149 return 'oo-ui-flaggedElement-' + flag
;
3152 if ( this.$flagged
) {
3153 this.$flagged
.removeClass( classNames
);
3156 this.$flagged
= $flagged
.addClass( classNames
);
3160 * Check if the specified flag is set.
3162 * @param {string} flag Name of flag
3163 * @return {boolean} The flag is set
3165 OO
.ui
.mixin
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
3166 // This may be called before the constructor, thus before this.flags is set
3167 return this.flags
&& ( flag
in this.flags
);
3171 * Get the names of all flags set.
3173 * @return {string[]} Flag names
3175 OO
.ui
.mixin
.FlaggedElement
.prototype.getFlags = function () {
3176 // This may be called before the constructor, thus before this.flags is set
3177 return Object
.keys( this.flags
|| {} );
3186 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags = function () {
3187 var flag
, className
,
3190 classPrefix
= 'oo-ui-flaggedElement-';
3192 for ( flag
in this.flags
) {
3193 className
= classPrefix
+ flag
;
3194 changes
[ flag
] = false;
3195 delete this.flags
[ flag
];
3196 remove
.push( className
);
3199 if ( this.$flagged
) {
3200 this.$flagged
.removeClass( remove
.join( ' ' ) );
3203 this.updateThemeClasses();
3204 this.emit( 'flag', changes
);
3210 * Add one or more flags.
3212 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
3213 * or an object keyed by flag name with a boolean value that indicates whether the flag should
3214 * be added (`true`) or removed (`false`).
3218 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags = function ( flags
) {
3219 var i
, len
, flag
, className
,
3223 classPrefix
= 'oo-ui-flaggedElement-';
3225 if ( typeof flags
=== 'string' ) {
3226 className
= classPrefix
+ flags
;
3228 if ( !this.flags
[ flags
] ) {
3229 this.flags
[ flags
] = true;
3230 add
.push( className
);
3232 } else if ( Array
.isArray( flags
) ) {
3233 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
3235 className
= classPrefix
+ flag
;
3237 if ( !this.flags
[ flag
] ) {
3238 changes
[ flag
] = true;
3239 this.flags
[ flag
] = true;
3240 add
.push( className
);
3243 } else if ( OO
.isPlainObject( flags
) ) {
3244 for ( flag
in flags
) {
3245 className
= classPrefix
+ flag
;
3246 if ( flags
[ flag
] ) {
3248 if ( !this.flags
[ flag
] ) {
3249 changes
[ flag
] = true;
3250 this.flags
[ flag
] = true;
3251 add
.push( className
);
3255 if ( this.flags
[ flag
] ) {
3256 changes
[ flag
] = false;
3257 delete this.flags
[ flag
];
3258 remove
.push( className
);
3264 if ( this.$flagged
) {
3266 .addClass( add
.join( ' ' ) )
3267 .removeClass( remove
.join( ' ' ) );
3270 this.updateThemeClasses();
3271 this.emit( 'flag', changes
);
3277 * TitledElement is mixed into other classes to provide a `title` attribute.
3278 * Titles are rendered by the browser and are made visible when the user moves
3279 * the mouse over the element. Titles are not visible on touch devices.
3282 * // TitledElement provides a 'title' attribute to the
3283 * // ButtonWidget class
3284 * var button = new OO.ui.ButtonWidget( {
3285 * label: 'Button with Title',
3286 * title: 'I am a button'
3288 * $( 'body' ).append( button.$element );
3294 * @param {Object} [config] Configuration options
3295 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
3296 * If this config is omitted, the title functionality is applied to $element, the
3297 * element created by the class.
3298 * @cfg {string|Function} [title] The title text or a function that returns text. If
3299 * this config is omitted, the value of the {@link #static-title static title} property is used.
3301 OO
.ui
.mixin
.TitledElement
= function OoUiMixinTitledElement( config
) {
3302 // Configuration initialization
3303 config
= config
|| {};
3306 this.$titled
= null;
3310 this.setTitle( config
.title
!== undefined ? config
.title
: this.constructor.static.title
);
3311 this.setTitledElement( config
.$titled
|| this.$element
);
3316 OO
.initClass( OO
.ui
.mixin
.TitledElement
);
3318 /* Static Properties */
3321 * The title text, a function that returns text, or `null` for no title. The value of the static property
3322 * is overridden if the #title config option is used.
3326 * @property {string|Function|null}
3328 OO
.ui
.mixin
.TitledElement
.static.title
= null;
3333 * Set the titled element.
3335 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
3336 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
3338 * @param {jQuery} $titled Element that should use the 'titled' functionality
3340 OO
.ui
.mixin
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
3341 if ( this.$titled
) {
3342 this.$titled
.removeAttr( 'title' );
3345 this.$titled
= $titled
;
3347 this.$titled
.attr( 'title', this.title
);
3354 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
3357 OO
.ui
.mixin
.TitledElement
.prototype.setTitle = function ( title
) {
3358 title
= typeof title
=== 'function' ? OO
.ui
.resolveMsg( title
) : title
;
3359 title
= ( typeof title
=== 'string' && title
.length
) ? title
: null;
3361 if ( this.title
!== title
) {
3362 if ( this.$titled
) {
3363 if ( title
!== null ) {
3364 this.$titled
.attr( 'title', title
);
3366 this.$titled
.removeAttr( 'title' );
3378 * @return {string} Title string
3380 OO
.ui
.mixin
.TitledElement
.prototype.getTitle = function () {
3385 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
3386 * Accesskeys allow an user to go to a specific element by using
3387 * a shortcut combination of a browser specific keys + the key
3391 * // AccessKeyedElement provides an 'accesskey' attribute to the
3392 * // ButtonWidget class
3393 * var button = new OO.ui.ButtonWidget( {
3394 * label: 'Button with Accesskey',
3397 * $( 'body' ).append( button.$element );
3403 * @param {Object} [config] Configuration options
3404 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
3405 * If this config is omitted, the accesskey functionality is applied to $element, the
3406 * element created by the class.
3407 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
3408 * this config is omitted, no accesskey will be added.
3410 OO
.ui
.mixin
.AccessKeyedElement
= function OoUiMixinAccessKeyedElement( config
) {
3411 // Configuration initialization
3412 config
= config
|| {};
3415 this.$accessKeyed
= null;
3416 this.accessKey
= null;
3419 this.setAccessKey( config
.accessKey
|| null );
3420 this.setAccessKeyedElement( config
.$accessKeyed
|| this.$element
);
3425 OO
.initClass( OO
.ui
.mixin
.AccessKeyedElement
);
3427 /* Static Properties */
3430 * The access key, a function that returns a key, or `null` for no accesskey.
3434 * @property {string|Function|null}
3436 OO
.ui
.mixin
.AccessKeyedElement
.static.accessKey
= null;
3441 * Set the accesskeyed element.
3443 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
3444 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
3446 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
3448 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKeyedElement = function ( $accessKeyed
) {
3449 if ( this.$accessKeyed
) {
3450 this.$accessKeyed
.removeAttr( 'accesskey' );
3453 this.$accessKeyed
= $accessKeyed
;
3454 if ( this.accessKey
) {
3455 this.$accessKeyed
.attr( 'accesskey', this.accessKey
);
3462 * @param {string|Function|null} accessKey Key, a function that returns a key, or `null` for no accesskey
3465 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKey = function ( accessKey
) {
3466 accessKey
= typeof accessKey
=== 'string' ? OO
.ui
.resolveMsg( accessKey
) : null;
3468 if ( this.accessKey
!== accessKey
) {
3469 if ( this.$accessKeyed
) {
3470 if ( accessKey
!== null ) {
3471 this.$accessKeyed
.attr( 'accesskey', accessKey
);
3473 this.$accessKeyed
.removeAttr( 'accesskey' );
3476 this.accessKey
= accessKey
;
3485 * @return {string} accessKey string
3487 OO
.ui
.mixin
.AccessKeyedElement
.prototype.getAccessKey = function () {
3488 return this.accessKey
;
3492 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
3493 * feels, and functionality can be customized via the class’s configuration options
3494 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
3497 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
3500 * // A button widget
3501 * var button = new OO.ui.ButtonWidget( {
3502 * label: 'Button with Icon',
3504 * iconTitle: 'Remove'
3506 * $( 'body' ).append( button.$element );
3508 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
3511 * @extends OO.ui.Widget
3512 * @mixins OO.ui.mixin.ButtonElement
3513 * @mixins OO.ui.mixin.IconElement
3514 * @mixins OO.ui.mixin.IndicatorElement
3515 * @mixins OO.ui.mixin.LabelElement
3516 * @mixins OO.ui.mixin.TitledElement
3517 * @mixins OO.ui.mixin.FlaggedElement
3518 * @mixins OO.ui.mixin.TabIndexedElement
3519 * @mixins OO.ui.mixin.AccessKeyedElement
3522 * @param {Object} [config] Configuration options
3523 * @cfg {boolean} [active=false] Whether button should be shown as active
3524 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
3525 * @cfg {string} [target] The frame or window in which to open the hyperlink.
3526 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
3528 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
3529 // Configuration initialization
3530 config
= config
|| {};
3532 // Parent constructor
3533 OO
.ui
.ButtonWidget
.parent
.call( this, config
);
3535 // Mixin constructors
3536 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
3537 OO
.ui
.mixin
.IconElement
.call( this, config
);
3538 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
3539 OO
.ui
.mixin
.LabelElement
.call( this, config
);
3540 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
3541 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
3542 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
3543 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$button
} ) );
3548 this.noFollow
= false;
3551 this.connect( this, { disable
: 'onDisable' } );
3554 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
3556 .addClass( 'oo-ui-buttonWidget' )
3557 .append( this.$button
);
3558 this.setActive( config
.active
);
3559 this.setHref( config
.href
);
3560 this.setTarget( config
.target
);
3561 this.setNoFollow( config
.noFollow
);
3566 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
3567 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
3568 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IconElement
);
3569 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
3570 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.LabelElement
);
3571 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TitledElement
);
3572 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
3573 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
3574 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
3576 /* Static Properties */
3582 OO
.ui
.ButtonWidget
.static.cancelButtonMouseDownEvents
= false;
3588 OO
.ui
.ButtonWidget
.static.tagName
= 'span';
3593 * Get hyperlink location.
3595 * @return {string} Hyperlink location
3597 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
3602 * Get hyperlink target.
3604 * @return {string} Hyperlink target
3606 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
3611 * Get search engine traversal hint.
3613 * @return {boolean} Whether search engines should avoid traversing this hyperlink
3615 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
3616 return this.noFollow
;
3620 * Set hyperlink location.
3622 * @param {string|null} href Hyperlink location, null to remove
3624 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
3625 href
= typeof href
=== 'string' ? href
: null;
3626 if ( href
!== null && !OO
.ui
.isSafeUrl( href
) ) {
3630 if ( href
!== this.href
) {
3639 * Update the `href` attribute, in case of changes to href or
3645 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
3646 if ( this.href
!== null && !this.isDisabled() ) {
3647 this.$button
.attr( 'href', this.href
);
3649 this.$button
.removeAttr( 'href' );
3656 * Handle disable events.
3659 * @param {boolean} disabled Element is disabled
3661 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
3666 * Set hyperlink target.
3668 * @param {string|null} target Hyperlink target, null to remove
3670 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
3671 target
= typeof target
=== 'string' ? target
: null;
3673 if ( target
!== this.target
) {
3674 this.target
= target
;
3675 if ( target
!== null ) {
3676 this.$button
.attr( 'target', target
);
3678 this.$button
.removeAttr( 'target' );
3686 * Set search engine traversal hint.
3688 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
3690 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
3691 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
3693 if ( noFollow
!== this.noFollow
) {
3694 this.noFollow
= noFollow
;
3696 this.$button
.attr( 'rel', 'nofollow' );
3698 this.$button
.removeAttr( 'rel' );
3705 // Override method visibility hints from ButtonElement
3716 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
3717 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
3718 * removed, and cleared from the group.
3721 * // Example: A ButtonGroupWidget with two buttons
3722 * var button1 = new OO.ui.PopupButtonWidget( {
3723 * label: 'Select a category',
3726 * $content: $( '<p>List of categories...</p>' ),
3731 * var button2 = new OO.ui.ButtonWidget( {
3734 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
3735 * items: [button1, button2]
3737 * $( 'body' ).append( buttonGroup.$element );
3740 * @extends OO.ui.Widget
3741 * @mixins OO.ui.mixin.GroupElement
3744 * @param {Object} [config] Configuration options
3745 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
3747 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
3748 // Configuration initialization
3749 config
= config
|| {};
3751 // Parent constructor
3752 OO
.ui
.ButtonGroupWidget
.parent
.call( this, config
);
3754 // Mixin constructors
3755 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
3758 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
3759 if ( Array
.isArray( config
.items
) ) {
3760 this.addItems( config
.items
);
3766 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
3767 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.GroupElement
);
3769 /* Static Properties */
3775 OO
.ui
.ButtonGroupWidget
.static.tagName
= 'span';
3784 OO
.ui
.ButtonGroupWidget
.prototype.focus = function () {
3785 if ( !this.isDisabled() ) {
3786 if ( this.items
[ 0 ] ) {
3787 this.items
[ 0 ].focus();
3796 OO
.ui
.ButtonGroupWidget
.prototype.simulateLabelClick = function () {
3801 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
3802 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
3803 * for a list of icons included in the library.
3806 * // An icon widget with a label
3807 * var myIcon = new OO.ui.IconWidget( {
3811 * // Create a label.
3812 * var iconLabel = new OO.ui.LabelWidget( {
3815 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
3817 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
3820 * @extends OO.ui.Widget
3821 * @mixins OO.ui.mixin.IconElement
3822 * @mixins OO.ui.mixin.TitledElement
3823 * @mixins OO.ui.mixin.FlaggedElement
3826 * @param {Object} [config] Configuration options
3828 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
3829 // Configuration initialization
3830 config
= config
|| {};
3832 // Parent constructor
3833 OO
.ui
.IconWidget
.parent
.call( this, config
);
3835 // Mixin constructors
3836 OO
.ui
.mixin
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
3837 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
3838 OO
.ui
.mixin
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
3841 this.$element
.addClass( 'oo-ui-iconWidget' );
3846 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
3847 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.IconElement
);
3848 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.TitledElement
);
3849 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.FlaggedElement
);
3851 /* Static Properties */
3857 OO
.ui
.IconWidget
.static.tagName
= 'span';
3860 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
3861 * attention to the status of an item or to clarify the function of a control. For a list of
3862 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
3865 * // Example of an indicator widget
3866 * var indicator1 = new OO.ui.IndicatorWidget( {
3867 * indicator: 'alert'
3870 * // Create a fieldset layout to add a label
3871 * var fieldset = new OO.ui.FieldsetLayout();
3872 * fieldset.addItems( [
3873 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
3875 * $( 'body' ).append( fieldset.$element );
3877 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3880 * @extends OO.ui.Widget
3881 * @mixins OO.ui.mixin.IndicatorElement
3882 * @mixins OO.ui.mixin.TitledElement
3885 * @param {Object} [config] Configuration options
3887 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
3888 // Configuration initialization
3889 config
= config
|| {};
3891 // Parent constructor
3892 OO
.ui
.IndicatorWidget
.parent
.call( this, config
);
3894 // Mixin constructors
3895 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
3896 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
3899 this.$element
.addClass( 'oo-ui-indicatorWidget' );
3904 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
3905 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.IndicatorElement
);
3906 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.TitledElement
);
3908 /* Static Properties */
3914 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
3917 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
3918 * be configured with a `label` option that is set to a string, a label node, or a function:
3920 * - String: a plaintext string
3921 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
3922 * label that includes a link or special styling, such as a gray color or additional graphical elements.
3923 * - Function: a function that will produce a string in the future. Functions are used
3924 * in cases where the value of the label is not currently defined.
3926 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
3927 * will come into focus when the label is clicked.
3930 * // Examples of LabelWidgets
3931 * var label1 = new OO.ui.LabelWidget( {
3932 * label: 'plaintext label'
3934 * var label2 = new OO.ui.LabelWidget( {
3935 * label: $( '<a href="default.html">jQuery label</a>' )
3937 * // Create a fieldset layout with fields for each example
3938 * var fieldset = new OO.ui.FieldsetLayout();
3939 * fieldset.addItems( [
3940 * new OO.ui.FieldLayout( label1 ),
3941 * new OO.ui.FieldLayout( label2 )
3943 * $( 'body' ).append( fieldset.$element );
3946 * @extends OO.ui.Widget
3947 * @mixins OO.ui.mixin.LabelElement
3948 * @mixins OO.ui.mixin.TitledElement
3951 * @param {Object} [config] Configuration options
3952 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
3953 * Clicking the label will focus the specified input field.
3955 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
3956 // Configuration initialization
3957 config
= config
|| {};
3959 // Parent constructor
3960 OO
.ui
.LabelWidget
.parent
.call( this, config
);
3962 // Mixin constructors
3963 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
3964 OO
.ui
.mixin
.TitledElement
.call( this, config
);
3967 this.input
= config
.input
;
3971 if ( this.input
.getInputId() ) {
3972 this.$element
.attr( 'for', this.input
.getInputId() );
3974 this.$label
.on( 'click', function () {
3975 this.input
.simulateLabelClick();
3980 this.$element
.addClass( 'oo-ui-labelWidget' );
3985 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
3986 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.LabelElement
);
3987 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.TitledElement
);
3989 /* Static Properties */
3995 OO
.ui
.LabelWidget
.static.tagName
= 'label';
3998 * PendingElement is a mixin that is used to create elements that notify users that something is happening
3999 * and that they should wait before proceeding. The pending state is visually represented with a pending
4000 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
4001 * field of a {@link OO.ui.TextInputWidget text input widget}.
4003 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
4004 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
4005 * in process dialogs.
4008 * function MessageDialog( config ) {
4009 * MessageDialog.parent.call( this, config );
4011 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
4013 * MessageDialog.static.name = 'myMessageDialog';
4014 * MessageDialog.static.actions = [
4015 * { action: 'save', label: 'Done', flags: 'primary' },
4016 * { label: 'Cancel', flags: 'safe' }
4019 * MessageDialog.prototype.initialize = function () {
4020 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
4021 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
4022 * 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>' );
4023 * this.$body.append( this.content.$element );
4025 * MessageDialog.prototype.getBodyHeight = function () {
4028 * MessageDialog.prototype.getActionProcess = function ( action ) {
4029 * var dialog = this;
4030 * if ( action === 'save' ) {
4031 * dialog.getActions().get({actions: 'save'})[0].pushPending();
4032 * return new OO.ui.Process()
4034 * .next( function () {
4035 * dialog.getActions().get({actions: 'save'})[0].popPending();
4038 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
4041 * var windowManager = new OO.ui.WindowManager();
4042 * $( 'body' ).append( windowManager.$element );
4044 * var dialog = new MessageDialog();
4045 * windowManager.addWindows( [ dialog ] );
4046 * windowManager.openWindow( dialog );
4052 * @param {Object} [config] Configuration options
4053 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
4055 OO
.ui
.mixin
.PendingElement
= function OoUiMixinPendingElement( config
) {
4056 // Configuration initialization
4057 config
= config
|| {};
4061 this.$pending
= null;
4064 this.setPendingElement( config
.$pending
|| this.$element
);
4069 OO
.initClass( OO
.ui
.mixin
.PendingElement
);
4074 * Set the pending element (and clean up any existing one).
4076 * @param {jQuery} $pending The element to set to pending.
4078 OO
.ui
.mixin
.PendingElement
.prototype.setPendingElement = function ( $pending
) {
4079 if ( this.$pending
) {
4080 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
4083 this.$pending
= $pending
;
4084 if ( this.pending
> 0 ) {
4085 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
4090 * Check if an element is pending.
4092 * @return {boolean} Element is pending
4094 OO
.ui
.mixin
.PendingElement
.prototype.isPending = function () {
4095 return !!this.pending
;
4099 * Increase the pending counter. The pending state will remain active until the counter is zero
4100 * (i.e., the number of calls to #pushPending and #popPending is the same).
4104 OO
.ui
.mixin
.PendingElement
.prototype.pushPending = function () {
4105 if ( this.pending
=== 0 ) {
4106 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
4107 this.updateThemeClasses();
4115 * Decrease the pending counter. The pending state will remain active until the counter is zero
4116 * (i.e., the number of calls to #pushPending and #popPending is the same).
4120 OO
.ui
.mixin
.PendingElement
.prototype.popPending = function () {
4121 if ( this.pending
=== 1 ) {
4122 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
4123 this.updateThemeClasses();
4125 this.pending
= Math
.max( 0, this.pending
- 1 );
4131 * Element that will stick adjacent to a specified container, even when it is inserted elsewhere
4132 * in the document (for example, in an OO.ui.Window's $overlay).
4134 * The elements's position is automatically calculated and maintained when window is resized or the
4135 * page is scrolled. If you reposition the container manually, you have to call #position to make
4136 * sure the element is still placed correctly.
4138 * As positioning is only possible when both the element and the container are attached to the DOM
4139 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
4140 * the #toggle method to display a floating popup, for example.
4146 * @param {Object} [config] Configuration options
4147 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
4148 * @cfg {jQuery} [$floatableContainer] Node to position adjacent to
4149 * @cfg {string} [verticalPosition='below'] Where to position $floatable vertically:
4150 * 'below': Directly below $floatableContainer, aligning f's top edge with fC's bottom edge
4151 * 'above': Directly above $floatableContainer, aligning f's bottom edge with fC's top edge
4152 * 'top': Align the top edge with $floatableContainer's top edge
4153 * 'bottom': Align the bottom edge with $floatableContainer's bottom edge
4154 * 'center': Vertically align the center with $floatableContainer's center
4155 * @cfg {string} [horizontalPosition='start'] Where to position $floatable horizontally:
4156 * 'before': Directly before $floatableContainer, aligning f's end edge with fC's start edge
4157 * 'after': Directly after $floatableContainer, algining f's start edge with fC's end edge
4158 * 'start': Align the start (left in LTR, right in RTL) edge with $floatableContainer's start edge
4159 * 'end': Align the end (right in LTR, left in RTL) edge with $floatableContainer's end edge
4160 * 'center': Horizontally align the center with $floatableContainer's center
4161 * @cfg {boolean} [hideWhenOutOfView=true] Whether to hide the floatable element if the container
4164 OO
.ui
.mixin
.FloatableElement
= function OoUiMixinFloatableElement( config
) {
4165 // Configuration initialization
4166 config
= config
|| {};
4169 this.$floatable
= null;
4170 this.$floatableContainer
= null;
4171 this.$floatableWindow
= null;
4172 this.$floatableClosestScrollable
= null;
4173 this.onFloatableScrollHandler
= this.position
.bind( this );
4174 this.onFloatableWindowResizeHandler
= this.position
.bind( this );
4177 this.setFloatableContainer( config
.$floatableContainer
);
4178 this.setFloatableElement( config
.$floatable
|| this.$element
);
4179 this.setVerticalPosition( config
.verticalPosition
|| 'below' );
4180 this.setHorizontalPosition( config
.horizontalPosition
|| 'start' );
4181 this.hideWhenOutOfView
= config
.hideWhenOutOfView
=== undefined ? true : !!config
.hideWhenOutOfView
;
4187 * Set floatable element.
4189 * If an element is already set, it will be cleaned up before setting up the new element.
4191 * @param {jQuery} $floatable Element to make floatable
4193 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableElement = function ( $floatable
) {
4194 if ( this.$floatable
) {
4195 this.$floatable
.removeClass( 'oo-ui-floatableElement-floatable' );
4196 this.$floatable
.css( { left
: '', top
: '' } );
4199 this.$floatable
= $floatable
.addClass( 'oo-ui-floatableElement-floatable' );
4204 * Set floatable container.
4206 * The element will be positioned relative to the specified container.
4208 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
4210 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableContainer = function ( $floatableContainer
) {
4211 this.$floatableContainer
= $floatableContainer
;
4212 if ( this.$floatable
) {
4218 * Change how the element is positioned vertically.
4220 * @param {string} position 'below', 'above', 'top', 'bottom' or 'center'
4222 OO
.ui
.mixin
.FloatableElement
.prototype.setVerticalPosition = function ( position
) {
4223 if ( [ 'below', 'above', 'top', 'bottom', 'center' ].indexOf( position
) === -1 ) {
4224 throw new Error( 'Invalid value for vertical position: ' + position
);
4226 if ( this.verticalPosition
!== position
) {
4227 this.verticalPosition
= position
;
4228 if ( this.$floatable
) {
4235 * Change how the element is positioned horizontally.
4237 * @param {string} position 'before', 'after', 'start', 'end' or 'center'
4239 OO
.ui
.mixin
.FloatableElement
.prototype.setHorizontalPosition = function ( position
) {
4240 if ( [ 'before', 'after', 'start', 'end', 'center' ].indexOf( position
) === -1 ) {
4241 throw new Error( 'Invalid value for horizontal position: ' + position
);
4243 if ( this.horizontalPosition
!== position
) {
4244 this.horizontalPosition
= position
;
4245 if ( this.$floatable
) {
4252 * Toggle positioning.
4254 * Do not turn positioning on until after the element is attached to the DOM and visible.
4256 * @param {boolean} [positioning] Enable positioning, omit to toggle
4259 OO
.ui
.mixin
.FloatableElement
.prototype.togglePositioning = function ( positioning
) {
4260 var closestScrollableOfContainer
;
4262 if ( !this.$floatable
|| !this.$floatableContainer
) {
4266 positioning
= positioning
=== undefined ? !this.positioning
: !!positioning
;
4268 if ( positioning
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
4269 OO
.ui
.warnDeprecation( 'FloatableElement#togglePositioning: Before calling this method, the element must be attached to the DOM.' );
4270 this.warnedUnattached
= true;
4273 if ( this.positioning
!== positioning
) {
4274 this.positioning
= positioning
;
4276 this.needsCustomPosition
=
4277 this.verticalPostion
!== 'below' ||
4278 this.horizontalPosition
!== 'start' ||
4279 !OO
.ui
.contains( this.$floatableContainer
[ 0 ], this.$floatable
[ 0 ] );
4281 closestScrollableOfContainer
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatableContainer
[ 0 ] );
4282 // If the scrollable is the root, we have to listen to scroll events
4283 // on the window because of browser inconsistencies.
4284 if ( $( closestScrollableOfContainer
).is( 'html, body' ) ) {
4285 closestScrollableOfContainer
= OO
.ui
.Element
.static.getWindow( closestScrollableOfContainer
);
4288 if ( positioning
) {
4289 this.$floatableWindow
= $( this.getElementWindow() );
4290 this.$floatableWindow
.on( 'resize', this.onFloatableWindowResizeHandler
);
4292 this.$floatableClosestScrollable
= $( closestScrollableOfContainer
);
4293 this.$floatableClosestScrollable
.on( 'scroll', this.onFloatableScrollHandler
);
4295 // Initial position after visible
4298 if ( this.$floatableWindow
) {
4299 this.$floatableWindow
.off( 'resize', this.onFloatableWindowResizeHandler
);
4300 this.$floatableWindow
= null;
4303 if ( this.$floatableClosestScrollable
) {
4304 this.$floatableClosestScrollable
.off( 'scroll', this.onFloatableScrollHandler
);
4305 this.$floatableClosestScrollable
= null;
4308 this.$floatable
.css( { left
: '', right
: '', top
: '' } );
4316 * Check whether the bottom edge of the given element is within the viewport of the given container.
4319 * @param {jQuery} $element
4320 * @param {jQuery} $container
4323 OO
.ui
.mixin
.FloatableElement
.prototype.isElementInViewport = function ( $element
, $container
) {
4324 var elemRect
, contRect
, topEdgeInBounds
, bottomEdgeInBounds
, leftEdgeInBounds
, rightEdgeInBounds
,
4325 startEdgeInBounds
, endEdgeInBounds
,
4326 direction
= $element
.css( 'direction' );
4328 elemRect
= $element
[ 0 ].getBoundingClientRect();
4329 if ( $container
[ 0 ] === window
) {
4333 right
: document
.documentElement
.clientWidth
,
4334 bottom
: document
.documentElement
.clientHeight
4337 contRect
= $container
[ 0 ].getBoundingClientRect();
4340 topEdgeInBounds
= elemRect
.top
>= contRect
.top
&& elemRect
.top
<= contRect
.bottom
;
4341 bottomEdgeInBounds
= elemRect
.bottom
>= contRect
.top
&& elemRect
.bottom
<= contRect
.bottom
;
4342 leftEdgeInBounds
= elemRect
.left
>= contRect
.left
&& elemRect
.left
<= contRect
.right
;
4343 rightEdgeInBounds
= elemRect
.right
>= contRect
.left
&& elemRect
.right
<= contRect
.right
;
4344 if ( direction
=== 'rtl' ) {
4345 startEdgeInBounds
= rightEdgeInBounds
;
4346 endEdgeInBounds
= leftEdgeInBounds
;
4348 startEdgeInBounds
= leftEdgeInBounds
;
4349 endEdgeInBounds
= rightEdgeInBounds
;
4352 if ( this.verticalPosition
=== 'below' && !bottomEdgeInBounds
) {
4355 if ( this.verticalPosition
=== 'above' && !topEdgeInBounds
) {
4358 if ( this.horizontalPosition
=== 'before' && !startEdgeInBounds
) {
4361 if ( this.horizontalPosition
=== 'after' && !endEdgeInBounds
) {
4365 // The other positioning values are all about being inside the container,
4366 // so in those cases all we care about is that any part of the container is visible.
4367 return elemRect
.top
<= contRect
.bottom
&& elemRect
.bottom
>= contRect
.top
&&
4368 elemRect
.left
<= contRect
.right
&& elemRect
.right
>= contRect
.left
;
4372 * Position the floatable below its container.
4374 * This should only be done when both of them are attached to the DOM and visible.
4378 OO
.ui
.mixin
.FloatableElement
.prototype.position = function () {
4379 if ( !this.positioning
) {
4384 // To continue, some things need to be true:
4385 // The element must actually be in the DOM
4386 this.isElementAttached() && (
4387 // The closest scrollable is the current window
4388 this.$floatableClosestScrollable
[ 0 ] === this.getElementWindow() ||
4389 // OR is an element in the element's DOM
4390 $.contains( this.getElementDocument(), this.$floatableClosestScrollable
[ 0 ] )
4393 // Abort early if important parts of the widget are no longer attached to the DOM
4397 if ( this.hideWhenOutOfView
&& !this.isElementInViewport( this.$floatableContainer
, this.$floatableClosestScrollable
) ) {
4398 this.$floatable
.addClass( 'oo-ui-element-hidden' );
4401 this.$floatable
.removeClass( 'oo-ui-element-hidden' );
4404 if ( !this.needsCustomPosition
) {
4408 this.$floatable
.css( this.computePosition() );
4410 // We updated the position, so re-evaluate the clipping state.
4411 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
4412 // will not notice the need to update itself.)
4413 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
4414 // it not listen to the right events in the right places?
4423 * Compute how #$floatable should be positioned based on the position of #$floatableContainer
4424 * and the positioning settings. This is a helper for #position that shouldn't be called directly,
4425 * but may be overridden by subclasses if they want to change or add to the positioning logic.
4427 * @return {Object} New position to apply with .css(). Keys are 'top', 'left', 'bottom' and 'right'.
4429 OO
.ui
.mixin
.FloatableElement
.prototype.computePosition = function () {
4430 var isBody
, scrollableX
, scrollableY
, containerPos
,
4431 horizScrollbarHeight
, vertScrollbarWidth
, scrollTop
, scrollLeft
,
4432 newPos
= { top
: '', left
: '', bottom
: '', right
: '' },
4433 direction
= this.$floatableContainer
.css( 'direction' ),
4434 $offsetParent
= this.$floatable
.offsetParent();
4436 if ( $offsetParent
.is( 'html' ) ) {
4437 // The innerHeight/Width and clientHeight/Width calculations don't work well on the
4438 // <html> element, but they do work on the <body>
4439 $offsetParent
= $( $offsetParent
[ 0 ].ownerDocument
.body
);
4441 isBody
= $offsetParent
.is( 'body' );
4442 scrollableX
= $offsetParent
.css( 'overflow-x' ) === 'scroll' || $offsetParent
.css( 'overflow-x' ) === 'auto';
4443 scrollableY
= $offsetParent
.css( 'overflow-y' ) === 'scroll' || $offsetParent
.css( 'overflow-y' ) === 'auto';
4445 vertScrollbarWidth
= $offsetParent
.innerWidth() - $offsetParent
.prop( 'clientWidth' );
4446 horizScrollbarHeight
= $offsetParent
.innerHeight() - $offsetParent
.prop( 'clientHeight' );
4447 // We don't need to compute and add scrollTop and scrollLeft if the scrollable container is the body,
4448 // or if it isn't scrollable
4449 scrollTop
= scrollableY
&& !isBody
? $offsetParent
.scrollTop() : 0;
4450 scrollLeft
= scrollableX
&& !isBody
? OO
.ui
.Element
.static.getScrollLeft( $offsetParent
[ 0 ] ) : 0;
4452 // Avoid passing the <body> to getRelativePosition(), because it won't return what we expect
4453 // if the <body> has a margin
4454 containerPos
= isBody
?
4455 this.$floatableContainer
.offset() :
4456 OO
.ui
.Element
.static.getRelativePosition( this.$floatableContainer
, $offsetParent
);
4457 containerPos
.bottom
= containerPos
.top
+ this.$floatableContainer
.outerHeight();
4458 containerPos
.right
= containerPos
.left
+ this.$floatableContainer
.outerWidth();
4459 containerPos
.start
= direction
=== 'rtl' ? containerPos
.right
: containerPos
.left
;
4460 containerPos
.end
= direction
=== 'rtl' ? containerPos
.left
: containerPos
.right
;
4462 if ( this.verticalPosition
=== 'below' ) {
4463 newPos
.top
= containerPos
.bottom
;
4464 } else if ( this.verticalPosition
=== 'above' ) {
4465 newPos
.bottom
= $offsetParent
.outerHeight() - containerPos
.top
;
4466 } else if ( this.verticalPosition
=== 'top' ) {
4467 newPos
.top
= containerPos
.top
;
4468 } else if ( this.verticalPosition
=== 'bottom' ) {
4469 newPos
.bottom
= $offsetParent
.outerHeight() - containerPos
.bottom
;
4470 } else if ( this.verticalPosition
=== 'center' ) {
4471 newPos
.top
= containerPos
.top
+
4472 ( this.$floatableContainer
.height() - this.$floatable
.height() ) / 2;
4475 if ( this.horizontalPosition
=== 'before' ) {
4476 newPos
.end
= containerPos
.start
;
4477 } else if ( this.horizontalPosition
=== 'after' ) {
4478 newPos
.start
= containerPos
.end
;
4479 } else if ( this.horizontalPosition
=== 'start' ) {
4480 newPos
.start
= containerPos
.start
;
4481 } else if ( this.horizontalPosition
=== 'end' ) {
4482 newPos
.end
= containerPos
.end
;
4483 } else if ( this.horizontalPosition
=== 'center' ) {
4484 newPos
.left
= containerPos
.left
+
4485 ( this.$floatableContainer
.width() - this.$floatable
.width() ) / 2;
4488 if ( newPos
.start
!== undefined ) {
4489 if ( direction
=== 'rtl' ) {
4490 newPos
.right
= ( isBody
? $( $offsetParent
[ 0 ].ownerDocument
.documentElement
) : $offsetParent
).outerWidth() - newPos
.start
;
4492 newPos
.left
= newPos
.start
;
4494 delete newPos
.start
;
4496 if ( newPos
.end
!== undefined ) {
4497 if ( direction
=== 'rtl' ) {
4498 newPos
.left
= newPos
.end
;
4500 newPos
.right
= ( isBody
? $( $offsetParent
[ 0 ].ownerDocument
.documentElement
) : $offsetParent
).outerWidth() - newPos
.end
;
4505 // Account for scroll position
4506 if ( newPos
.top
!== '' ) {
4507 newPos
.top
+= scrollTop
;
4509 if ( newPos
.bottom
!== '' ) {
4510 newPos
.bottom
-= scrollTop
;
4512 if ( newPos
.left
!== '' ) {
4513 newPos
.left
+= scrollLeft
;
4515 if ( newPos
.right
!== '' ) {
4516 newPos
.right
-= scrollLeft
;
4519 // Account for scrollbar gutter
4520 if ( newPos
.bottom
!== '' ) {
4521 newPos
.bottom
-= horizScrollbarHeight
;
4523 if ( direction
=== 'rtl' ) {
4524 if ( newPos
.left
!== '' ) {
4525 newPos
.left
-= vertScrollbarWidth
;
4528 if ( newPos
.right
!== '' ) {
4529 newPos
.right
-= vertScrollbarWidth
;
4537 * Element that can be automatically clipped to visible boundaries.
4539 * Whenever the element's natural height changes, you have to call
4540 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
4541 * clipping correctly.
4543 * The dimensions of #$clippableContainer will be compared to the boundaries of the
4544 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
4545 * then #$clippable will be given a fixed reduced height and/or width and will be made
4546 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
4547 * but you can build a static footer by setting #$clippableContainer to an element that contains
4548 * #$clippable and the footer.
4554 * @param {Object} [config] Configuration options
4555 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
4556 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
4557 * omit to use #$clippable
4559 OO
.ui
.mixin
.ClippableElement
= function OoUiMixinClippableElement( config
) {
4560 // Configuration initialization
4561 config
= config
|| {};
4564 this.$clippable
= null;
4565 this.$clippableContainer
= null;
4566 this.clipping
= false;
4567 this.clippedHorizontally
= false;
4568 this.clippedVertically
= false;
4569 this.$clippableScrollableContainer
= null;
4570 this.$clippableScroller
= null;
4571 this.$clippableWindow
= null;
4572 this.idealWidth
= null;
4573 this.idealHeight
= null;
4574 this.onClippableScrollHandler
= this.clip
.bind( this );
4575 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
4578 if ( config
.$clippableContainer
) {
4579 this.setClippableContainer( config
.$clippableContainer
);
4581 this.setClippableElement( config
.$clippable
|| this.$element
);
4587 * Set clippable element.
4589 * If an element is already set, it will be cleaned up before setting up the new element.
4591 * @param {jQuery} $clippable Element to make clippable
4593 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
4594 if ( this.$clippable
) {
4595 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
4596 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
4597 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4600 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
4605 * Set clippable container.
4607 * This is the container that will be measured when deciding whether to clip. When clipping,
4608 * #$clippable will be resized in order to keep the clippable container fully visible.
4610 * If the clippable container is unset, #$clippable will be used.
4612 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
4614 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableContainer = function ( $clippableContainer
) {
4615 this.$clippableContainer
= $clippableContainer
;
4616 if ( this.$clippable
) {
4624 * Do not turn clipping on until after the element is attached to the DOM and visible.
4626 * @param {boolean} [clipping] Enable clipping, omit to toggle
4629 OO
.ui
.mixin
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
4630 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
4632 if ( clipping
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
4633 OO
.ui
.warnDeprecation( 'ClippableElement#toggleClipping: Before calling this method, the element must be attached to the DOM.' );
4634 this.warnedUnattached
= true;
4637 if ( this.clipping
!== clipping
) {
4638 this.clipping
= clipping
;
4640 this.$clippableScrollableContainer
= $( this.getClosestScrollableElementContainer() );
4641 // If the clippable container is the root, we have to listen to scroll events and check
4642 // jQuery.scrollTop on the window because of browser inconsistencies
4643 this.$clippableScroller
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
4644 $( OO
.ui
.Element
.static.getWindow( this.$clippableScrollableContainer
) ) :
4645 this.$clippableScrollableContainer
;
4646 this.$clippableScroller
.on( 'scroll', this.onClippableScrollHandler
);
4647 this.$clippableWindow
= $( this.getElementWindow() )
4648 .on( 'resize', this.onClippableWindowResizeHandler
);
4649 // Initial clip after visible
4652 this.$clippable
.css( {
4660 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4662 this.$clippableScrollableContainer
= null;
4663 this.$clippableScroller
.off( 'scroll', this.onClippableScrollHandler
);
4664 this.$clippableScroller
= null;
4665 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
4666 this.$clippableWindow
= null;
4674 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
4676 * @return {boolean} Element will be clipped to the visible area
4678 OO
.ui
.mixin
.ClippableElement
.prototype.isClipping = function () {
4679 return this.clipping
;
4683 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
4685 * @return {boolean} Part of the element is being clipped
4687 OO
.ui
.mixin
.ClippableElement
.prototype.isClipped = function () {
4688 return this.clippedHorizontally
|| this.clippedVertically
;
4692 * Check if the right of the element is being clipped by the nearest scrollable container.
4694 * @return {boolean} Part of the element is being clipped
4696 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedHorizontally = function () {
4697 return this.clippedHorizontally
;
4701 * Check if the bottom of the element is being clipped by the nearest scrollable container.
4703 * @return {boolean} Part of the element is being clipped
4705 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedVertically = function () {
4706 return this.clippedVertically
;
4710 * Set the ideal size. These are the dimensions #$clippable will have when it's not being clipped.
4712 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
4713 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
4715 OO
.ui
.mixin
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
4716 this.idealWidth
= width
;
4717 this.idealHeight
= height
;
4719 if ( !this.clipping
) {
4720 // Update dimensions
4721 this.$clippable
.css( { width
: width
, height
: height
} );
4723 // While clipping, idealWidth and idealHeight are not considered
4727 * Clip element to visible boundaries and allow scrolling when needed. You should call this method
4728 * when the element's natural height changes.
4730 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
4731 * overlapped by, the visible area of the nearest scrollable container.
4733 * Because calling clip() when the natural height changes isn't always possible, we also set
4734 * max-height when the element isn't being clipped. This means that if the element tries to grow
4735 * beyond the edge, something reasonable will happen before clip() is called.
4739 OO
.ui
.mixin
.ClippableElement
.prototype.clip = function () {
4740 var $container
, extraHeight
, extraWidth
, ccOffset
,
4741 $scrollableContainer
, scOffset
, scHeight
, scWidth
,
4742 ccWidth
, scrollerIsWindow
, scrollTop
, scrollLeft
,
4743 desiredWidth
, desiredHeight
, allotedWidth
, allotedHeight
,
4744 naturalWidth
, naturalHeight
, clipWidth
, clipHeight
,
4745 buffer
= 7; // Chosen by fair dice roll
4747 if ( !this.clipping
) {
4748 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
4752 $container
= this.$clippableContainer
|| this.$clippable
;
4753 extraHeight
= $container
.outerHeight() - this.$clippable
.outerHeight();
4754 extraWidth
= $container
.outerWidth() - this.$clippable
.outerWidth();
4755 ccOffset
= $container
.offset();
4756 if ( this.$clippableScrollableContainer
.is( 'html, body' ) ) {
4757 $scrollableContainer
= this.$clippableWindow
;
4758 scOffset
= { top
: 0, left
: 0 };
4760 $scrollableContainer
= this.$clippableScrollableContainer
;
4761 scOffset
= $scrollableContainer
.offset();
4763 scHeight
= $scrollableContainer
.innerHeight() - buffer
;
4764 scWidth
= $scrollableContainer
.innerWidth() - buffer
;
4765 ccWidth
= $container
.outerWidth() + buffer
;
4766 scrollerIsWindow
= this.$clippableScroller
[ 0 ] === this.$clippableWindow
[ 0 ];
4767 scrollTop
= scrollerIsWindow
? this.$clippableScroller
.scrollTop() : 0;
4768 scrollLeft
= scrollerIsWindow
? this.$clippableScroller
.scrollLeft() : 0;
4769 desiredWidth
= ccOffset
.left
< 0 ?
4770 ccWidth
+ ccOffset
.left
:
4771 ( scOffset
.left
+ scrollLeft
+ scWidth
) - ccOffset
.left
;
4772 desiredHeight
= ( scOffset
.top
+ scrollTop
+ scHeight
) - ccOffset
.top
;
4773 // It should never be desirable to exceed the dimensions of the browser viewport... right?
4774 desiredWidth
= Math
.min( desiredWidth
, document
.documentElement
.clientWidth
);
4775 desiredHeight
= Math
.min( desiredHeight
, document
.documentElement
.clientHeight
);
4776 allotedWidth
= Math
.ceil( desiredWidth
- extraWidth
);
4777 allotedHeight
= Math
.ceil( desiredHeight
- extraHeight
);
4778 naturalWidth
= this.$clippable
.prop( 'scrollWidth' );
4779 naturalHeight
= this.$clippable
.prop( 'scrollHeight' );
4780 clipWidth
= allotedWidth
< naturalWidth
;
4781 clipHeight
= allotedHeight
< naturalHeight
;
4784 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. (T157672)
4785 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
4786 this.$clippable
.css( 'overflowX', 'scroll' );
4787 void this.$clippable
[ 0 ].offsetHeight
; // Force reflow
4788 this.$clippable
.css( {
4789 width
: Math
.max( 0, allotedWidth
),
4793 this.$clippable
.css( {
4795 width
: this.idealWidth
|| '',
4796 maxWidth
: Math
.max( 0, allotedWidth
)
4800 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. (T157672)
4801 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
4802 this.$clippable
.css( 'overflowY', 'scroll' );
4803 void this.$clippable
[ 0 ].offsetHeight
; // Force reflow
4804 this.$clippable
.css( {
4805 height
: Math
.max( 0, allotedHeight
),
4809 this.$clippable
.css( {
4811 height
: this.idealHeight
|| '',
4812 maxHeight
: Math
.max( 0, allotedHeight
)
4816 // If we stopped clipping in at least one of the dimensions
4817 if ( ( this.clippedHorizontally
&& !clipWidth
) || ( this.clippedVertically
&& !clipHeight
) ) {
4818 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4821 this.clippedHorizontally
= clipWidth
;
4822 this.clippedVertically
= clipHeight
;
4828 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
4829 * By default, each popup has an anchor that points toward its origin.
4830 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
4832 * Unlike most widgets, PopupWidget is initially hidden and must be shown by calling #toggle.
4835 * // A popup widget.
4836 * var popup = new OO.ui.PopupWidget( {
4837 * $content: $( '<p>Hi there!</p>' ),
4842 * $( 'body' ).append( popup.$element );
4843 * // To display the popup, toggle the visibility to 'true'.
4844 * popup.toggle( true );
4846 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
4849 * @extends OO.ui.Widget
4850 * @mixins OO.ui.mixin.LabelElement
4851 * @mixins OO.ui.mixin.ClippableElement
4852 * @mixins OO.ui.mixin.FloatableElement
4855 * @param {Object} [config] Configuration options
4856 * @cfg {number} [width=320] Width of popup in pixels
4857 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
4858 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
4859 * @cfg {string} [position='below'] Where to position the popup relative to $floatableContainer
4860 * 'above': Put popup above $floatableContainer; anchor points down to the horizontal center
4861 * of $floatableContainer
4862 * 'below': Put popup below $floatableContainer; anchor points up to the horizontal center
4863 * of $floatableContainer
4864 * 'before': Put popup to the left (LTR) / right (RTL) of $floatableContainer; anchor points
4865 * endwards (right/left) to the vertical center of $floatableContainer
4866 * 'after': Put popup to the right (LTR) / left (RTL) of $floatableContainer; anchor points
4867 * startwards (left/right) to the vertical center of $floatableContainer
4868 * @cfg {string} [align='center'] How to align the popup to $floatableContainer
4869 * 'forwards': If position is above/below, move the popup as far endwards (right in LTR, left in RTL)
4870 * as possible while still keeping the anchor within the popup;
4871 * if position is before/after, move the popup as far downwards as possible.
4872 * 'backwards': If position is above/below, move the popup as far startwards (left in LTR, right in RTL)
4873 * as possible while still keeping the anchor within the popup;
4874 * if position in before/after, move the popup as far upwards as possible.
4875 * 'center': Horizontally (if position is above/below) or vertically (before/after) align the center
4876 * of the popup with the center of $floatableContainer.
4877 * 'force-left': Alias for 'forwards' in LTR and 'backwards' in RTL
4878 * 'force-right': Alias for 'backwards' in RTL and 'forwards' in LTR
4879 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
4880 * See the [OOjs UI docs on MediaWiki][3] for an example.
4881 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
4882 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
4883 * @cfg {jQuery} [$content] Content to append to the popup's body
4884 * @cfg {jQuery} [$footer] Content to append to the popup's footer
4885 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
4886 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
4887 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
4889 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
4890 * @cfg {boolean} [head=false] Show a popup header that contains a #label (if specified) and close
4892 * @cfg {boolean} [padded=false] Add padding to the popup's body
4894 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
4895 // Configuration initialization
4896 config
= config
|| {};
4898 // Parent constructor
4899 OO
.ui
.PopupWidget
.parent
.call( this, config
);
4901 // Properties (must be set before ClippableElement constructor call)
4902 this.$body
= $( '<div>' );
4903 this.$popup
= $( '<div>' );
4905 // Mixin constructors
4906 OO
.ui
.mixin
.LabelElement
.call( this, config
);
4907 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, {
4908 $clippable
: this.$body
,
4909 $clippableContainer
: this.$popup
4911 OO
.ui
.mixin
.FloatableElement
.call( this, config
);
4914 this.$anchor
= $( '<div>' );
4915 // If undefined, will be computed lazily in updateDimensions()
4916 this.$container
= config
.$container
;
4917 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
4918 this.autoClose
= !!config
.autoClose
;
4919 this.$autoCloseIgnore
= config
.$autoCloseIgnore
;
4920 this.transitionTimeout
= null;
4921 this.anchored
= false;
4922 this.width
= config
.width
!== undefined ? config
.width
: 320;
4923 this.height
= config
.height
!== undefined ? config
.height
: null;
4924 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
4925 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
4928 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
4929 this.setAlignment( config
.align
|| 'center' );
4930 this.setPosition( config
.position
|| 'below' );
4931 this.$body
.addClass( 'oo-ui-popupWidget-body' );
4932 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
4934 .addClass( 'oo-ui-popupWidget-popup' )
4935 .append( this.$body
);
4937 .addClass( 'oo-ui-popupWidget' )
4938 .append( this.$popup
, this.$anchor
);
4939 // Move content, which was added to #$element by OO.ui.Widget, to the body
4940 // FIXME This is gross, we should use '$body' or something for the config
4941 if ( config
.$content
instanceof jQuery
) {
4942 this.$body
.append( config
.$content
);
4945 if ( config
.padded
) {
4946 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
4949 if ( config
.head
) {
4950 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
4951 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
4952 this.$head
= $( '<div>' )
4953 .addClass( 'oo-ui-popupWidget-head' )
4954 .append( this.$label
, this.closeButton
.$element
);
4955 this.$popup
.prepend( this.$head
);
4958 if ( config
.$footer
) {
4959 this.$footer
= $( '<div>' )
4960 .addClass( 'oo-ui-popupWidget-footer' )
4961 .append( config
.$footer
);
4962 this.$popup
.append( this.$footer
);
4965 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
4966 // that reference properties not initialized at that time of parent class construction
4967 // TODO: Find a better way to handle post-constructor setup
4968 this.visible
= false;
4969 this.$element
.addClass( 'oo-ui-element-hidden' );
4974 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
4975 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.LabelElement
);
4976 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.ClippableElement
);
4977 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.FloatableElement
);
4984 * The popup is ready: it is visible and has been positioned and clipped.
4990 * Handles mouse down events.
4993 * @param {MouseEvent} e Mouse down event
4995 OO
.ui
.PopupWidget
.prototype.onMouseDown = function ( e
) {
4998 !OO
.ui
.contains( this.$element
.add( this.$autoCloseIgnore
).get(), e
.target
, true )
5000 this.toggle( false );
5005 * Bind mouse down listener.
5009 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
5010 // Capture clicks outside popup
5011 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler
, true );
5015 * Handles close button click events.
5019 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
5020 if ( this.isVisible() ) {
5021 this.toggle( false );
5026 * Unbind mouse down listener.
5030 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
5031 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler
, true );
5035 * Handles key down events.
5038 * @param {KeyboardEvent} e Key down event
5040 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
5042 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
5045 this.toggle( false );
5047 e
.stopPropagation();
5052 * Bind key down listener.
5056 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
5057 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
5061 * Unbind key down listener.
5065 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
5066 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
5070 * Show, hide, or toggle the visibility of the anchor.
5072 * @param {boolean} [show] Show anchor, omit to toggle
5074 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
5075 show
= show
=== undefined ? !this.anchored
: !!show
;
5077 if ( this.anchored
!== show
) {
5079 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
5080 this.$element
.addClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
5082 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
5083 this.$element
.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
5085 this.anchored
= show
;
5089 * Change which edge the anchor appears on.
5091 * @param {string} edge 'top', 'bottom', 'start' or 'end'
5093 OO
.ui
.PopupWidget
.prototype.setAnchorEdge = function ( edge
) {
5094 if ( [ 'top', 'bottom', 'start', 'end' ].indexOf( edge
) === -1 ) {
5095 throw new Error( 'Invalid value for edge: ' + edge
);
5097 if ( this.anchorEdge
!== null ) {
5098 this.$element
.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
5100 this.anchorEdge
= edge
;
5101 if ( this.anchored
) {
5102 this.$element
.addClass( 'oo-ui-popupWidget-anchored-' + edge
);
5107 * Check if the anchor is visible.
5109 * @return {boolean} Anchor is visible
5111 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
5112 return this.anchored
;
5116 * Toggle visibility of the popup. The popup is initially hidden and must be shown by calling
5117 * `.toggle( true )` after its #$element is attached to the DOM.
5119 * Do not show the popup while it is not attached to the DOM. The calculations required to display
5120 * it in the right place and with the right dimensions only work correctly while it is attached.
5121 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
5122 * strictly enforced, so currently it only generates a warning in the browser console.
5127 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
5129 show
= show
=== undefined ? !this.isVisible() : !!show
;
5131 change
= show
!== this.isVisible();
5133 if ( show
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
5134 OO
.ui
.warnDeprecation( 'PopupWidget#toggle: Before calling this method, the popup must be attached to the DOM.' );
5135 this.warnedUnattached
= true;
5137 if ( show
&& !this.$floatableContainer
&& this.isElementAttached() ) {
5138 // Fall back to the parent node if the floatableContainer is not set
5139 this.setFloatableContainer( this.$element
.parent() );
5143 OO
.ui
.PopupWidget
.parent
.prototype.toggle
.call( this, show
);
5146 this.togglePositioning( show
&& !!this.$floatableContainer
);
5149 if ( this.autoClose
) {
5150 this.bindMouseDownListener();
5151 this.bindKeyDownListener();
5153 this.updateDimensions();
5154 this.toggleClipping( true );
5155 this.emit( 'ready' );
5157 this.toggleClipping( false );
5158 if ( this.autoClose
) {
5159 this.unbindMouseDownListener();
5160 this.unbindKeyDownListener();
5169 * Set the size of the popup.
5171 * Changing the size may also change the popup's position depending on the alignment.
5173 * @param {number} width Width in pixels
5174 * @param {number} height Height in pixels
5175 * @param {boolean} [transition=false] Use a smooth transition
5178 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
5180 this.height
= height
!== undefined ? height
: null;
5181 if ( this.isVisible() ) {
5182 this.updateDimensions( transition
);
5187 * Update the size and position.
5189 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
5190 * be called automatically.
5192 * @param {boolean} [transition=false] Use a smooth transition
5195 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
5198 // Prevent transition from being interrupted
5199 clearTimeout( this.transitionTimeout
);
5201 // Enable transition
5202 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
5208 // Prevent transitioning after transition is complete
5209 this.transitionTimeout
= setTimeout( function () {
5210 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
5213 // Prevent transitioning immediately
5214 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
5221 OO
.ui
.PopupWidget
.prototype.computePosition = function () {
5222 var direction
, align
, vertical
, start
, end
, near
, far
, sizeProp
, popupSize
, anchorSize
, anchorPos
,
5223 anchorOffset
, anchorMargin
, parentPosition
, positionProp
, positionAdjustment
, floatablePos
,
5224 offsetParentPos
, containerPos
,
5226 anchorCss
= { left
: '', right
: '', top
: '', bottom
: '' },
5229 'force-left': 'backwards',
5230 'force-right': 'forwards'
5233 'force-left': 'forwards',
5234 'force-right': 'backwards'
5246 backwards
: this.anchored
? 'before' : 'end'
5254 if ( !this.$container
) {
5255 // Lazy-initialize $container if not specified in constructor
5256 this.$container
= $( this.getClosestScrollableElementContainer() );
5258 direction
= this.$container
.css( 'direction' );
5260 // Set height and width before we do anything else, since it might cause our measurements
5261 // to change (e.g. due to scrollbars appearing or disappearing), and it also affects centering
5264 height
: this.height
!== null ? this.height
: 'auto'
5267 align
= alignMap
[ direction
][ this.align
] || this.align
;
5268 // If the popup is positioned before or after, then the anchor positioning is vertical, otherwise horizontal
5269 vertical
= this.popupPosition
=== 'before' || this.popupPosition
=== 'after';
5270 start
= vertical
? 'top' : ( direction
=== 'rtl' ? 'right' : 'left' );
5271 end
= vertical
? 'bottom' : ( direction
=== 'rtl' ? 'left' : 'right' );
5272 near
= vertical
? 'top' : 'left';
5273 far
= vertical
? 'bottom' : 'right';
5274 sizeProp
= vertical
? 'Height' : 'Width';
5275 popupSize
= vertical
? ( this.height
|| this.$popup
.height() ) : this.width
;
5277 this.setAnchorEdge( anchorEdgeMap
[ this.popupPosition
] );
5278 this.horizontalPosition
= vertical
? this.popupPosition
: hPosMap
[ align
];
5279 this.verticalPosition
= vertical
? vPosMap
[ align
] : this.popupPosition
;
5282 parentPosition
= OO
.ui
.mixin
.FloatableElement
.prototype.computePosition
.call( this );
5283 // Find out which property FloatableElement used for positioning, and adjust that value
5284 positionProp
= vertical
?
5285 ( parentPosition
.top
!== '' ? 'top' : 'bottom' ) :
5286 ( parentPosition
.left
!== '' ? 'left' : 'right' );
5288 // Figure out where the near and far edges of the popup and $floatableContainer are
5289 floatablePos
= this.$floatableContainer
.offset();
5290 floatablePos
[ far
] = floatablePos
[ near
] + this.$floatableContainer
[ 'outer' + sizeProp
]();
5291 // Measure where the offsetParent is and compute our position based on that and parentPosition
5292 offsetParentPos
= this.$element
.offsetParent().offset();
5294 if ( positionProp
=== near
) {
5295 popupPos
[ near
] = offsetParentPos
[ near
] + parentPosition
[ near
];
5296 popupPos
[ far
] = popupPos
[ near
] + popupSize
;
5298 popupPos
[ far
] = offsetParentPos
[ near
] +
5299 this.$element
.offsetParent()[ 'inner' + sizeProp
]() - parentPosition
[ far
];
5300 popupPos
[ near
] = popupPos
[ far
] - popupSize
;
5303 if ( this.anchored
) {
5304 // Position the anchor (which is positioned relative to the popup) to point to $floatableContainer
5305 anchorPos
= ( floatablePos
[ start
] + floatablePos
[ end
] ) / 2;
5306 anchorOffset
= ( start
=== far
? -1 : 1 ) * ( anchorPos
- popupPos
[ start
] );
5308 // If the anchor is less than 2*anchorSize from either edge, move the popup to make more space
5309 // this.$anchor.width()/height() returns 0 because of the CSS trickery we use, so use scrollWidth/Height
5310 anchorSize
= this.$anchor
[ 0 ][ 'scroll' + sizeProp
];
5311 anchorMargin
= parseFloat( this.$anchor
.css( 'margin-' + start
) );
5312 if ( anchorOffset
+ anchorMargin
< 2 * anchorSize
) {
5313 // Not enough space for the anchor on the start side; pull the popup startwards
5314 positionAdjustment
= ( positionProp
=== start
? -1 : 1 ) *
5315 ( 2 * anchorSize
- ( anchorOffset
+ anchorMargin
) );
5316 } else if ( anchorOffset
+ anchorMargin
> popupSize
- 2 * anchorSize
) {
5317 // Not enough space for the anchor on the end side; pull the popup endwards
5318 positionAdjustment
= ( positionProp
=== end
? -1 : 1 ) *
5319 ( anchorOffset
+ anchorMargin
- ( popupSize
- 2 * anchorSize
) );
5321 positionAdjustment
= 0;
5324 positionAdjustment
= 0;
5327 // Check if the popup will go beyond the edge of this.$container
5328 containerPos
= this.$container
.offset();
5329 containerPos
[ far
] = containerPos
[ near
] + this.$container
[ 'inner' + sizeProp
]();
5330 // Take into account how much the popup will move because of the adjustments we're going to make
5331 popupPos
[ near
] += ( positionProp
=== near
? 1 : -1 ) * positionAdjustment
;
5332 popupPos
[ far
] += ( positionProp
=== near
? 1 : -1 ) * positionAdjustment
;
5333 if ( containerPos
[ near
] + this.containerPadding
> popupPos
[ near
] ) {
5334 // Popup goes beyond the near (left/top) edge, move it to the right/bottom
5335 positionAdjustment
+= ( positionProp
=== near
? 1 : -1 ) *
5336 ( containerPos
[ near
] + this.containerPadding
- popupPos
[ near
] );
5337 } else if ( containerPos
[ far
] - this.containerPadding
< popupPos
[ far
] ) {
5338 // Popup goes beyond the far (right/bottom) edge, move it to the left/top
5339 positionAdjustment
+= ( positionProp
=== far
? 1 : -1 ) *
5340 ( popupPos
[ far
] - ( containerPos
[ far
] - this.containerPadding
) );
5343 if ( this.anchored
) {
5344 // Adjust anchorOffset for positionAdjustment
5345 anchorOffset
+= ( positionProp
=== start
? -1 : 1 ) * positionAdjustment
;
5347 // Position the anchor
5348 anchorCss
[ start
] = anchorOffset
;
5349 this.$anchor
.css( anchorCss
);
5352 // Move the popup if needed
5353 parentPosition
[ positionProp
] += positionAdjustment
;
5355 return parentPosition
;
5359 * Set popup alignment
5361 * @param {string} [align=center] Alignment of the popup, `center`, `force-left`, `force-right`,
5362 * `backwards` or `forwards`.
5364 OO
.ui
.PopupWidget
.prototype.setAlignment = function ( align
) {
5365 // Validate alignment
5366 if ( [ 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align
) > -1 ) {
5369 this.align
= 'center';
5375 * Get popup alignment
5377 * @return {string} Alignment of the popup, `center`, `force-left`, `force-right`,
5378 * `backwards` or `forwards`.
5380 OO
.ui
.PopupWidget
.prototype.getAlignment = function () {
5385 * Change the positioning of the popup.
5387 * @param {string} position 'above', 'below', 'before' or 'after'
5389 OO
.ui
.PopupWidget
.prototype.setPosition = function ( position
) {
5390 if ( [ 'above', 'below', 'before', 'after' ].indexOf( position
) === -1 ) {
5393 this.popupPosition
= position
;
5398 * Get popup positioning.
5400 * @return {string} 'above', 'below', 'before' or 'after'
5402 OO
.ui
.PopupWidget
.prototype.getPosition = function () {
5403 return this.popupPosition
;
5407 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5408 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5409 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5410 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5416 * @param {Object} [config] Configuration options
5417 * @cfg {Object} [popup] Configuration to pass to popup
5418 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5420 OO
.ui
.mixin
.PopupElement
= function OoUiMixinPopupElement( config
) {
5421 // Configuration initialization
5422 config
= config
|| {};
5425 this.popup
= new OO
.ui
.PopupWidget( $.extend(
5428 $floatableContainer
: this.$element
5432 $autoCloseIgnore
: this.$element
.add( config
.popup
&& config
.popup
.$autoCloseIgnore
)
5442 * @return {OO.ui.PopupWidget} Popup widget
5444 OO
.ui
.mixin
.PopupElement
.prototype.getPopup = function () {
5449 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
5450 * which is used to display additional information or options.
5453 * // Example of a popup button.
5454 * var popupButton = new OO.ui.PopupButtonWidget( {
5455 * label: 'Popup button with options',
5458 * $content: $( '<p>Additional options here.</p>' ),
5460 * align: 'force-left'
5463 * // Append the button to the DOM.
5464 * $( 'body' ).append( popupButton.$element );
5467 * @extends OO.ui.ButtonWidget
5468 * @mixins OO.ui.mixin.PopupElement
5471 * @param {Object} [config] Configuration options
5472 * @cfg {jQuery} [$overlay] Render the popup into a separate layer. This configuration is useful in cases where
5473 * the expanded popup is larger than its containing `<div>`. The specified overlay layer is usually on top of the
5474 * containing `<div>` and has a larger area. By default, the popup uses relative positioning.
5475 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
5477 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
5478 // Configuration initialization
5479 config
= config
|| {};
5481 // Parent constructor
5482 OO
.ui
.PopupButtonWidget
.parent
.call( this, config
);
5484 // Mixin constructors
5485 OO
.ui
.mixin
.PopupElement
.call( this, config
);
5488 this.$overlay
= config
.$overlay
|| this.$element
;
5491 this.connect( this, { click
: 'onAction' } );
5495 .addClass( 'oo-ui-popupButtonWidget' )
5496 .attr( 'aria-haspopup', 'true' );
5498 .addClass( 'oo-ui-popupButtonWidget-popup' )
5499 .toggleClass( 'oo-ui-popupButtonWidget-framed-popup', this.isFramed() )
5500 .toggleClass( 'oo-ui-popupButtonWidget-frameless-popup', !this.isFramed() );
5501 this.$overlay
.append( this.popup
.$element
);
5506 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
5507 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.mixin
.PopupElement
);
5512 * Handle the button action being triggered.
5516 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
5517 this.popup
.toggle();
5521 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
5523 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
5528 * @mixins OO.ui.mixin.GroupElement
5531 * @param {Object} [config] Configuration options
5533 OO
.ui
.mixin
.GroupWidget
= function OoUiMixinGroupWidget( config
) {
5534 // Mixin constructors
5535 OO
.ui
.mixin
.GroupElement
.call( this, config
);
5540 OO
.mixinClass( OO
.ui
.mixin
.GroupWidget
, OO
.ui
.mixin
.GroupElement
);
5545 * Set the disabled state of the widget.
5547 * This will also update the disabled state of child widgets.
5549 * @param {boolean} disabled Disable widget
5552 OO
.ui
.mixin
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
5556 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
5557 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
5559 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
5561 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5562 this.items
[ i
].updateDisabled();
5570 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
5572 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
5573 * allows bidirectional communication.
5575 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
5583 OO
.ui
.mixin
.ItemWidget
= function OoUiMixinItemWidget() {
5590 * Check if widget is disabled.
5592 * Checks parent if present, making disabled state inheritable.
5594 * @return {boolean} Widget is disabled
5596 OO
.ui
.mixin
.ItemWidget
.prototype.isDisabled = function () {
5597 return this.disabled
||
5598 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
5602 * Set group element is in.
5604 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
5607 OO
.ui
.mixin
.ItemWidget
.prototype.setElementGroup = function ( group
) {
5609 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
5610 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
5612 // Initialize item disabled states
5613 this.updateDisabled();
5619 * OptionWidgets are special elements that can be selected and configured with data. The
5620 * data is often unique for each option, but it does not have to be. OptionWidgets are used
5621 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
5622 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
5624 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5627 * @extends OO.ui.Widget
5628 * @mixins OO.ui.mixin.ItemWidget
5629 * @mixins OO.ui.mixin.LabelElement
5630 * @mixins OO.ui.mixin.FlaggedElement
5631 * @mixins OO.ui.mixin.AccessKeyedElement
5634 * @param {Object} [config] Configuration options
5636 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
5637 // Configuration initialization
5638 config
= config
|| {};
5640 // Parent constructor
5641 OO
.ui
.OptionWidget
.parent
.call( this, config
);
5643 // Mixin constructors
5644 OO
.ui
.mixin
.ItemWidget
.call( this );
5645 OO
.ui
.mixin
.LabelElement
.call( this, config
);
5646 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
5647 OO
.ui
.mixin
.AccessKeyedElement
.call( this, config
);
5650 this.selected
= false;
5651 this.highlighted
= false;
5652 this.pressed
= false;
5656 .data( 'oo-ui-optionWidget', this )
5657 // Allow programmatic focussing (and by accesskey), but not tabbing
5658 .attr( 'tabindex', '-1' )
5659 .attr( 'role', 'option' )
5660 .attr( 'aria-selected', 'false' )
5661 .addClass( 'oo-ui-optionWidget' )
5662 .append( this.$label
);
5667 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
5668 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.ItemWidget
);
5669 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.LabelElement
);
5670 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.FlaggedElement
);
5671 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
5673 /* Static Properties */
5676 * Whether this option can be selected. See #setSelected.
5680 * @property {boolean}
5682 OO
.ui
.OptionWidget
.static.selectable
= true;
5685 * Whether this option can be highlighted. See #setHighlighted.
5689 * @property {boolean}
5691 OO
.ui
.OptionWidget
.static.highlightable
= true;
5694 * Whether this option can be pressed. See #setPressed.
5698 * @property {boolean}
5700 OO
.ui
.OptionWidget
.static.pressable
= true;
5703 * Whether this option will be scrolled into view when it is selected.
5707 * @property {boolean}
5709 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
5714 * Check if the option can be selected.
5716 * @return {boolean} Item is selectable
5718 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
5719 return this.constructor.static.selectable
&& !this.isDisabled() && this.isVisible();
5723 * Check if the option can be highlighted. A highlight indicates that the option
5724 * may be selected when a user presses enter or clicks. Disabled items cannot
5727 * @return {boolean} Item is highlightable
5729 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
5730 return this.constructor.static.highlightable
&& !this.isDisabled() && this.isVisible();
5734 * Check if the option can be pressed. The pressed state occurs when a user mouses
5735 * down on an item, but has not yet let go of the mouse.
5737 * @return {boolean} Item is pressable
5739 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
5740 return this.constructor.static.pressable
&& !this.isDisabled() && this.isVisible();
5744 * Check if the option is selected.
5746 * @return {boolean} Item is selected
5748 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
5749 return this.selected
;
5753 * Check if the option is highlighted. A highlight indicates that the
5754 * item may be selected when a user presses enter or clicks.
5756 * @return {boolean} Item is highlighted
5758 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
5759 return this.highlighted
;
5763 * Check if the option is pressed. The pressed state occurs when a user mouses
5764 * down on an item, but has not yet let go of the mouse. The item may appear
5765 * selected, but it will not be selected until the user releases the mouse.
5767 * @return {boolean} Item is pressed
5769 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
5770 return this.pressed
;
5774 * Set the option’s selected state. In general, all modifications to the selection
5775 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
5776 * method instead of this method.
5778 * @param {boolean} [state=false] Select option
5781 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
5782 if ( this.constructor.static.selectable
) {
5783 this.selected
= !!state
;
5785 .toggleClass( 'oo-ui-optionWidget-selected', state
)
5786 .attr( 'aria-selected', state
.toString() );
5787 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
5788 this.scrollElementIntoView();
5790 this.updateThemeClasses();
5796 * Set the option’s highlighted state. In general, all programmatic
5797 * modifications to the highlight should be handled by the
5798 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
5799 * method instead of this method.
5801 * @param {boolean} [state=false] Highlight option
5804 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
5805 if ( this.constructor.static.highlightable
) {
5806 this.highlighted
= !!state
;
5807 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
5808 this.updateThemeClasses();
5814 * Set the option’s pressed state. In general, all
5815 * programmatic modifications to the pressed state should be handled by the
5816 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
5817 * method instead of this method.
5819 * @param {boolean} [state=false] Press option
5822 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
5823 if ( this.constructor.static.pressable
) {
5824 this.pressed
= !!state
;
5825 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
5826 this.updateThemeClasses();
5832 * Get text to match search strings against.
5834 * The default implementation returns the label text, but subclasses
5835 * can override this to provide more complex behavior.
5837 * @return {string|boolean} String to match search string against
5839 OO
.ui
.OptionWidget
.prototype.getMatchText = function () {
5840 var label
= this.getLabel();
5841 return typeof label
=== 'string' ? label
: this.$label
.text();
5845 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
5846 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
5847 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
5850 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
5851 * information, please see the [OOjs UI documentation on MediaWiki][1].
5854 * // Example of a select widget with three options
5855 * var select = new OO.ui.SelectWidget( {
5857 * new OO.ui.OptionWidget( {
5859 * label: 'Option One',
5861 * new OO.ui.OptionWidget( {
5863 * label: 'Option Two',
5865 * new OO.ui.OptionWidget( {
5867 * label: 'Option Three',
5871 * $( 'body' ).append( select.$element );
5873 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5877 * @extends OO.ui.Widget
5878 * @mixins OO.ui.mixin.GroupWidget
5881 * @param {Object} [config] Configuration options
5882 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
5883 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
5884 * the [OOjs UI documentation on MediaWiki] [2] for examples.
5885 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5887 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
5888 // Configuration initialization
5889 config
= config
|| {};
5891 // Parent constructor
5892 OO
.ui
.SelectWidget
.parent
.call( this, config
);
5894 // Mixin constructors
5895 OO
.ui
.mixin
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
5898 this.pressed
= false;
5899 this.selecting
= null;
5900 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
5901 this.onMouseMoveHandler
= this.onMouseMove
.bind( this );
5902 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
5903 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
5904 this.keyPressBuffer
= '';
5905 this.keyPressBufferTimer
= null;
5906 this.blockMouseOverEvents
= 0;
5909 this.connect( this, {
5913 focusin
: this.onFocus
.bind( this ),
5914 mousedown
: this.onMouseDown
.bind( this ),
5915 mouseover
: this.onMouseOver
.bind( this ),
5916 mouseleave
: this.onMouseLeave
.bind( this )
5921 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
5922 .attr( 'role', 'listbox' );
5923 this.setFocusOwner( this.$element
);
5924 if ( Array
.isArray( config
.items
) ) {
5925 this.addItems( config
.items
);
5931 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
5932 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupWidget
);
5939 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
5941 * @param {OO.ui.OptionWidget|null} item Highlighted item
5947 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
5948 * pressed state of an option.
5950 * @param {OO.ui.OptionWidget|null} item Pressed item
5956 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
5958 * @param {OO.ui.OptionWidget|null} item Selected item
5963 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
5964 * @param {OO.ui.OptionWidget} item Chosen item
5970 * An `add` event is emitted when options are added to the select with the #addItems method.
5972 * @param {OO.ui.OptionWidget[]} items Added items
5973 * @param {number} index Index of insertion point
5979 * A `remove` event is emitted when options are removed from the select with the #clearItems
5980 * or #removeItems methods.
5982 * @param {OO.ui.OptionWidget[]} items Removed items
5988 * Handle focus events
5991 * @param {jQuery.Event} event
5993 OO
.ui
.SelectWidget
.prototype.onFocus = function ( event
) {
5995 if ( event
.target
=== this.$element
[ 0 ] ) {
5996 // This widget was focussed, e.g. by the user tabbing to it.
5997 // The styles for focus state depend on one of the items being selected.
5998 if ( !this.getSelectedItem() ) {
5999 item
= this.getFirstSelectableItem();
6002 // One of the options got focussed (and the event bubbled up here).
6003 // They can't be tabbed to, but they can be activated using accesskeys.
6004 item
= this.getTargetItem( event
);
6008 if ( item
.constructor.static.highlightable
) {
6009 this.highlightItem( item
);
6011 this.selectItem( item
);
6015 if ( event
.target
!== this.$element
[ 0 ] ) {
6016 this.$focusOwner
.focus();
6021 * Handle mouse down events.
6024 * @param {jQuery.Event} e Mouse down event
6026 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
6029 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
6030 this.togglePressed( true );
6031 item
= this.getTargetItem( e
);
6032 if ( item
&& item
.isSelectable() ) {
6033 this.pressItem( item
);
6034 this.selecting
= item
;
6035 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
6036 this.getElementDocument().addEventListener( 'mousemove', this.onMouseMoveHandler
, true );
6043 * Handle mouse up events.
6046 * @param {MouseEvent} e Mouse up event
6048 OO
.ui
.SelectWidget
.prototype.onMouseUp = function ( e
) {
6051 this.togglePressed( false );
6052 if ( !this.selecting
) {
6053 item
= this.getTargetItem( e
);
6054 if ( item
&& item
.isSelectable() ) {
6055 this.selecting
= item
;
6058 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
&& this.selecting
) {
6059 this.pressItem( null );
6060 this.chooseItem( this.selecting
);
6061 this.selecting
= null;
6064 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
6065 this.getElementDocument().removeEventListener( 'mousemove', this.onMouseMoveHandler
, true );
6071 * Handle mouse move events.
6074 * @param {MouseEvent} e Mouse move event
6076 OO
.ui
.SelectWidget
.prototype.onMouseMove = function ( e
) {
6079 if ( !this.isDisabled() && this.pressed
) {
6080 item
= this.getTargetItem( e
);
6081 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
6082 this.pressItem( item
);
6083 this.selecting
= item
;
6089 * Handle mouse over events.
6092 * @param {jQuery.Event} e Mouse over event
6094 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
6096 if ( this.blockMouseOverEvents
) {
6099 if ( !this.isDisabled() ) {
6100 item
= this.getTargetItem( e
);
6101 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
6107 * Handle mouse leave events.
6110 * @param {jQuery.Event} e Mouse over event
6112 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
6113 if ( !this.isDisabled() ) {
6114 this.highlightItem( null );
6120 * Handle key down events.
6123 * @param {KeyboardEvent} e Key down event
6125 OO
.ui
.SelectWidget
.prototype.onKeyDown = function ( e
) {
6128 currentItem
= this.getHighlightedItem() || this.getSelectedItem();
6130 if ( !this.isDisabled() && this.isVisible() ) {
6131 switch ( e
.keyCode
) {
6132 case OO
.ui
.Keys
.ENTER
:
6133 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
6134 // Was only highlighted, now let's select it. No-op if already selected.
6135 this.chooseItem( currentItem
);
6140 case OO
.ui
.Keys
.LEFT
:
6141 this.clearKeyPressBuffer();
6142 nextItem
= this.getRelativeSelectableItem( currentItem
, -1 );
6145 case OO
.ui
.Keys
.DOWN
:
6146 case OO
.ui
.Keys
.RIGHT
:
6147 this.clearKeyPressBuffer();
6148 nextItem
= this.getRelativeSelectableItem( currentItem
, 1 );
6151 case OO
.ui
.Keys
.ESCAPE
:
6152 case OO
.ui
.Keys
.TAB
:
6153 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
6154 currentItem
.setHighlighted( false );
6156 this.unbindKeyDownListener();
6157 this.unbindKeyPressListener();
6158 // Don't prevent tabbing away / defocusing
6164 if ( nextItem
.constructor.static.highlightable
) {
6165 this.highlightItem( nextItem
);
6167 this.chooseItem( nextItem
);
6169 this.scrollItemIntoView( nextItem
);
6174 e
.stopPropagation();
6180 * Bind key down listener.
6184 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
6185 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler
, true );
6189 * Unbind key down listener.
6193 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
6194 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler
, true );
6198 * Scroll item into view, preventing spurious mouse highlight actions from happening.
6200 * @param {OO.ui.OptionWidget} item Item to scroll into view
6202 OO
.ui
.SelectWidget
.prototype.scrollItemIntoView = function ( item
) {
6204 // Chromium's Blink engine will generate spurious 'mouseover' events during programmatic scrolling
6205 // and around 100-150 ms after it is finished.
6206 this.blockMouseOverEvents
++;
6207 item
.scrollElementIntoView().done( function () {
6208 setTimeout( function () {
6209 widget
.blockMouseOverEvents
--;
6215 * Clear the key-press buffer
6219 OO
.ui
.SelectWidget
.prototype.clearKeyPressBuffer = function () {
6220 if ( this.keyPressBufferTimer
) {
6221 clearTimeout( this.keyPressBufferTimer
);
6222 this.keyPressBufferTimer
= null;
6224 this.keyPressBuffer
= '';
6228 * Handle key press events.
6231 * @param {KeyboardEvent} e Key press event
6233 OO
.ui
.SelectWidget
.prototype.onKeyPress = function ( e
) {
6234 var c
, filter
, item
;
6236 if ( !e
.charCode
) {
6237 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.keyPressBuffer
!== '' ) {
6238 this.keyPressBuffer
= this.keyPressBuffer
.substr( 0, this.keyPressBuffer
.length
- 1 );
6243 if ( String
.fromCodePoint
) {
6244 c
= String
.fromCodePoint( e
.charCode
);
6246 c
= String
.fromCharCode( e
.charCode
);
6249 if ( this.keyPressBufferTimer
) {
6250 clearTimeout( this.keyPressBufferTimer
);
6252 this.keyPressBufferTimer
= setTimeout( this.clearKeyPressBuffer
.bind( this ), 1500 );
6254 item
= this.getHighlightedItem() || this.getSelectedItem();
6256 if ( this.keyPressBuffer
=== c
) {
6257 // Common (if weird) special case: typing "xxxx" will cycle through all
6258 // the items beginning with "x".
6260 item
= this.getRelativeSelectableItem( item
, 1 );
6263 this.keyPressBuffer
+= c
;
6266 filter
= this.getItemMatcher( this.keyPressBuffer
, false );
6267 if ( !item
|| !filter( item
) ) {
6268 item
= this.getRelativeSelectableItem( item
, 1, filter
);
6271 if ( this.isVisible() && item
.constructor.static.highlightable
) {
6272 this.highlightItem( item
);
6274 this.chooseItem( item
);
6276 this.scrollItemIntoView( item
);
6280 e
.stopPropagation();
6284 * Get a matcher for the specific string
6287 * @param {string} s String to match against items
6288 * @param {boolean} [exact=false] Only accept exact matches
6289 * @return {Function} function ( OO.ui.OptionWidget ) => boolean
6291 OO
.ui
.SelectWidget
.prototype.getItemMatcher = function ( s
, exact
) {
6294 if ( s
.normalize
) {
6297 s
= exact
? s
.trim() : s
.replace( /^\s+/, '' );
6298 re
= '^\\s*' + s
.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
6302 re
= new RegExp( re
, 'i' );
6303 return function ( item
) {
6304 var matchText
= item
.getMatchText();
6305 if ( matchText
.normalize
) {
6306 matchText
= matchText
.normalize();
6308 return re
.test( matchText
);
6313 * Bind key press listener.
6317 OO
.ui
.SelectWidget
.prototype.bindKeyPressListener = function () {
6318 this.getElementWindow().addEventListener( 'keypress', this.onKeyPressHandler
, true );
6322 * Unbind key down listener.
6324 * If you override this, be sure to call this.clearKeyPressBuffer() from your
6329 OO
.ui
.SelectWidget
.prototype.unbindKeyPressListener = function () {
6330 this.getElementWindow().removeEventListener( 'keypress', this.onKeyPressHandler
, true );
6331 this.clearKeyPressBuffer();
6335 * Visibility change handler
6338 * @param {boolean} visible
6340 OO
.ui
.SelectWidget
.prototype.onToggle = function ( visible
) {
6342 this.clearKeyPressBuffer();
6347 * Get the closest item to a jQuery.Event.
6350 * @param {jQuery.Event} e
6351 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
6353 OO
.ui
.SelectWidget
.prototype.getTargetItem = function ( e
) {
6354 return $( e
.target
).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
6358 * Get selected item.
6360 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
6362 OO
.ui
.SelectWidget
.prototype.getSelectedItem = function () {
6365 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6366 if ( this.items
[ i
].isSelected() ) {
6367 return this.items
[ i
];
6374 * Get highlighted item.
6376 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
6378 OO
.ui
.SelectWidget
.prototype.getHighlightedItem = function () {
6381 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6382 if ( this.items
[ i
].isHighlighted() ) {
6383 return this.items
[ i
];
6390 * Toggle pressed state.
6392 * Press is a state that occurs when a user mouses down on an item, but
6393 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
6394 * until the user releases the mouse.
6396 * @param {boolean} pressed An option is being pressed
6398 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
6399 if ( pressed
=== undefined ) {
6400 pressed
= !this.pressed
;
6402 if ( pressed
!== this.pressed
) {
6404 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
6405 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
6406 this.pressed
= pressed
;
6411 * Highlight an option. If the `item` param is omitted, no options will be highlighted
6412 * and any existing highlight will be removed. The highlight is mutually exclusive.
6414 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
6418 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
6419 var i
, len
, highlighted
,
6422 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6423 highlighted
= this.items
[ i
] === item
;
6424 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
6425 this.items
[ i
].setHighlighted( highlighted
);
6431 this.$focusOwner
.attr( 'aria-activedescendant', item
.getElementId() );
6433 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
6435 this.emit( 'highlight', item
);
6442 * Fetch an item by its label.
6444 * @param {string} label Label of the item to select.
6445 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
6446 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
6448 OO
.ui
.SelectWidget
.prototype.getItemFromLabel = function ( label
, prefix
) {
6450 len
= this.items
.length
,
6451 filter
= this.getItemMatcher( label
, true );
6453 for ( i
= 0; i
< len
; i
++ ) {
6454 item
= this.items
[ i
];
6455 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
6462 filter
= this.getItemMatcher( label
, false );
6463 for ( i
= 0; i
< len
; i
++ ) {
6464 item
= this.items
[ i
];
6465 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
6481 * Programmatically select an option by its label. If the item does not exist,
6482 * all options will be deselected.
6484 * @param {string} [label] Label of the item to select.
6485 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
6489 OO
.ui
.SelectWidget
.prototype.selectItemByLabel = function ( label
, prefix
) {
6490 var itemFromLabel
= this.getItemFromLabel( label
, !!prefix
);
6491 if ( label
=== undefined || !itemFromLabel
) {
6492 return this.selectItem();
6494 return this.selectItem( itemFromLabel
);
6498 * Programmatically select an option by its data. If the `data` parameter is omitted,
6499 * or if the item does not exist, all options will be deselected.
6501 * @param {Object|string} [data] Value of the item to select, omit to deselect all
6505 OO
.ui
.SelectWidget
.prototype.selectItemByData = function ( data
) {
6506 var itemFromData
= this.getItemFromData( data
);
6507 if ( data
=== undefined || !itemFromData
) {
6508 return this.selectItem();
6510 return this.selectItem( itemFromData
);
6514 * Programmatically select an option by its reference. If the `item` parameter is omitted,
6515 * all options will be deselected.
6517 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
6521 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
6522 var i
, len
, selected
,
6525 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6526 selected
= this.items
[ i
] === item
;
6527 if ( this.items
[ i
].isSelected() !== selected
) {
6528 this.items
[ i
].setSelected( selected
);
6533 if ( item
&& !item
.constructor.static.highlightable
) {
6535 this.$focusOwner
.attr( 'aria-activedescendant', item
.getElementId() );
6537 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
6540 this.emit( 'select', item
);
6549 * Press is a state that occurs when a user mouses down on an item, but has not
6550 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
6551 * releases the mouse.
6553 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
6557 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
6558 var i
, len
, pressed
,
6561 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6562 pressed
= this.items
[ i
] === item
;
6563 if ( this.items
[ i
].isPressed() !== pressed
) {
6564 this.items
[ i
].setPressed( pressed
);
6569 this.emit( 'press', item
);
6578 * Note that ‘choose’ should never be modified programmatically. A user can choose
6579 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
6580 * use the #selectItem method.
6582 * This method is identical to #selectItem, but may vary in subclasses that take additional action
6583 * when users choose an item with the keyboard or mouse.
6585 * @param {OO.ui.OptionWidget} item Item to choose
6589 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
6591 this.selectItem( item
);
6592 this.emit( 'choose', item
);
6599 * Get an option by its position relative to the specified item (or to the start of the option array,
6600 * if item is `null`). The direction in which to search through the option array is specified with a
6601 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
6602 * `null` if there are no options in the array.
6604 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
6605 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
6606 * @param {Function} [filter] Only consider items for which this function returns
6607 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
6608 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
6610 OO
.ui
.SelectWidget
.prototype.getRelativeSelectableItem = function ( item
, direction
, filter
) {
6611 var currentIndex
, nextIndex
, i
,
6612 increase
= direction
> 0 ? 1 : -1,
6613 len
= this.items
.length
;
6615 if ( item
instanceof OO
.ui
.OptionWidget
) {
6616 currentIndex
= this.items
.indexOf( item
);
6617 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
6619 // If no item is selected and moving forward, start at the beginning.
6620 // If moving backward, start at the end.
6621 nextIndex
= direction
> 0 ? 0 : len
- 1;
6624 for ( i
= 0; i
< len
; i
++ ) {
6625 item
= this.items
[ nextIndex
];
6627 item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() &&
6628 ( !filter
|| filter( item
) )
6632 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
6638 * Get the next selectable item or `null` if there are no selectable items.
6639 * Disabled options and menu-section markers and breaks are not selectable.
6641 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
6643 OO
.ui
.SelectWidget
.prototype.getFirstSelectableItem = function () {
6644 return this.getRelativeSelectableItem( null, 1 );
6648 * Add an array of options to the select. Optionally, an index number can be used to
6649 * specify an insertion point.
6651 * @param {OO.ui.OptionWidget[]} items Items to add
6652 * @param {number} [index] Index to insert items after
6656 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
6658 OO
.ui
.mixin
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
6660 // Always provide an index, even if it was omitted
6661 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
6667 * Remove the specified array of options from the select. Options will be detached
6668 * from the DOM, not removed, so they can be reused later. To remove all options from
6669 * the select, you may wish to use the #clearItems method instead.
6671 * @param {OO.ui.OptionWidget[]} items Items to remove
6675 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
6678 // Deselect items being removed
6679 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
6681 if ( item
.isSelected() ) {
6682 this.selectItem( null );
6687 OO
.ui
.mixin
.GroupWidget
.prototype.removeItems
.call( this, items
);
6689 this.emit( 'remove', items
);
6695 * Clear all options from the select. Options will be detached from the DOM, not removed,
6696 * so that they can be reused later. To remove a subset of options from the select, use
6697 * the #removeItems method.
6702 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
6703 var items
= this.items
.slice();
6706 OO
.ui
.mixin
.GroupWidget
.prototype.clearItems
.call( this );
6709 this.selectItem( null );
6711 this.emit( 'remove', items
);
6717 * Set the DOM element which has focus while the user is interacting with this SelectWidget.
6719 * Currently this is just used to set `aria-activedescendant` on it.
6722 * @param {jQuery} $focusOwner
6724 OO
.ui
.SelectWidget
.prototype.setFocusOwner = function ( $focusOwner
) {
6725 this.$focusOwner
= $focusOwner
;
6729 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
6730 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
6731 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
6732 * options. For more information about options and selects, please see the
6733 * [OOjs UI documentation on MediaWiki][1].
6736 * // Decorated options in a select widget
6737 * var select = new OO.ui.SelectWidget( {
6739 * new OO.ui.DecoratedOptionWidget( {
6741 * label: 'Option with icon',
6744 * new OO.ui.DecoratedOptionWidget( {
6746 * label: 'Option with indicator',
6751 * $( 'body' ).append( select.$element );
6753 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
6756 * @extends OO.ui.OptionWidget
6757 * @mixins OO.ui.mixin.IconElement
6758 * @mixins OO.ui.mixin.IndicatorElement
6761 * @param {Object} [config] Configuration options
6763 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
6764 // Parent constructor
6765 OO
.ui
.DecoratedOptionWidget
.parent
.call( this, config
);
6767 // Mixin constructors
6768 OO
.ui
.mixin
.IconElement
.call( this, config
);
6769 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
6773 .addClass( 'oo-ui-decoratedOptionWidget' )
6774 .prepend( this.$icon
)
6775 .append( this.$indicator
);
6780 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
6781 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IconElement
);
6782 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IndicatorElement
);
6785 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
6786 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
6787 * the [OOjs UI documentation on MediaWiki] [1] for more information.
6789 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
6792 * @extends OO.ui.DecoratedOptionWidget
6795 * @param {Object} [config] Configuration options
6797 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
6798 // Parent constructor
6799 OO
.ui
.MenuOptionWidget
.parent
.call( this, config
);
6802 this.$element
.addClass( 'oo-ui-menuOptionWidget' );
6807 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
6809 /* Static Properties */
6815 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
6818 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
6819 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
6822 * var myDropdown = new OO.ui.DropdownWidget( {
6825 * new OO.ui.MenuSectionOptionWidget( {
6828 * new OO.ui.MenuOptionWidget( {
6830 * label: 'Welsh Corgi'
6832 * new OO.ui.MenuOptionWidget( {
6834 * label: 'Standard Poodle'
6836 * new OO.ui.MenuSectionOptionWidget( {
6839 * new OO.ui.MenuOptionWidget( {
6846 * $( 'body' ).append( myDropdown.$element );
6849 * @extends OO.ui.DecoratedOptionWidget
6852 * @param {Object} [config] Configuration options
6854 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
6855 // Parent constructor
6856 OO
.ui
.MenuSectionOptionWidget
.parent
.call( this, config
);
6859 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' )
6860 .removeAttr( 'role aria-selected' );
6865 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
6867 /* Static Properties */
6873 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
6879 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
6882 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
6883 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
6884 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
6885 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
6886 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
6887 * and customized to be opened, closed, and displayed as needed.
6889 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
6890 * mouse outside the menu.
6892 * Menus also have support for keyboard interaction:
6894 * - Enter/Return key: choose and select a menu option
6895 * - Up-arrow key: highlight the previous menu option
6896 * - Down-arrow key: highlight the next menu option
6897 * - Esc key: hide the menu
6899 * Unlike most widgets, MenuSelectWidget is initially hidden and must be shown by calling #toggle.
6901 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
6902 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
6905 * @extends OO.ui.SelectWidget
6906 * @mixins OO.ui.mixin.ClippableElement
6907 * @mixins OO.ui.mixin.FloatableElement
6910 * @param {Object} [config] Configuration options
6911 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
6912 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
6913 * and {@link OO.ui.mixin.LookupElement LookupElement}
6914 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
6915 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiselectWidget CapsuleMultiselectWidget}
6916 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
6917 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
6918 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
6919 * that button, unless the button (or its parent widget) is passed in here.
6920 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
6921 * @cfg {jQuery} [$autoCloseIgnore] If these elements are clicked, don't auto-hide the menu.
6922 * @cfg {boolean} [hideOnChoose=true] Hide the menu when the user chooses an option.
6923 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
6924 * @cfg {boolean} [highlightOnFilter] Highlight the first result when filtering
6925 * @cfg {number} [width] Width of the menu
6927 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
6928 // Configuration initialization
6929 config
= config
|| {};
6931 // Parent constructor
6932 OO
.ui
.MenuSelectWidget
.parent
.call( this, config
);
6934 // Mixin constructors
6935 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
6936 OO
.ui
.mixin
.FloatableElement
.call( this, config
);
6939 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
6940 this.hideOnChoose
= config
.hideOnChoose
=== undefined || !!config
.hideOnChoose
;
6941 this.filterFromInput
= !!config
.filterFromInput
;
6942 this.$input
= config
.$input
? config
.$input
: config
.input
? config
.input
.$input
: null;
6943 this.$widget
= config
.widget
? config
.widget
.$element
: null;
6944 this.$autoCloseIgnore
= config
.$autoCloseIgnore
|| $( [] );
6945 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
6946 this.onInputEditHandler
= OO
.ui
.debounce( this.updateItemVisibility
.bind( this ), 100 );
6947 this.highlightOnFilter
= !!config
.highlightOnFilter
;
6948 this.width
= config
.width
;
6951 this.$element
.addClass( 'oo-ui-menuSelectWidget' );
6952 if ( config
.widget
) {
6953 this.setFocusOwner( config
.widget
.$tabIndexed
);
6956 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
6957 // that reference properties not initialized at that time of parent class construction
6958 // TODO: Find a better way to handle post-constructor setup
6959 this.visible
= false;
6960 this.$element
.addClass( 'oo-ui-element-hidden' );
6965 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
6966 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.ClippableElement
);
6967 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.FloatableElement
);
6974 * The menu is ready: it is visible and has been positioned and clipped.
6980 * Handles document mouse down events.
6983 * @param {MouseEvent} e Mouse down event
6985 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
6989 this.$element
.add( this.$widget
).add( this.$autoCloseIgnore
).get(),
6994 this.toggle( false );
7001 OO
.ui
.MenuSelectWidget
.prototype.onKeyDown = function ( e
) {
7002 var currentItem
= this.getHighlightedItem() || this.getSelectedItem();
7004 if ( !this.isDisabled() && this.isVisible() ) {
7005 switch ( e
.keyCode
) {
7006 case OO
.ui
.Keys
.LEFT
:
7007 case OO
.ui
.Keys
.RIGHT
:
7008 // Do nothing if a text field is associated, arrow keys will be handled natively
7009 if ( !this.$input
) {
7010 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
7013 case OO
.ui
.Keys
.ESCAPE
:
7014 case OO
.ui
.Keys
.TAB
:
7015 if ( currentItem
) {
7016 currentItem
.setHighlighted( false );
7018 this.toggle( false );
7019 // Don't prevent tabbing away, prevent defocusing
7020 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
7022 e
.stopPropagation();
7026 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
7033 * Update menu item visibility and clipping after input changes (if filterFromInput is enabled)
7034 * or after items were added/removed (always).
7038 OO
.ui
.MenuSelectWidget
.prototype.updateItemVisibility = function () {
7039 var i
, item
, visible
, section
, sectionEmpty
, filter
, exactFilter
,
7040 firstItemFound
= false,
7042 len
= this.items
.length
,
7043 showAll
= !this.isVisible(),
7046 if ( this.$input
&& this.filterFromInput
) {
7047 filter
= showAll
? null : this.getItemMatcher( this.$input
.val() );
7048 exactFilter
= this.getItemMatcher( this.$input
.val(), true );
7050 // Hide non-matching options, and also hide section headers if all options
7051 // in their section are hidden.
7052 for ( i
= 0; i
< len
; i
++ ) {
7053 item
= this.items
[ i
];
7054 if ( item
instanceof OO
.ui
.MenuSectionOptionWidget
) {
7056 // If the previous section was empty, hide its header
7057 section
.toggle( showAll
|| !sectionEmpty
);
7060 sectionEmpty
= true;
7061 } else if ( item
instanceof OO
.ui
.OptionWidget
) {
7062 visible
= showAll
|| filter( item
);
7063 exactMatch
= exactMatch
|| exactFilter( item
);
7064 anyVisible
= anyVisible
|| visible
;
7065 sectionEmpty
= sectionEmpty
&& !visible
;
7066 item
.toggle( visible
);
7067 if ( this.highlightOnFilter
&& visible
&& !firstItemFound
) {
7068 // Highlight the first item in the list
7069 this.highlightItem( item
);
7070 firstItemFound
= true;
7074 // Process the final section
7076 section
.toggle( showAll
|| !sectionEmpty
);
7079 if ( anyVisible
&& this.items
.length
&& !exactMatch
) {
7080 this.scrollItemIntoView( this.items
[ 0 ] );
7083 this.$element
.toggleClass( 'oo-ui-menuSelectWidget-invisible', !anyVisible
);
7086 // Reevaluate clipping
7093 OO
.ui
.MenuSelectWidget
.prototype.bindKeyDownListener = function () {
7094 if ( this.$input
) {
7095 this.$input
.on( 'keydown', this.onKeyDownHandler
);
7097 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyDownListener
.call( this );
7104 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyDownListener = function () {
7105 if ( this.$input
) {
7106 this.$input
.off( 'keydown', this.onKeyDownHandler
);
7108 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyDownListener
.call( this );
7115 OO
.ui
.MenuSelectWidget
.prototype.bindKeyPressListener = function () {
7116 if ( this.$input
) {
7117 if ( this.filterFromInput
) {
7118 this.$input
.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
7119 this.updateItemVisibility();
7122 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyPressListener
.call( this );
7129 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyPressListener = function () {
7130 if ( this.$input
) {
7131 if ( this.filterFromInput
) {
7132 this.$input
.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
7133 this.updateItemVisibility();
7136 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyPressListener
.call( this );
7143 * When a user chooses an item, the menu is closed, unless the hideOnChoose config option is set to false.
7145 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
7146 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
7148 * @param {OO.ui.OptionWidget} item Item to choose
7151 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
7152 OO
.ui
.MenuSelectWidget
.parent
.prototype.chooseItem
.call( this, item
);
7153 if ( this.hideOnChoose
) {
7154 this.toggle( false );
7162 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
7164 OO
.ui
.MenuSelectWidget
.parent
.prototype.addItems
.call( this, items
, index
);
7166 this.updateItemVisibility();
7174 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
7176 OO
.ui
.MenuSelectWidget
.parent
.prototype.removeItems
.call( this, items
);
7178 this.updateItemVisibility();
7186 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
7188 OO
.ui
.MenuSelectWidget
.parent
.prototype.clearItems
.call( this );
7190 this.updateItemVisibility();
7196 * Toggle visibility of the menu. The menu is initially hidden and must be shown by calling
7197 * `.toggle( true )` after its #$element is attached to the DOM.
7199 * Do not show the menu while it is not attached to the DOM. The calculations required to display
7200 * it in the right place and with the right dimensions only work correctly while it is attached.
7201 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
7202 * strictly enforced, so currently it only generates a warning in the browser console.
7207 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
7210 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
7211 change
= visible
!== this.isVisible();
7213 if ( visible
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
7214 OO
.ui
.warnDeprecation( 'MenuSelectWidget#toggle: Before calling this method, the menu must be attached to the DOM.' );
7215 this.warnedUnattached
= true;
7218 if ( change
&& visible
&& ( this.width
|| this.$floatableContainer
) ) {
7219 this.setIdealSize( this.width
|| this.$floatableContainer
.width() );
7223 OO
.ui
.MenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
7227 this.bindKeyDownListener();
7228 this.bindKeyPressListener();
7230 this.togglePositioning( !!this.$floatableContainer
);
7231 this.toggleClipping( true );
7233 if ( this.getSelectedItem() ) {
7234 this.$focusOwner
.attr( 'aria-activedescendant', this.getSelectedItem().getElementId() );
7235 this.getSelectedItem().scrollElementIntoView( { duration
: 0 } );
7239 if ( this.autoHide
) {
7240 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
7243 this.emit( 'ready' );
7245 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
7246 this.unbindKeyDownListener();
7247 this.unbindKeyPressListener();
7248 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
7249 this.togglePositioning( false );
7250 this.toggleClipping( false );
7258 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
7259 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
7260 * users can interact with it.
7262 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7263 * OO.ui.DropdownInputWidget instead.
7266 * // Example: A DropdownWidget with a menu that contains three options
7267 * var dropDown = new OO.ui.DropdownWidget( {
7268 * label: 'Dropdown menu: Select a menu option',
7271 * new OO.ui.MenuOptionWidget( {
7275 * new OO.ui.MenuOptionWidget( {
7279 * new OO.ui.MenuOptionWidget( {
7287 * $( 'body' ).append( dropDown.$element );
7289 * dropDown.getMenu().selectItemByData( 'b' );
7291 * dropDown.getMenu().getSelectedItem().getData(); // returns 'b'
7293 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
7295 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
7298 * @extends OO.ui.Widget
7299 * @mixins OO.ui.mixin.IconElement
7300 * @mixins OO.ui.mixin.IndicatorElement
7301 * @mixins OO.ui.mixin.LabelElement
7302 * @mixins OO.ui.mixin.TitledElement
7303 * @mixins OO.ui.mixin.TabIndexedElement
7306 * @param {Object} [config] Configuration options
7307 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.MenuSelectWidget menu select widget}
7308 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
7309 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
7310 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
7311 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
7313 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
7314 // Configuration initialization
7315 config
= $.extend( { indicator
: 'down' }, config
);
7317 // Parent constructor
7318 OO
.ui
.DropdownWidget
.parent
.call( this, config
);
7320 // Properties (must be set before TabIndexedElement constructor call)
7321 this.$handle
= this.$( '<span>' );
7322 this.$overlay
= config
.$overlay
|| this.$element
;
7324 // Mixin constructors
7325 OO
.ui
.mixin
.IconElement
.call( this, config
);
7326 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
7327 OO
.ui
.mixin
.LabelElement
.call( this, config
);
7328 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
7329 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
7332 this.menu
= new OO
.ui
.MenuSelectWidget( $.extend( {
7334 $floatableContainer
: this.$element
7339 click
: this.onClick
.bind( this ),
7340 keydown
: this.onKeyDown
.bind( this ),
7341 // Hack? Handle type-to-search when menu is not expanded and not handling its own events
7342 keypress
: this.menu
.onKeyPressHandler
,
7343 blur
: this.menu
.clearKeyPressBuffer
.bind( this.menu
)
7345 this.menu
.connect( this, {
7346 select
: 'onMenuSelect',
7347 toggle
: 'onMenuToggle'
7352 .addClass( 'oo-ui-dropdownWidget-handle' )
7355 'aria-owns': this.menu
.getElementId(),
7356 'aria-autocomplete': 'list'
7358 .append( this.$icon
, this.$label
, this.$indicator
);
7360 .addClass( 'oo-ui-dropdownWidget' )
7361 .append( this.$handle
);
7362 this.$overlay
.append( this.menu
.$element
);
7367 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
7368 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IconElement
);
7369 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IndicatorElement
);
7370 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.LabelElement
);
7371 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TitledElement
);
7372 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TabIndexedElement
);
7379 * @return {OO.ui.MenuSelectWidget} Menu of widget
7381 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
7386 * Handles menu select events.
7389 * @param {OO.ui.MenuOptionWidget} item Selected menu item
7391 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
7395 this.setLabel( null );
7399 selectedLabel
= item
.getLabel();
7401 // If the label is a DOM element, clone it, because setLabel will append() it
7402 if ( selectedLabel
instanceof jQuery
) {
7403 selectedLabel
= selectedLabel
.clone();
7406 this.setLabel( selectedLabel
);
7410 * Handle menu toggle events.
7413 * @param {boolean} isVisible Menu toggle event
7415 OO
.ui
.DropdownWidget
.prototype.onMenuToggle = function ( isVisible
) {
7416 this.$element
.toggleClass( 'oo-ui-dropdownWidget-open', isVisible
);
7420 * Handle mouse click events.
7423 * @param {jQuery.Event} e Mouse click event
7425 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
7426 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
7433 * Handle key down events.
7436 * @param {jQuery.Event} e Key down event
7438 OO
.ui
.DropdownWidget
.prototype.onKeyDown = function ( e
) {
7440 !this.isDisabled() &&
7442 e
.which
=== OO
.ui
.Keys
.ENTER
||
7444 !this.menu
.isVisible() &&
7446 e
.which
=== OO
.ui
.Keys
.SPACE
||
7447 e
.which
=== OO
.ui
.Keys
.UP
||
7448 e
.which
=== OO
.ui
.Keys
.DOWN
7459 * RadioOptionWidget is an option widget that looks like a radio button.
7460 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
7461 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
7463 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
7466 * @extends OO.ui.OptionWidget
7469 * @param {Object} [config] Configuration options
7471 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
7472 // Configuration initialization
7473 config
= config
|| {};
7475 // Properties (must be done before parent constructor which calls #setDisabled)
7476 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
7478 // Parent constructor
7479 OO
.ui
.RadioOptionWidget
.parent
.call( this, config
);
7482 // Remove implicit role, we're handling it ourselves
7483 this.radio
.$input
.attr( 'role', 'presentation' );
7485 .addClass( 'oo-ui-radioOptionWidget' )
7486 .attr( 'role', 'radio' )
7487 .attr( 'aria-checked', 'false' )
7488 .removeAttr( 'aria-selected' )
7489 .prepend( this.radio
.$element
);
7494 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
7496 /* Static Properties */
7502 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
7508 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
7514 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
7520 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
7527 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
7528 OO
.ui
.RadioOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
7530 this.radio
.setSelected( state
);
7532 .attr( 'aria-checked', state
.toString() )
7533 .removeAttr( 'aria-selected' );
7541 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
7542 OO
.ui
.RadioOptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
7544 this.radio
.setDisabled( this.isDisabled() );
7550 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
7551 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
7552 * an interface for adding, removing and selecting options.
7553 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
7555 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7556 * OO.ui.RadioSelectInputWidget instead.
7559 * // A RadioSelectWidget with RadioOptions.
7560 * var option1 = new OO.ui.RadioOptionWidget( {
7562 * label: 'Selected radio option'
7565 * var option2 = new OO.ui.RadioOptionWidget( {
7567 * label: 'Unselected radio option'
7570 * var radioSelect=new OO.ui.RadioSelectWidget( {
7571 * items: [ option1, option2 ]
7574 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
7575 * radioSelect.selectItem( option1 );
7577 * $( 'body' ).append( radioSelect.$element );
7579 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
7583 * @extends OO.ui.SelectWidget
7584 * @mixins OO.ui.mixin.TabIndexedElement
7587 * @param {Object} [config] Configuration options
7589 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
7590 // Parent constructor
7591 OO
.ui
.RadioSelectWidget
.parent
.call( this, config
);
7593 // Mixin constructors
7594 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
7598 focus
: this.bindKeyDownListener
.bind( this ),
7599 blur
: this.unbindKeyDownListener
.bind( this )
7604 .addClass( 'oo-ui-radioSelectWidget' )
7605 .attr( 'role', 'radiogroup' );
7610 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
7611 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
7614 * MultioptionWidgets are special elements that can be selected and configured with data. The
7615 * data is often unique for each option, but it does not have to be. MultioptionWidgets are used
7616 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
7617 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
7619 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Multioptions
7622 * @extends OO.ui.Widget
7623 * @mixins OO.ui.mixin.ItemWidget
7624 * @mixins OO.ui.mixin.LabelElement
7627 * @param {Object} [config] Configuration options
7628 * @cfg {boolean} [selected=false] Whether the option is initially selected
7630 OO
.ui
.MultioptionWidget
= function OoUiMultioptionWidget( config
) {
7631 // Configuration initialization
7632 config
= config
|| {};
7634 // Parent constructor
7635 OO
.ui
.MultioptionWidget
.parent
.call( this, config
);
7637 // Mixin constructors
7638 OO
.ui
.mixin
.ItemWidget
.call( this );
7639 OO
.ui
.mixin
.LabelElement
.call( this, config
);
7642 this.selected
= null;
7646 .addClass( 'oo-ui-multioptionWidget' )
7647 .append( this.$label
);
7648 this.setSelected( config
.selected
);
7653 OO
.inheritClass( OO
.ui
.MultioptionWidget
, OO
.ui
.Widget
);
7654 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.ItemWidget
);
7655 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.LabelElement
);
7662 * A change event is emitted when the selected state of the option changes.
7664 * @param {boolean} selected Whether the option is now selected
7670 * Check if the option is selected.
7672 * @return {boolean} Item is selected
7674 OO
.ui
.MultioptionWidget
.prototype.isSelected = function () {
7675 return this.selected
;
7679 * Set the option’s selected state. In general, all modifications to the selection
7680 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
7681 * method instead of this method.
7683 * @param {boolean} [state=false] Select option
7686 OO
.ui
.MultioptionWidget
.prototype.setSelected = function ( state
) {
7688 if ( this.selected
!== state
) {
7689 this.selected
= state
;
7690 this.emit( 'change', state
);
7691 this.$element
.toggleClass( 'oo-ui-multioptionWidget-selected', state
);
7697 * MultiselectWidget allows selecting multiple options from a list.
7699 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
7701 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
7705 * @extends OO.ui.Widget
7706 * @mixins OO.ui.mixin.GroupWidget
7709 * @param {Object} [config] Configuration options
7710 * @cfg {OO.ui.MultioptionWidget[]} [items] An array of options to add to the multiselect.
7712 OO
.ui
.MultiselectWidget
= function OoUiMultiselectWidget( config
) {
7713 // Parent constructor
7714 OO
.ui
.MultiselectWidget
.parent
.call( this, config
);
7716 // Configuration initialization
7717 config
= config
|| {};
7719 // Mixin constructors
7720 OO
.ui
.mixin
.GroupWidget
.call( this, config
);
7723 this.aggregate( { change
: 'select' } );
7724 // This is mostly for compatibility with CapsuleMultiselectWidget... normally, 'change' is emitted
7725 // by GroupElement only when items are added/removed
7726 this.connect( this, { select
: [ 'emit', 'change' ] } );
7729 if ( config
.items
) {
7730 this.addItems( config
.items
);
7732 this.$group
.addClass( 'oo-ui-multiselectWidget-group' );
7733 this.$element
.addClass( 'oo-ui-multiselectWidget' )
7734 .append( this.$group
);
7739 OO
.inheritClass( OO
.ui
.MultiselectWidget
, OO
.ui
.Widget
);
7740 OO
.mixinClass( OO
.ui
.MultiselectWidget
, OO
.ui
.mixin
.GroupWidget
);
7747 * A change event is emitted when the set of items changes, or an item is selected or deselected.
7753 * A select event is emitted when an item is selected or deselected.
7759 * Get options that are selected.
7761 * @return {OO.ui.MultioptionWidget[]} Selected options
7763 OO
.ui
.MultiselectWidget
.prototype.getSelectedItems = function () {
7764 return this.items
.filter( function ( item
) {
7765 return item
.isSelected();
7770 * Get the data of options that are selected.
7772 * @return {Object[]|string[]} Values of selected options
7774 OO
.ui
.MultiselectWidget
.prototype.getSelectedItemsData = function () {
7775 return this.getSelectedItems().map( function ( item
) {
7781 * Select options by reference. Options not mentioned in the `items` array will be deselected.
7783 * @param {OO.ui.MultioptionWidget[]} items Items to select
7786 OO
.ui
.MultiselectWidget
.prototype.selectItems = function ( items
) {
7787 this.items
.forEach( function ( item
) {
7788 var selected
= items
.indexOf( item
) !== -1;
7789 item
.setSelected( selected
);
7795 * Select items by their data. Options not mentioned in the `datas` array will be deselected.
7797 * @param {Object[]|string[]} datas Values of items to select
7800 OO
.ui
.MultiselectWidget
.prototype.selectItemsByData = function ( datas
) {
7803 items
= datas
.map( function ( data
) {
7804 return widget
.getItemFromData( data
);
7806 this.selectItems( items
);
7811 * CheckboxMultioptionWidget is an option widget that looks like a checkbox.
7812 * The class is used with OO.ui.CheckboxMultiselectWidget to create a selection of checkbox options.
7813 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
7815 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
7818 * @extends OO.ui.MultioptionWidget
7821 * @param {Object} [config] Configuration options
7823 OO
.ui
.CheckboxMultioptionWidget
= function OoUiCheckboxMultioptionWidget( config
) {
7824 // Configuration initialization
7825 config
= config
|| {};
7827 // Properties (must be done before parent constructor which calls #setDisabled)
7828 this.checkbox
= new OO
.ui
.CheckboxInputWidget();
7830 // Parent constructor
7831 OO
.ui
.CheckboxMultioptionWidget
.parent
.call( this, config
);
7834 this.checkbox
.on( 'change', this.onCheckboxChange
.bind( this ) );
7835 this.$element
.on( 'keydown', this.onKeyDown
.bind( this ) );
7839 .addClass( 'oo-ui-checkboxMultioptionWidget' )
7840 .prepend( this.checkbox
.$element
);
7845 OO
.inheritClass( OO
.ui
.CheckboxMultioptionWidget
, OO
.ui
.MultioptionWidget
);
7847 /* Static Properties */
7853 OO
.ui
.CheckboxMultioptionWidget
.static.tagName
= 'label';
7858 * Handle checkbox selected state change.
7862 OO
.ui
.CheckboxMultioptionWidget
.prototype.onCheckboxChange = function () {
7863 this.setSelected( this.checkbox
.isSelected() );
7869 OO
.ui
.CheckboxMultioptionWidget
.prototype.setSelected = function ( state
) {
7870 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setSelected
.call( this, state
);
7871 this.checkbox
.setSelected( state
);
7878 OO
.ui
.CheckboxMultioptionWidget
.prototype.setDisabled = function ( disabled
) {
7879 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
7880 this.checkbox
.setDisabled( this.isDisabled() );
7887 OO
.ui
.CheckboxMultioptionWidget
.prototype.focus = function () {
7888 this.checkbox
.focus();
7892 * Handle key down events.
7895 * @param {jQuery.Event} e
7897 OO
.ui
.CheckboxMultioptionWidget
.prototype.onKeyDown = function ( e
) {
7899 element
= this.getElementGroup(),
7902 if ( e
.keyCode
=== OO
.ui
.Keys
.LEFT
|| e
.keyCode
=== OO
.ui
.Keys
.UP
) {
7903 nextItem
= element
.getRelativeFocusableItem( this, -1 );
7904 } else if ( e
.keyCode
=== OO
.ui
.Keys
.RIGHT
|| e
.keyCode
=== OO
.ui
.Keys
.DOWN
) {
7905 nextItem
= element
.getRelativeFocusableItem( this, 1 );
7915 * CheckboxMultiselectWidget is a {@link OO.ui.MultiselectWidget multiselect widget} that contains
7916 * checkboxes and is used together with OO.ui.CheckboxMultioptionWidget. The
7917 * CheckboxMultiselectWidget provides an interface for adding, removing and selecting options.
7918 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
7920 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7921 * OO.ui.CheckboxMultiselectInputWidget instead.
7924 * // A CheckboxMultiselectWidget with CheckboxMultioptions.
7925 * var option1 = new OO.ui.CheckboxMultioptionWidget( {
7928 * label: 'Selected checkbox'
7931 * var option2 = new OO.ui.CheckboxMultioptionWidget( {
7933 * label: 'Unselected checkbox'
7936 * var multiselect=new OO.ui.CheckboxMultiselectWidget( {
7937 * items: [ option1, option2 ]
7940 * $( 'body' ).append( multiselect.$element );
7942 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
7945 * @extends OO.ui.MultiselectWidget
7948 * @param {Object} [config] Configuration options
7950 OO
.ui
.CheckboxMultiselectWidget
= function OoUiCheckboxMultiselectWidget( config
) {
7951 // Parent constructor
7952 OO
.ui
.CheckboxMultiselectWidget
.parent
.call( this, config
);
7955 this.$lastClicked
= null;
7958 this.$group
.on( 'click', this.onClick
.bind( this ) );
7962 .addClass( 'oo-ui-checkboxMultiselectWidget' );
7967 OO
.inheritClass( OO
.ui
.CheckboxMultiselectWidget
, OO
.ui
.MultiselectWidget
);
7972 * Get an option by its position relative to the specified item (or to the start of the option array,
7973 * if item is `null`). The direction in which to search through the option array is specified with a
7974 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
7975 * `null` if there are no options in the array.
7977 * @param {OO.ui.CheckboxMultioptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
7978 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
7979 * @return {OO.ui.CheckboxMultioptionWidget|null} Item at position, `null` if there are no items in the select
7981 OO
.ui
.CheckboxMultiselectWidget
.prototype.getRelativeFocusableItem = function ( item
, direction
) {
7982 var currentIndex
, nextIndex
, i
,
7983 increase
= direction
> 0 ? 1 : -1,
7984 len
= this.items
.length
;
7987 currentIndex
= this.items
.indexOf( item
);
7988 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
7990 // If no item is selected and moving forward, start at the beginning.
7991 // If moving backward, start at the end.
7992 nextIndex
= direction
> 0 ? 0 : len
- 1;
7995 for ( i
= 0; i
< len
; i
++ ) {
7996 item
= this.items
[ nextIndex
];
7997 if ( item
&& !item
.isDisabled() ) {
8000 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
8006 * Handle click events on checkboxes.
8008 * @param {jQuery.Event} e
8010 OO
.ui
.CheckboxMultiselectWidget
.prototype.onClick = function ( e
) {
8011 var $options
, lastClickedIndex
, nowClickedIndex
, i
, direction
, wasSelected
, items
,
8012 $lastClicked
= this.$lastClicked
,
8013 $nowClicked
= $( e
.target
).closest( '.oo-ui-checkboxMultioptionWidget' )
8014 .not( '.oo-ui-widget-disabled' );
8016 // Allow selecting multiple options at once by Shift-clicking them
8017 if ( $lastClicked
&& $nowClicked
.length
&& e
.shiftKey
) {
8018 $options
= this.$group
.find( '.oo-ui-checkboxMultioptionWidget' );
8019 lastClickedIndex
= $options
.index( $lastClicked
);
8020 nowClickedIndex
= $options
.index( $nowClicked
);
8021 // If it's the same item, either the user is being silly, or it's a fake event generated by the
8022 // browser. In either case we don't need custom handling.
8023 if ( nowClickedIndex
!== lastClickedIndex
) {
8025 wasSelected
= items
[ nowClickedIndex
].isSelected();
8026 direction
= nowClickedIndex
> lastClickedIndex
? 1 : -1;
8028 // This depends on the DOM order of the items and the order of the .items array being the same.
8029 for ( i
= lastClickedIndex
; i
!== nowClickedIndex
; i
+= direction
) {
8030 if ( !items
[ i
].isDisabled() ) {
8031 items
[ i
].setSelected( !wasSelected
);
8034 // For the now-clicked element, use immediate timeout to allow the browser to do its own
8035 // handling first, then set our value. The order in which events happen is different for
8036 // clicks on the <input> and on the <label> and there are additional fake clicks fired for
8037 // non-click actions that change the checkboxes.
8039 setTimeout( function () {
8040 if ( !items
[ nowClickedIndex
].isDisabled() ) {
8041 items
[ nowClickedIndex
].setSelected( !wasSelected
);
8047 if ( $nowClicked
.length
) {
8048 this.$lastClicked
= $nowClicked
;
8057 OO
.ui
.CheckboxMultiselectWidget
.prototype.focus = function () {
8059 if ( !this.isDisabled() ) {
8060 item
= this.getRelativeFocusableItem( null, 1 );
8071 OO
.ui
.CheckboxMultiselectWidget
.prototype.simulateLabelClick = function () {
8076 * FloatingMenuSelectWidget was a menu that would stick under a specified
8077 * container, even when it is inserted elsewhere in the document.
8078 * This functionality is now included in MenuSelectWidget, and FloatingMenuSelectWidget
8079 * is preserved for backwards-compatibility.
8082 * @extends OO.ui.MenuSelectWidget
8083 * @deprecated since v0.21.3, use MenuSelectWidget instead.
8086 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
8087 * Deprecated, omit this parameter and specify `$container` instead.
8088 * @param {Object} [config] Configuration options
8089 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
8091 OO
.ui
.FloatingMenuSelectWidget
= function OoUiFloatingMenuSelectWidget( inputWidget
, config
) {
8092 OO
.ui
.warnDeprecation( 'FloatingMenuSelectWidget is deprecated. Use the MenuSelectWidget instead.' );
8094 // Allow 'inputWidget' parameter and config for backwards compatibility
8095 if ( OO
.isPlainObject( inputWidget
) && config
=== undefined ) {
8096 config
= inputWidget
;
8097 inputWidget
= config
.inputWidget
;
8100 // Configuration initialization
8101 config
= config
|| {};
8104 this.inputWidget
= inputWidget
; // For backwards compatibility
8105 this.$container
= config
.$floatableContainer
|| config
.$container
|| this.inputWidget
.$element
;
8107 // Parent constructor
8108 OO
.ui
.FloatingMenuSelectWidget
.parent
.call( this, $.extend( {}, config
, { $floatableContainer
: this.$container
} ) );
8111 this.$element
.addClass( 'oo-ui-floatingMenuSelectWidget' );
8112 // For backwards compatibility
8113 this.$element
.addClass( 'oo-ui-textInputMenuSelectWidget' );
8118 OO
.inheritClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.MenuSelectWidget
);
8121 * Progress bars visually display the status of an operation, such as a download,
8122 * and can be either determinate or indeterminate:
8124 * - **determinate** process bars show the percent of an operation that is complete.
8126 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
8127 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
8128 * not use percentages.
8130 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
8133 * // Examples of determinate and indeterminate progress bars.
8134 * var progressBar1 = new OO.ui.ProgressBarWidget( {
8137 * var progressBar2 = new OO.ui.ProgressBarWidget();
8139 * // Create a FieldsetLayout to layout progress bars
8140 * var fieldset = new OO.ui.FieldsetLayout;
8141 * fieldset.addItems( [
8142 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
8143 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
8145 * $( 'body' ).append( fieldset.$element );
8148 * @extends OO.ui.Widget
8151 * @param {Object} [config] Configuration options
8152 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
8153 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
8154 * By default, the progress bar is indeterminate.
8156 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
8157 // Configuration initialization
8158 config
= config
|| {};
8160 // Parent constructor
8161 OO
.ui
.ProgressBarWidget
.parent
.call( this, config
);
8164 this.$bar
= $( '<div>' );
8165 this.progress
= null;
8168 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
8169 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
8172 role
: 'progressbar',
8174 'aria-valuemax': 100
8176 .addClass( 'oo-ui-progressBarWidget' )
8177 .append( this.$bar
);
8182 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
8184 /* Static Properties */
8190 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
8195 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
8197 * @return {number|boolean} Progress percent
8199 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
8200 return this.progress
;
8204 * Set the percent of the process completed or `false` for an indeterminate process.
8206 * @param {number|boolean} progress Progress percent or `false` for indeterminate
8208 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
8209 this.progress
= progress
;
8211 if ( progress
!== false ) {
8212 this.$bar
.css( 'width', this.progress
+ '%' );
8213 this.$element
.attr( 'aria-valuenow', this.progress
);
8215 this.$bar
.css( 'width', '' );
8216 this.$element
.removeAttr( 'aria-valuenow' );
8218 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', progress
=== false );
8222 * InputWidget is the base class for all input widgets, which
8223 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
8224 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
8225 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
8227 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8231 * @extends OO.ui.Widget
8232 * @mixins OO.ui.mixin.FlaggedElement
8233 * @mixins OO.ui.mixin.TabIndexedElement
8234 * @mixins OO.ui.mixin.TitledElement
8235 * @mixins OO.ui.mixin.AccessKeyedElement
8238 * @param {Object} [config] Configuration options
8239 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
8240 * @cfg {string} [value=''] The value of the input.
8241 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
8242 * @cfg {string} [inputId] The value of the input’s HTML `id` attribute.
8243 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
8244 * before it is accepted.
8246 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
8247 // Configuration initialization
8248 config
= config
|| {};
8250 // Parent constructor
8251 OO
.ui
.InputWidget
.parent
.call( this, config
);
8254 // See #reusePreInfuseDOM about config.$input
8255 this.$input
= config
.$input
|| this.getInputElement( config
);
8257 this.inputFilter
= config
.inputFilter
;
8259 // Mixin constructors
8260 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
8261 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
8262 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
8263 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$input
} ) );
8266 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
8270 .addClass( 'oo-ui-inputWidget-input' )
8271 .attr( 'name', config
.name
)
8272 .prop( 'disabled', this.isDisabled() );
8274 .addClass( 'oo-ui-inputWidget' )
8275 .append( this.$input
);
8276 this.setValue( config
.value
);
8278 this.setDir( config
.dir
);
8280 if ( config
.inputId
!== undefined ) {
8281 this.setInputId( config
.inputId
);
8287 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
8288 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.FlaggedElement
);
8289 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TabIndexedElement
);
8290 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TitledElement
);
8291 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
8293 /* Static Methods */
8298 OO
.ui
.InputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
8299 config
= OO
.ui
.InputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
8300 // Reusing $input lets browsers preserve inputted values across page reloads (T114134)
8301 config
.$input
= $( node
).find( '.oo-ui-inputWidget-input' );
8308 OO
.ui
.InputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8309 var state
= OO
.ui
.InputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8310 if ( config
.$input
&& config
.$input
.length
) {
8311 state
.value
= config
.$input
.val();
8312 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
8313 state
.focus
= config
.$input
.is( ':focus' );
8323 * A change event is emitted when the value of the input changes.
8325 * @param {string} value
8331 * Get input element.
8333 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
8334 * different circumstances. The element must have a `value` property (like form elements).
8337 * @param {Object} config Configuration options
8338 * @return {jQuery} Input element
8340 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
8341 return $( '<input>' );
8345 * Handle potentially value-changing events.
8348 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
8350 OO
.ui
.InputWidget
.prototype.onEdit = function () {
8352 if ( !this.isDisabled() ) {
8353 // Allow the stack to clear so the value will be updated
8354 setTimeout( function () {
8355 widget
.setValue( widget
.$input
.val() );
8361 * Get the value of the input.
8363 * @return {string} Input value
8365 OO
.ui
.InputWidget
.prototype.getValue = function () {
8366 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
8367 // it, and we won't know unless they're kind enough to trigger a 'change' event.
8368 var value
= this.$input
.val();
8369 if ( this.value
!== value
) {
8370 this.setValue( value
);
8376 * Set the directionality of the input.
8378 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
8381 OO
.ui
.InputWidget
.prototype.setDir = function ( dir
) {
8382 this.$input
.prop( 'dir', dir
);
8387 * Set the value of the input.
8389 * @param {string} value New value
8393 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
8394 value
= this.cleanUpValue( value
);
8395 // Update the DOM if it has changed. Note that with cleanUpValue, it
8396 // is possible for the DOM value to change without this.value changing.
8397 if ( this.$input
.val() !== value
) {
8398 this.$input
.val( value
);
8400 if ( this.value
!== value
) {
8402 this.emit( 'change', this.value
);
8408 * Clean up incoming value.
8410 * Ensures value is a string, and converts undefined and null to empty string.
8413 * @param {string} value Original value
8414 * @return {string} Cleaned up value
8416 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
8417 if ( value
=== undefined || value
=== null ) {
8419 } else if ( this.inputFilter
) {
8420 return this.inputFilter( String( value
) );
8422 return String( value
);
8429 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
8430 OO
.ui
.InputWidget
.parent
.prototype.setDisabled
.call( this, state
);
8431 if ( this.$input
) {
8432 this.$input
.prop( 'disabled', this.isDisabled() );
8438 * Set the 'id' attribute of the `<input>` element.
8440 * @param {string} id
8443 OO
.ui
.InputWidget
.prototype.setInputId = function ( id
) {
8444 this.$input
.attr( 'id', id
);
8451 OO
.ui
.InputWidget
.prototype.restorePreInfuseState = function ( state
) {
8452 OO
.ui
.InputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
8453 if ( state
.value
!== undefined && state
.value
!== this.getValue() ) {
8454 this.setValue( state
.value
);
8456 if ( state
.focus
) {
8462 * Data widget intended for creating 'hidden'-type inputs.
8465 * @extends OO.ui.Widget
8468 * @param {Object} [config] Configuration options
8469 * @cfg {string} [value=''] The value of the input.
8470 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
8472 OO
.ui
.HiddenInputWidget
= function OoUiHiddenInputWidget( config
) {
8473 // Configuration initialization
8474 config
= $.extend( { value
: '', name
: '' }, config
);
8476 // Parent constructor
8477 OO
.ui
.HiddenInputWidget
.parent
.call( this, config
);
8480 this.$element
.attr( {
8482 value
: config
.value
,
8485 this.$element
.removeAttr( 'aria-disabled' );
8490 OO
.inheritClass( OO
.ui
.HiddenInputWidget
, OO
.ui
.Widget
);
8492 /* Static Properties */
8498 OO
.ui
.HiddenInputWidget
.static.tagName
= 'input';
8501 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
8502 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
8503 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
8504 * HTML `<button>` (the default) or an HTML `<input>` tags. See the
8505 * [OOjs UI documentation on MediaWiki] [1] for more information.
8508 * // A ButtonInputWidget rendered as an HTML button, the default.
8509 * var button = new OO.ui.ButtonInputWidget( {
8510 * label: 'Input button',
8514 * $( 'body' ).append( button.$element );
8516 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
8519 * @extends OO.ui.InputWidget
8520 * @mixins OO.ui.mixin.ButtonElement
8521 * @mixins OO.ui.mixin.IconElement
8522 * @mixins OO.ui.mixin.IndicatorElement
8523 * @mixins OO.ui.mixin.LabelElement
8524 * @mixins OO.ui.mixin.TitledElement
8527 * @param {Object} [config] Configuration options
8528 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
8529 * @cfg {boolean} [useInputTag=false] Use an `<input>` tag instead of a `<button>` tag, the default.
8530 * Widgets configured to be an `<input>` do not support {@link #icon icons} and {@link #indicator indicators},
8531 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
8532 * be set to `true` when there’s need to support IE 6 in a form with multiple buttons.
8534 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
8535 // Configuration initialization
8536 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
8538 // See InputWidget#reusePreInfuseDOM about config.$input
8539 if ( config
.$input
) {
8540 config
.$input
.empty();
8543 // Properties (must be set before parent constructor, which calls #setValue)
8544 this.useInputTag
= config
.useInputTag
;
8546 // Parent constructor
8547 OO
.ui
.ButtonInputWidget
.parent
.call( this, config
);
8549 // Mixin constructors
8550 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
8551 OO
.ui
.mixin
.IconElement
.call( this, config
);
8552 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
8553 OO
.ui
.mixin
.LabelElement
.call( this, config
);
8554 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
8557 if ( !config
.useInputTag
) {
8558 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
8560 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
8565 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
8566 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.ButtonElement
);
8567 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IconElement
);
8568 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
8569 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.LabelElement
);
8570 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.TitledElement
);
8572 /* Static Properties */
8578 OO
.ui
.ButtonInputWidget
.static.tagName
= 'span';
8586 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
8588 type
= [ 'button', 'submit', 'reset' ].indexOf( config
.type
) !== -1 ? config
.type
: 'button';
8589 return $( '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + type
+ '">' );
8595 * If #useInputTag is `true`, the label is set as the `value` of the `<input>` tag.
8597 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
8598 * text, or `null` for no label
8601 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
8602 if ( typeof label
=== 'function' ) {
8603 label
= OO
.ui
.resolveMsg( label
);
8606 if ( this.useInputTag
) {
8607 // Discard non-plaintext labels
8608 if ( typeof label
!== 'string' ) {
8612 this.$input
.val( label
);
8615 return OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.call( this, label
);
8619 * Set the value of the input.
8621 * This method is disabled for button inputs configured as {@link #useInputTag <input> tags}, as
8622 * they do not support {@link #value values}.
8624 * @param {string} value New value
8627 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
8628 if ( !this.useInputTag
) {
8629 OO
.ui
.ButtonInputWidget
.parent
.prototype.setValue
.call( this, value
);
8637 OO
.ui
.ButtonInputWidget
.prototype.getInputId = function () {
8638 // Disable generating `<label>` elements for buttons. One would very rarely need additional label
8639 // for a button, and it's already a big clickable target, and it causes unexpected rendering.
8644 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
8645 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
8646 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
8647 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
8649 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
8652 * // An example of selected, unselected, and disabled checkbox inputs
8653 * var checkbox1=new OO.ui.CheckboxInputWidget( {
8657 * var checkbox2=new OO.ui.CheckboxInputWidget( {
8660 * var checkbox3=new OO.ui.CheckboxInputWidget( {
8664 * // Create a fieldset layout with fields for each checkbox.
8665 * var fieldset = new OO.ui.FieldsetLayout( {
8666 * label: 'Checkboxes'
8668 * fieldset.addItems( [
8669 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
8670 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
8671 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
8673 * $( 'body' ).append( fieldset.$element );
8675 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8678 * @extends OO.ui.InputWidget
8681 * @param {Object} [config] Configuration options
8682 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
8684 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
8685 // Configuration initialization
8686 config
= config
|| {};
8688 // Parent constructor
8689 OO
.ui
.CheckboxInputWidget
.parent
.call( this, config
);
8693 .addClass( 'oo-ui-checkboxInputWidget' )
8694 // Required for pretty styling in WikimediaUI theme
8695 .append( $( '<span>' ) );
8696 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
8701 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
8703 /* Static Properties */
8709 OO
.ui
.CheckboxInputWidget
.static.tagName
= 'span';
8711 /* Static Methods */
8716 OO
.ui
.CheckboxInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8717 var state
= OO
.ui
.CheckboxInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8718 state
.checked
= config
.$input
.prop( 'checked' );
8728 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
8729 return $( '<input>' ).attr( 'type', 'checkbox' );
8735 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
8737 if ( !this.isDisabled() ) {
8738 // Allow the stack to clear so the value will be updated
8739 setTimeout( function () {
8740 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
8746 * Set selection state of this checkbox.
8748 * @param {boolean} state `true` for selected
8751 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
8753 if ( this.selected
!== state
) {
8754 this.selected
= state
;
8755 this.$input
.prop( 'checked', this.selected
);
8756 this.emit( 'change', this.selected
);
8762 * Check if this checkbox is selected.
8764 * @return {boolean} Checkbox is selected
8766 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
8767 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
8768 // it, and we won't know unless they're kind enough to trigger a 'change' event.
8769 var selected
= this.$input
.prop( 'checked' );
8770 if ( this.selected
!== selected
) {
8771 this.setSelected( selected
);
8773 return this.selected
;
8779 OO
.ui
.CheckboxInputWidget
.prototype.simulateLabelClick = function () {
8780 if ( !this.isDisabled() ) {
8781 this.$input
.click();
8789 OO
.ui
.CheckboxInputWidget
.prototype.restorePreInfuseState = function ( state
) {
8790 OO
.ui
.CheckboxInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
8791 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
8792 this.setSelected( state
.checked
);
8797 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
8798 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
8799 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
8800 * more information about input widgets.
8802 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
8803 * are no options. If no `value` configuration option is provided, the first option is selected.
8804 * If you need a state representing no value (no option being selected), use a DropdownWidget.
8806 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
8809 * // Example: A DropdownInputWidget with three options
8810 * var dropdownInput = new OO.ui.DropdownInputWidget( {
8812 * { data: 'a', label: 'First' },
8813 * { data: 'b', label: 'Second'},
8814 * { data: 'c', label: 'Third' }
8817 * $( 'body' ).append( dropdownInput.$element );
8819 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8822 * @extends OO.ui.InputWidget
8823 * @mixins OO.ui.mixin.TitledElement
8826 * @param {Object} [config] Configuration options
8827 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
8828 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
8830 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
8831 // Configuration initialization
8832 config
= config
|| {};
8834 // See InputWidget#reusePreInfuseDOM about config.$input
8835 if ( config
.$input
) {
8836 config
.$input
.addClass( 'oo-ui-element-hidden' );
8839 // Properties (must be done before parent constructor which calls #setDisabled)
8840 this.dropdownWidget
= new OO
.ui
.DropdownWidget( config
.dropdown
);
8842 // Parent constructor
8843 OO
.ui
.DropdownInputWidget
.parent
.call( this, config
);
8845 // Mixin constructors
8846 OO
.ui
.mixin
.TitledElement
.call( this, config
);
8849 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
8852 this.setOptions( config
.options
|| [] );
8853 // Set the value again, after we did setOptions(). The call from parent doesn't work because the
8854 // widget has no valid options when it happens.
8855 this.setValue( config
.value
);
8857 .addClass( 'oo-ui-dropdownInputWidget' )
8858 .append( this.dropdownWidget
.$element
);
8859 this.setTabIndexedElement( null );
8864 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
8865 OO
.mixinClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.mixin
.TitledElement
);
8873 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
8874 return $( '<input>' ).attr( 'type', 'hidden' );
8878 * Handles menu select events.
8881 * @param {OO.ui.MenuOptionWidget|null} item Selected menu item
8883 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
8884 this.setValue( item
? item
.getData() : '' );
8890 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
8892 value
= this.cleanUpValue( value
);
8893 // Only allow setting values that are actually present in the dropdown
8894 selected
= this.dropdownWidget
.getMenu().getItemFromData( value
) ||
8895 this.dropdownWidget
.getMenu().getFirstSelectableItem();
8896 this.dropdownWidget
.getMenu().selectItem( selected
);
8897 value
= selected
? selected
.getData() : '';
8898 OO
.ui
.DropdownInputWidget
.parent
.prototype.setValue
.call( this, value
);
8905 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
8906 this.dropdownWidget
.setDisabled( state
);
8907 OO
.ui
.DropdownInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
8912 * Set the options available for this input.
8914 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
8917 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
8919 value
= this.getValue(),
8922 // Rebuild the dropdown menu
8923 this.dropdownWidget
.getMenu()
8925 .addItems( options
.map( function ( opt
) {
8926 var optValue
= widget
.cleanUpValue( opt
.data
);
8928 if ( opt
.optgroup
=== undefined ) {
8929 return new OO
.ui
.MenuOptionWidget( {
8931 label
: opt
.label
!== undefined ? opt
.label
: optValue
8934 return new OO
.ui
.MenuSectionOptionWidget( {
8940 // Restore the previous value, or reset to something sensible
8941 if ( this.dropdownWidget
.getMenu().getItemFromData( value
) ) {
8942 // Previous value is still available, ensure consistency with the dropdown
8943 this.setValue( value
);
8945 // No longer valid, reset
8946 if ( options
.length
) {
8947 this.setValue( options
[ 0 ].data
);
8957 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
8958 this.dropdownWidget
.focus();
8965 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
8966 this.dropdownWidget
.blur();
8971 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
8972 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
8973 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
8974 * please see the [OOjs UI documentation on MediaWiki][1].
8976 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
8979 * // An example of selected, unselected, and disabled radio inputs
8980 * var radio1 = new OO.ui.RadioInputWidget( {
8984 * var radio2 = new OO.ui.RadioInputWidget( {
8987 * var radio3 = new OO.ui.RadioInputWidget( {
8991 * // Create a fieldset layout with fields for each radio button.
8992 * var fieldset = new OO.ui.FieldsetLayout( {
8993 * label: 'Radio inputs'
8995 * fieldset.addItems( [
8996 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
8997 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
8998 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
9000 * $( 'body' ).append( fieldset.$element );
9002 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9005 * @extends OO.ui.InputWidget
9008 * @param {Object} [config] Configuration options
9009 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
9011 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
9012 // Configuration initialization
9013 config
= config
|| {};
9015 // Parent constructor
9016 OO
.ui
.RadioInputWidget
.parent
.call( this, config
);
9020 .addClass( 'oo-ui-radioInputWidget' )
9021 // Required for pretty styling in WikimediaUI theme
9022 .append( $( '<span>' ) );
9023 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
9028 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
9030 /* Static Properties */
9036 OO
.ui
.RadioInputWidget
.static.tagName
= 'span';
9038 /* Static Methods */
9043 OO
.ui
.RadioInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9044 var state
= OO
.ui
.RadioInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9045 state
.checked
= config
.$input
.prop( 'checked' );
9055 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
9056 return $( '<input>' ).attr( 'type', 'radio' );
9062 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
9063 // RadioInputWidget doesn't track its state.
9067 * Set selection state of this radio button.
9069 * @param {boolean} state `true` for selected
9072 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
9073 // RadioInputWidget doesn't track its state.
9074 this.$input
.prop( 'checked', state
);
9079 * Check if this radio button is selected.
9081 * @return {boolean} Radio is selected
9083 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
9084 return this.$input
.prop( 'checked' );
9090 OO
.ui
.RadioInputWidget
.prototype.simulateLabelClick = function () {
9091 if ( !this.isDisabled() ) {
9092 this.$input
.click();
9100 OO
.ui
.RadioInputWidget
.prototype.restorePreInfuseState = function ( state
) {
9101 OO
.ui
.RadioInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
9102 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
9103 this.setSelected( state
.checked
);
9108 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
9109 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
9110 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
9111 * more information about input widgets.
9113 * This and OO.ui.DropdownInputWidget support the same configuration options.
9116 * // Example: A RadioSelectInputWidget with three options
9117 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
9119 * { data: 'a', label: 'First' },
9120 * { data: 'b', label: 'Second'},
9121 * { data: 'c', label: 'Third' }
9124 * $( 'body' ).append( radioSelectInput.$element );
9126 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9129 * @extends OO.ui.InputWidget
9132 * @param {Object} [config] Configuration options
9133 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
9135 OO
.ui
.RadioSelectInputWidget
= function OoUiRadioSelectInputWidget( config
) {
9136 // Configuration initialization
9137 config
= config
|| {};
9139 // Properties (must be done before parent constructor which calls #setDisabled)
9140 this.radioSelectWidget
= new OO
.ui
.RadioSelectWidget();
9142 // Parent constructor
9143 OO
.ui
.RadioSelectInputWidget
.parent
.call( this, config
);
9146 this.radioSelectWidget
.connect( this, { select
: 'onMenuSelect' } );
9149 this.setOptions( config
.options
|| [] );
9151 .addClass( 'oo-ui-radioSelectInputWidget' )
9152 .append( this.radioSelectWidget
.$element
);
9153 this.setTabIndexedElement( null );
9158 OO
.inheritClass( OO
.ui
.RadioSelectInputWidget
, OO
.ui
.InputWidget
);
9160 /* Static Methods */
9165 OO
.ui
.RadioSelectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9166 var state
= OO
.ui
.RadioSelectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9167 state
.value
= $( node
).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
9174 OO
.ui
.RadioSelectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
9175 config
= OO
.ui
.RadioSelectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
9176 // Cannot reuse the `<input type=radio>` set
9177 delete config
.$input
;
9187 OO
.ui
.RadioSelectInputWidget
.prototype.getInputElement = function () {
9188 return $( '<input>' ).attr( 'type', 'hidden' );
9192 * Handles menu select events.
9195 * @param {OO.ui.RadioOptionWidget} item Selected menu item
9197 OO
.ui
.RadioSelectInputWidget
.prototype.onMenuSelect = function ( item
) {
9198 this.setValue( item
.getData() );
9204 OO
.ui
.RadioSelectInputWidget
.prototype.setValue = function ( value
) {
9205 value
= this.cleanUpValue( value
);
9206 this.radioSelectWidget
.selectItemByData( value
);
9207 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setValue
.call( this, value
);
9214 OO
.ui
.RadioSelectInputWidget
.prototype.setDisabled = function ( state
) {
9215 this.radioSelectWidget
.setDisabled( state
);
9216 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
9221 * Set the options available for this input.
9223 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9226 OO
.ui
.RadioSelectInputWidget
.prototype.setOptions = function ( options
) {
9228 value
= this.getValue(),
9231 // Rebuild the radioSelect menu
9232 this.radioSelectWidget
9234 .addItems( options
.map( function ( opt
) {
9235 var optValue
= widget
.cleanUpValue( opt
.data
);
9236 return new OO
.ui
.RadioOptionWidget( {
9238 label
: opt
.label
!== undefined ? opt
.label
: optValue
9242 // Restore the previous value, or reset to something sensible
9243 if ( this.radioSelectWidget
.getItemFromData( value
) ) {
9244 // Previous value is still available, ensure consistency with the radioSelect
9245 this.setValue( value
);
9247 // No longer valid, reset
9248 if ( options
.length
) {
9249 this.setValue( options
[ 0 ].data
);
9259 OO
.ui
.RadioSelectInputWidget
.prototype.focus = function () {
9260 this.radioSelectWidget
.focus();
9267 OO
.ui
.RadioSelectInputWidget
.prototype.blur = function () {
9268 this.radioSelectWidget
.blur();
9273 * CheckboxMultiselectInputWidget is a
9274 * {@link OO.ui.CheckboxMultiselectWidget CheckboxMultiselectWidget} intended to be used within a
9275 * HTML form, such as a OO.ui.FormLayout. The selected values are synchronized with the value of
9276 * HTML `<input type=checkbox>` tags. Please see the [OOjs UI documentation on MediaWiki][1] for
9277 * more information about input widgets.
9280 * // Example: A CheckboxMultiselectInputWidget with three options
9281 * var multiselectInput = new OO.ui.CheckboxMultiselectInputWidget( {
9283 * { data: 'a', label: 'First' },
9284 * { data: 'b', label: 'Second'},
9285 * { data: 'c', label: 'Third' }
9288 * $( 'body' ).append( multiselectInput.$element );
9290 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9293 * @extends OO.ui.InputWidget
9296 * @param {Object} [config] Configuration options
9297 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: …, disabled: … }`
9299 OO
.ui
.CheckboxMultiselectInputWidget
= function OoUiCheckboxMultiselectInputWidget( config
) {
9300 // Configuration initialization
9301 config
= config
|| {};
9303 // Properties (must be done before parent constructor which calls #setDisabled)
9304 this.checkboxMultiselectWidget
= new OO
.ui
.CheckboxMultiselectWidget();
9306 // Parent constructor
9307 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.call( this, config
);
9310 this.inputName
= config
.name
;
9314 .addClass( 'oo-ui-checkboxMultiselectInputWidget' )
9315 .append( this.checkboxMultiselectWidget
.$element
);
9316 // We don't use this.$input, but rather the CheckboxInputWidgets inside each option
9317 this.$input
.detach();
9318 this.setOptions( config
.options
|| [] );
9319 // Have to repeat this from parent, as we need options to be set up for this to make sense
9320 this.setValue( config
.value
);
9325 OO
.inheritClass( OO
.ui
.CheckboxMultiselectInputWidget
, OO
.ui
.InputWidget
);
9327 /* Static Methods */
9332 OO
.ui
.CheckboxMultiselectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9333 var state
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9334 state
.value
= $( node
).find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
9335 .toArray().map( function ( el
) { return el
.value
; } );
9342 OO
.ui
.CheckboxMultiselectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
9343 config
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
9344 // Cannot reuse the `<input type=checkbox>` set
9345 delete config
.$input
;
9355 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getInputElement = function () {
9357 return $( '<unused>' );
9363 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getValue = function () {
9364 var value
= this.$element
.find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
9365 .toArray().map( function ( el
) { return el
.value
; } );
9366 if ( this.value
!== value
) {
9367 this.setValue( value
);
9375 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setValue = function ( value
) {
9376 value
= this.cleanUpValue( value
);
9377 this.checkboxMultiselectWidget
.selectItemsByData( value
);
9378 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setValue
.call( this, value
);
9383 * Clean up incoming value.
9385 * @param {string[]} value Original value
9386 * @return {string[]} Cleaned up value
9388 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.cleanUpValue = function ( value
) {
9391 if ( !Array
.isArray( value
) ) {
9394 for ( i
= 0; i
< value
.length
; i
++ ) {
9396 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
.call( this, value
[ i
] );
9397 // Remove options that we don't have here
9398 if ( !this.checkboxMultiselectWidget
.getItemFromData( singleValue
) ) {
9401 cleanValue
.push( singleValue
);
9409 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setDisabled = function ( state
) {
9410 this.checkboxMultiselectWidget
.setDisabled( state
);
9411 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
9416 * Set the options available for this input.
9418 * @param {Object[]} options Array of menu options in the format `{ data: …, label: …, disabled: … }`
9421 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setOptions = function ( options
) {
9424 // Rebuild the checkboxMultiselectWidget menu
9425 this.checkboxMultiselectWidget
9427 .addItems( options
.map( function ( opt
) {
9428 var optValue
, item
, optDisabled
;
9430 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
.call( widget
, opt
.data
);
9431 optDisabled
= opt
.disabled
!== undefined ? opt
.disabled
: false;
9432 item
= new OO
.ui
.CheckboxMultioptionWidget( {
9434 label
: opt
.label
!== undefined ? opt
.label
: optValue
,
9435 disabled
: optDisabled
9437 // Set the 'name' and 'value' for form submission
9438 item
.checkbox
.$input
.attr( 'name', widget
.inputName
);
9439 item
.checkbox
.setValue( optValue
);
9443 // Re-set the value, checking the checkboxes as needed.
9444 // This will also get rid of any stale options that we just removed.
9445 this.setValue( this.getValue() );
9453 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.focus = function () {
9454 this.checkboxMultiselectWidget
.focus();
9459 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
9460 * size of the field as well as its presentation. In addition, these widgets can be configured
9461 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
9462 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
9463 * which modifies incoming values rather than validating them.
9464 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9466 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9469 * // Example of a text input widget
9470 * var textInput = new OO.ui.TextInputWidget( {
9471 * value: 'Text input'
9473 * $( 'body' ).append( textInput.$element );
9475 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9478 * @extends OO.ui.InputWidget
9479 * @mixins OO.ui.mixin.IconElement
9480 * @mixins OO.ui.mixin.IndicatorElement
9481 * @mixins OO.ui.mixin.PendingElement
9482 * @mixins OO.ui.mixin.LabelElement
9485 * @param {Object} [config] Configuration options
9486 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password'
9487 * 'email', 'url' or 'number'.
9488 * @cfg {string} [placeholder] Placeholder text
9489 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
9490 * instruct the browser to focus this widget.
9491 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
9492 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
9493 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
9494 * the value or placeholder text: `'before'` or `'after'`
9495 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
9496 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
9497 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
9498 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
9499 * (the value must contain only numbers); when RegExp, a regular expression that must match the
9500 * value for it to be considered valid; when Function, a function receiving the value as parameter
9501 * that must return true, or promise resolving to true, for it to be considered valid.
9503 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
9504 // Configuration initialization
9505 config
= $.extend( {
9507 labelPosition
: 'after'
9510 if ( config
.multiline
) {
9511 OO
.ui
.warnDeprecation( 'TextInputWidget: config.multiline is deprecated. Use the MultilineTextInputWidget instead. See T130434 for details.' );
9512 return new OO
.ui
.MultilineTextInputWidget( config
);
9515 // Parent constructor
9516 OO
.ui
.TextInputWidget
.parent
.call( this, config
);
9518 // Mixin constructors
9519 OO
.ui
.mixin
.IconElement
.call( this, config
);
9520 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
9521 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$input
} ) );
9522 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9525 this.type
= this.getSaneType( config
);
9526 this.readOnly
= false;
9527 this.required
= false;
9528 this.validate
= null;
9529 this.styleHeight
= null;
9530 this.scrollWidth
= null;
9532 this.setValidation( config
.validate
);
9533 this.setLabelPosition( config
.labelPosition
);
9537 keypress
: this.onKeyPress
.bind( this ),
9538 blur
: this.onBlur
.bind( this ),
9539 focus
: this.onFocus
.bind( this )
9541 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
9542 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
9543 this.on( 'labelChange', this.updatePosition
.bind( this ) );
9544 this.on( 'change', OO
.ui
.debounce( this.onDebouncedChange
.bind( this ), 250 ) );
9548 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type
)
9549 .append( this.$icon
, this.$indicator
);
9550 this.setReadOnly( !!config
.readOnly
);
9551 this.setRequired( !!config
.required
);
9552 if ( config
.placeholder
!== undefined ) {
9553 this.$input
.attr( 'placeholder', config
.placeholder
);
9555 if ( config
.maxLength
!== undefined ) {
9556 this.$input
.attr( 'maxlength', config
.maxLength
);
9558 if ( config
.autofocus
) {
9559 this.$input
.attr( 'autofocus', 'autofocus' );
9561 if ( config
.autocomplete
=== false ) {
9562 this.$input
.attr( 'autocomplete', 'off' );
9563 // Turning off autocompletion also disables "form caching" when the user navigates to a
9564 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
9566 beforeunload: function () {
9567 this.$input
.removeAttr( 'autocomplete' );
9569 pageshow: function () {
9570 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
9571 // whole page... it shouldn't hurt, though.
9572 this.$input
.attr( 'autocomplete', 'off' );
9577 this.isWaitingToBeAttached
= true;
9578 this.installParentChangeDetector();
9584 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
9585 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IconElement
);
9586 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
9587 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.PendingElement
);
9588 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.LabelElement
);
9590 /* Static Properties */
9592 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
9597 /* Static Methods */
9602 OO
.ui
.TextInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9603 var state
= OO
.ui
.TextInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9610 * An `enter` event is emitted when the user presses 'enter' inside the text box.
9618 * Handle icon mouse down events.
9621 * @param {jQuery.Event} e Mouse down event
9623 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
9624 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
9631 * Handle indicator mouse down events.
9634 * @param {jQuery.Event} e Mouse down event
9636 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
9637 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
9644 * Handle key press events.
9647 * @param {jQuery.Event} e Key press event
9648 * @fires enter If enter key is pressed
9650 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
9651 if ( e
.which
=== OO
.ui
.Keys
.ENTER
) {
9652 this.emit( 'enter', e
);
9657 * Handle blur events.
9660 * @param {jQuery.Event} e Blur event
9662 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
9663 this.setValidityFlag();
9667 * Handle focus events.
9670 * @param {jQuery.Event} e Focus event
9672 OO
.ui
.TextInputWidget
.prototype.onFocus = function () {
9673 if ( this.isWaitingToBeAttached
) {
9674 // If we've received focus, then we must be attached to the document, and if
9675 // isWaitingToBeAttached is still true, that means the handler never fired. Fire it now.
9676 this.onElementAttach();
9678 this.setValidityFlag( true );
9682 * Handle element attach events.
9685 * @param {jQuery.Event} e Element attach event
9687 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
9688 this.isWaitingToBeAttached
= false;
9689 // Any previously calculated size is now probably invalid if we reattached elsewhere
9690 this.valCache
= null;
9691 this.positionLabel();
9695 * Handle debounced change events.
9697 * @param {string} value
9700 OO
.ui
.TextInputWidget
.prototype.onDebouncedChange = function () {
9701 this.setValidityFlag();
9705 * Check if the input is {@link #readOnly read-only}.
9709 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
9710 return this.readOnly
;
9714 * Set the {@link #readOnly read-only} state of the input.
9716 * @param {boolean} state Make input read-only
9719 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
9720 this.readOnly
= !!state
;
9721 this.$input
.prop( 'readOnly', this.readOnly
);
9726 * Check if the input is {@link #required required}.
9730 OO
.ui
.TextInputWidget
.prototype.isRequired = function () {
9731 return this.required
;
9735 * Set the {@link #required required} state of the input.
9737 * @param {boolean} state Make input required
9740 OO
.ui
.TextInputWidget
.prototype.setRequired = function ( state
) {
9741 this.required
= !!state
;
9742 if ( this.required
) {
9744 .prop( 'required', true )
9745 .attr( 'aria-required', 'true' );
9746 if ( this.getIndicator() === null ) {
9747 this.setIndicator( 'required' );
9751 .prop( 'required', false )
9752 .removeAttr( 'aria-required' );
9753 if ( this.getIndicator() === 'required' ) {
9754 this.setIndicator( null );
9761 * Support function for making #onElementAttach work across browsers.
9763 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
9764 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
9766 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
9767 * first time that the element gets attached to the documented.
9769 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
9770 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
9771 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
9774 if ( MutationObserver
) {
9775 // The new way. If only it wasn't so ugly.
9777 if ( this.isElementAttached() ) {
9778 // Widget is attached already, do nothing. This breaks the functionality of this function when
9779 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
9780 // would require observation of the whole document, which would hurt performance of other,
9781 // more important code.
9785 // Find topmost node in the tree
9786 topmostNode
= this.$element
[ 0 ];
9787 while ( topmostNode
.parentNode
) {
9788 topmostNode
= topmostNode
.parentNode
;
9791 // We have no way to detect the $element being attached somewhere without observing the entire
9792 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
9793 // parent node of $element, and instead detect when $element is removed from it (and thus
9794 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
9795 // doesn't get attached, we end up back here and create the parent.
9797 mutationObserver
= new MutationObserver( function ( mutations
) {
9798 var i
, j
, removedNodes
;
9799 for ( i
= 0; i
< mutations
.length
; i
++ ) {
9800 removedNodes
= mutations
[ i
].removedNodes
;
9801 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
9802 if ( removedNodes
[ j
] === topmostNode
) {
9803 setTimeout( onRemove
, 0 );
9810 onRemove = function () {
9811 // If the node was attached somewhere else, report it
9812 if ( widget
.isElementAttached() ) {
9813 widget
.onElementAttach();
9815 mutationObserver
.disconnect();
9816 widget
.installParentChangeDetector();
9819 // Create a fake parent and observe it
9820 fakeParentNode
= $( '<div>' ).append( topmostNode
)[ 0 ];
9821 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
9823 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
9824 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
9825 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
9833 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
9834 if ( this.getSaneType( config
) === 'number' ) {
9835 return $( '<input>' )
9836 .attr( 'step', 'any' )
9837 .attr( 'type', 'number' );
9839 return $( '<input>' ).attr( 'type', this.getSaneType( config
) );
9844 * Get sanitized value for 'type' for given config.
9846 * @param {Object} config Configuration options
9847 * @return {string|null}
9850 OO
.ui
.TextInputWidget
.prototype.getSaneType = function ( config
) {
9851 var allowedTypes
= [
9858 return allowedTypes
.indexOf( config
.type
) !== -1 ? config
.type
: 'text';
9862 * Focus the input and select a specified range within the text.
9864 * @param {number} from Select from offset
9865 * @param {number} [to] Select to offset, defaults to from
9868 OO
.ui
.TextInputWidget
.prototype.selectRange = function ( from, to
) {
9869 var isBackwards
, start
, end
,
9870 input
= this.$input
[ 0 ];
9874 isBackwards
= to
< from;
9875 start
= isBackwards
? to
: from;
9876 end
= isBackwards
? from : to
;
9881 input
.setSelectionRange( start
, end
, isBackwards
? 'backward' : 'forward' );
9883 // IE throws an exception if you call setSelectionRange on a unattached DOM node.
9884 // Rather than expensively check if the input is attached every time, just check
9885 // if it was the cause of an error being thrown. If not, rethrow the error.
9886 if ( this.getElementDocument().body
.contains( input
) ) {
9894 * Get an object describing the current selection range in a directional manner
9896 * @return {Object} Object containing 'from' and 'to' offsets
9898 OO
.ui
.TextInputWidget
.prototype.getRange = function () {
9899 var input
= this.$input
[ 0 ],
9900 start
= input
.selectionStart
,
9901 end
= input
.selectionEnd
,
9902 isBackwards
= input
.selectionDirection
=== 'backward';
9905 from: isBackwards
? end
: start
,
9906 to
: isBackwards
? start
: end
9911 * Get the length of the text input value.
9913 * This could differ from the length of #getValue if the
9914 * value gets filtered
9916 * @return {number} Input length
9918 OO
.ui
.TextInputWidget
.prototype.getInputLength = function () {
9919 return this.$input
[ 0 ].value
.length
;
9923 * Focus the input and select the entire text.
9927 OO
.ui
.TextInputWidget
.prototype.select = function () {
9928 return this.selectRange( 0, this.getInputLength() );
9932 * Focus the input and move the cursor to the start.
9936 OO
.ui
.TextInputWidget
.prototype.moveCursorToStart = function () {
9937 return this.selectRange( 0 );
9941 * Focus the input and move the cursor to the end.
9945 OO
.ui
.TextInputWidget
.prototype.moveCursorToEnd = function () {
9946 return this.selectRange( this.getInputLength() );
9950 * Insert new content into the input.
9952 * @param {string} content Content to be inserted
9955 OO
.ui
.TextInputWidget
.prototype.insertContent = function ( content
) {
9957 range
= this.getRange(),
9958 value
= this.getValue();
9960 start
= Math
.min( range
.from, range
.to
);
9961 end
= Math
.max( range
.from, range
.to
);
9963 this.setValue( value
.slice( 0, start
) + content
+ value
.slice( end
) );
9964 this.selectRange( start
+ content
.length
);
9969 * Insert new content either side of a selection.
9971 * @param {string} pre Content to be inserted before the selection
9972 * @param {string} post Content to be inserted after the selection
9975 OO
.ui
.TextInputWidget
.prototype.encapsulateContent = function ( pre
, post
) {
9977 range
= this.getRange(),
9978 offset
= pre
.length
;
9980 start
= Math
.min( range
.from, range
.to
);
9981 end
= Math
.max( range
.from, range
.to
);
9983 this.selectRange( start
).insertContent( pre
);
9984 this.selectRange( offset
+ end
).insertContent( post
);
9986 this.selectRange( offset
+ start
, offset
+ end
);
9991 * Set the validation pattern.
9993 * The validation pattern is either a regular expression, a function, or the symbolic name of a
9994 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
9995 * value must contain only numbers).
9997 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
9998 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
10000 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
10001 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
10002 this.validate
= validate
;
10004 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
10009 * Sets the 'invalid' flag appropriately.
10011 * @param {boolean} [isValid] Optionally override validation result
10013 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
10015 setFlag = function ( valid
) {
10017 widget
.$input
.attr( 'aria-invalid', 'true' );
10019 widget
.$input
.removeAttr( 'aria-invalid' );
10021 widget
.setFlags( { invalid
: !valid
} );
10024 if ( isValid
!== undefined ) {
10025 setFlag( isValid
);
10027 this.getValidity().then( function () {
10036 * Get the validity of current value.
10038 * This method returns a promise that resolves if the value is valid and rejects if
10039 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
10041 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
10043 OO
.ui
.TextInputWidget
.prototype.getValidity = function () {
10046 function rejectOrResolve( valid
) {
10048 return $.Deferred().resolve().promise();
10050 return $.Deferred().reject().promise();
10054 // Check browser validity and reject if it is invalid
10056 this.$input
[ 0 ].checkValidity
!== undefined &&
10057 this.$input
[ 0 ].checkValidity() === false
10059 return rejectOrResolve( false );
10062 // Run our checks if the browser thinks the field is valid
10063 if ( this.validate
instanceof Function
) {
10064 result
= this.validate( this.getValue() );
10065 if ( result
&& $.isFunction( result
.promise
) ) {
10066 return result
.promise().then( function ( valid
) {
10067 return rejectOrResolve( valid
);
10070 return rejectOrResolve( result
);
10073 return rejectOrResolve( this.getValue().match( this.validate
) );
10078 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
10080 * @param {string} labelPosition Label position, 'before' or 'after'
10083 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
10084 this.labelPosition
= labelPosition
;
10085 if ( this.label
) {
10086 // If there is no label and we only change the position, #updatePosition is a no-op,
10087 // but it takes really a lot of work to do nothing.
10088 this.updatePosition();
10094 * Update the position of the inline label.
10096 * This method is called by #setLabelPosition, and can also be called on its own if
10097 * something causes the label to be mispositioned.
10101 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
10102 var after
= this.labelPosition
=== 'after';
10105 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
10106 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
10108 this.valCache
= null;
10109 this.scrollWidth
= null;
10110 this.positionLabel();
10116 * Position the label by setting the correct padding on the input.
10121 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
10122 var after
, rtl
, property
;
10124 if ( this.isWaitingToBeAttached
) {
10125 // #onElementAttach will be called soon, which calls this method
10129 // Clear old values
10131 // Clear old values if present
10133 'padding-right': '',
10137 if ( this.label
) {
10138 this.$element
.append( this.$label
);
10140 this.$label
.detach();
10144 after
= this.labelPosition
=== 'after';
10145 rtl
= this.$element
.css( 'direction' ) === 'rtl';
10146 property
= after
=== rtl
? 'padding-left' : 'padding-right';
10148 this.$input
.css( property
, this.$label
.outerWidth( true ) + ( after
? this.scrollWidth
: 0 ) );
10156 OO
.ui
.TextInputWidget
.prototype.restorePreInfuseState = function ( state
) {
10157 OO
.ui
.TextInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
10158 if ( state
.scrollTop
!== undefined ) {
10159 this.$input
.scrollTop( state
.scrollTop
);
10165 * @extends OO.ui.TextInputWidget
10168 * @param {Object} [config] Configuration options
10170 OO
.ui
.SearchInputWidget
= function OoUiSearchInputWidget( config
) {
10171 config
= $.extend( {
10175 // Set type to text so that TextInputWidget doesn't
10176 // get stuck in an infinite loop.
10177 config
.type
= 'text';
10179 // Parent constructor
10180 OO
.ui
.SearchInputWidget
.parent
.call( this, config
);
10183 this.connect( this, {
10188 this.$element
.addClass( 'oo-ui-textInputWidget-type-search' );
10189 this.updateSearchIndicator();
10190 this.connect( this, {
10191 disable
: 'onDisable'
10197 OO
.inheritClass( OO
.ui
.SearchInputWidget
, OO
.ui
.TextInputWidget
);
10205 OO
.ui
.SearchInputWidget
.prototype.getInputElement = function () {
10206 return $( '<input>' ).attr( 'type', 'search' );
10212 OO
.ui
.SearchInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
10213 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
10214 // Clear the text field
10215 this.setValue( '' );
10222 * Update the 'clear' indicator displayed on type: 'search' text
10223 * fields, hiding it when the field is already empty or when it's not
10226 OO
.ui
.SearchInputWidget
.prototype.updateSearchIndicator = function () {
10227 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
10228 this.setIndicator( null );
10230 this.setIndicator( 'clear' );
10235 * Handle change events.
10239 OO
.ui
.SearchInputWidget
.prototype.onChange = function () {
10240 this.updateSearchIndicator();
10244 * Handle disable events.
10246 * @param {boolean} disabled Element is disabled
10249 OO
.ui
.SearchInputWidget
.prototype.onDisable = function () {
10250 this.updateSearchIndicator();
10256 OO
.ui
.SearchInputWidget
.prototype.setReadOnly = function ( state
) {
10257 OO
.ui
.SearchInputWidget
.parent
.prototype.setReadOnly
.call( this, state
);
10258 this.updateSearchIndicator();
10264 * @extends OO.ui.TextInputWidget
10267 * @param {Object} [config] Configuration options
10268 * @cfg {number} [rows] Number of visible lines in textarea. If used with `autosize`,
10269 * specifies minimum number of rows to display.
10270 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
10271 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
10272 * Use the #maxRows config to specify a maximum number of displayed rows.
10273 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
10274 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
10276 OO
.ui
.MultilineTextInputWidget
= function OoUiMultilineTextInputWidget( config
) {
10277 config
= $.extend( {
10280 config
.multiline
= false;
10281 // Parent constructor
10282 OO
.ui
.MultilineTextInputWidget
.parent
.call( this, config
);
10285 this.multiline
= true;
10286 this.autosize
= !!config
.autosize
;
10287 this.minRows
= config
.rows
!== undefined ? config
.rows
: '';
10288 this.maxRows
= config
.maxRows
|| Math
.max( 2 * ( this.minRows
|| 0 ), 10 );
10290 // Clone for resizing
10291 if ( this.autosize
) {
10292 this.$clone
= this.$input
10294 .insertAfter( this.$input
)
10295 .attr( 'aria-hidden', 'true' )
10296 .addClass( 'oo-ui-element-hidden' );
10300 this.connect( this, {
10305 if ( this.multiline
&& config
.rows
) {
10306 this.$input
.attr( 'rows', config
.rows
);
10308 if ( this.autosize
) {
10309 this.isWaitingToBeAttached
= true;
10310 this.installParentChangeDetector();
10316 OO
.inheritClass( OO
.ui
.MultilineTextInputWidget
, OO
.ui
.TextInputWidget
);
10318 /* Static Methods */
10323 OO
.ui
.MultilineTextInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
10324 var state
= OO
.ui
.MultilineTextInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
10325 state
.scrollTop
= config
.$input
.scrollTop();
10334 OO
.ui
.MultilineTextInputWidget
.prototype.onElementAttach = function () {
10335 OO
.ui
.MultilineTextInputWidget
.parent
.prototype.onElementAttach
.call( this );
10340 * Handle change events.
10344 OO
.ui
.MultilineTextInputWidget
.prototype.onChange = function () {
10351 OO
.ui
.MultilineTextInputWidget
.prototype.updatePosition = function () {
10352 OO
.ui
.MultilineTextInputWidget
.parent
.prototype.updatePosition
.call( this );
10357 * Override TextInputWidget so it doesn't emit the 'enter' event.
10360 * @param {jQuery.Event} e Key press event
10362 OO
.ui
.MultilineTextInputWidget
.prototype.onKeyPress = function () {
10367 * Automatically adjust the size of the text input.
10369 * This only affects multiline inputs that are {@link #autosize autosized}.
10374 OO
.ui
.MultilineTextInputWidget
.prototype.adjustSize = function () {
10375 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
,
10376 idealHeight
, newHeight
, scrollWidth
, property
;
10378 if ( this.$input
.val() !== this.valCache
) {
10379 if ( this.autosize
) {
10381 .val( this.$input
.val() )
10382 .attr( 'rows', this.minRows
)
10383 // Set inline height property to 0 to measure scroll height
10384 .css( 'height', 0 );
10386 this.$clone
.removeClass( 'oo-ui-element-hidden' );
10388 this.valCache
= this.$input
.val();
10390 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
10392 // Remove inline height property to measure natural heights
10393 this.$clone
.css( 'height', '' );
10394 innerHeight
= this.$clone
.innerHeight();
10395 outerHeight
= this.$clone
.outerHeight();
10397 // Measure max rows height
10399 .attr( 'rows', this.maxRows
)
10400 .css( 'height', 'auto' )
10402 maxInnerHeight
= this.$clone
.innerHeight();
10404 // Difference between reported innerHeight and scrollHeight with no scrollbars present.
10405 // This is sometimes non-zero on Blink-based browsers, depending on zoom level.
10406 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
10407 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
10409 this.$clone
.addClass( 'oo-ui-element-hidden' );
10411 // Only apply inline height when expansion beyond natural height is needed
10412 // Use the difference between the inner and outer height as a buffer
10413 newHeight
= idealHeight
> innerHeight
? idealHeight
+ ( outerHeight
- innerHeight
) : '';
10414 if ( newHeight
!== this.styleHeight
) {
10415 this.$input
.css( 'height', newHeight
);
10416 this.styleHeight
= newHeight
;
10417 this.emit( 'resize' );
10420 scrollWidth
= this.$input
[ 0 ].offsetWidth
- this.$input
[ 0 ].clientWidth
;
10421 if ( scrollWidth
!== this.scrollWidth
) {
10422 property
= this.$element
.css( 'direction' ) === 'rtl' ? 'left' : 'right';
10424 this.$label
.css( { right
: '', left
: '' } );
10425 this.$indicator
.css( { right
: '', left
: '' } );
10427 if ( scrollWidth
) {
10428 this.$indicator
.css( property
, scrollWidth
);
10429 if ( this.labelPosition
=== 'after' ) {
10430 this.$label
.css( property
, scrollWidth
);
10434 this.scrollWidth
= scrollWidth
;
10435 this.positionLabel();
10445 OO
.ui
.MultilineTextInputWidget
.prototype.getInputElement = function () {
10446 return $( '<textarea>' );
10450 * Check if the input supports multiple lines.
10452 * @return {boolean}
10454 OO
.ui
.MultilineTextInputWidget
.prototype.isMultiline = function () {
10455 return !!this.multiline
;
10459 * Check if the input automatically adjusts its size.
10461 * @return {boolean}
10463 OO
.ui
.MultilineTextInputWidget
.prototype.isAutosizing = function () {
10464 return !!this.autosize
;
10468 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
10469 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
10470 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
10472 * - by typing a value in the text input field. If the value exactly matches the value of a menu
10473 * option, that option will appear to be selected.
10474 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
10477 * After the user chooses an option, its `data` will be used as a new value for the widget.
10478 * A `label` also can be specified for each option: if given, it will be shown instead of the
10479 * `data` in the dropdown menu.
10481 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
10483 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
10486 * // Example: A ComboBoxInputWidget.
10487 * var comboBox = new OO.ui.ComboBoxInputWidget( {
10488 * value: 'Option 1',
10490 * { data: 'Option 1' },
10491 * { data: 'Option 2' },
10492 * { data: 'Option 3' }
10495 * $( 'body' ).append( comboBox.$element );
10498 * // Example: A ComboBoxInputWidget with additional option labels.
10499 * var comboBox = new OO.ui.ComboBoxInputWidget( {
10500 * value: 'Option 1',
10503 * data: 'Option 1',
10504 * label: 'Option One'
10507 * data: 'Option 2',
10508 * label: 'Option Two'
10511 * data: 'Option 3',
10512 * label: 'Option Three'
10516 * $( 'body' ).append( comboBox.$element );
10518 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
10521 * @extends OO.ui.TextInputWidget
10524 * @param {Object} [config] Configuration options
10525 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
10526 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
10527 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
10528 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
10529 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
10530 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
10532 OO
.ui
.ComboBoxInputWidget
= function OoUiComboBoxInputWidget( config
) {
10533 // Configuration initialization
10534 config
= $.extend( {
10535 autocomplete
: false
10538 // ComboBoxInputWidget shouldn't support `multiline`
10539 config
.multiline
= false;
10541 // See InputWidget#reusePreInfuseDOM about `config.$input`
10542 if ( config
.$input
) {
10543 config
.$input
.removeAttr( 'list' );
10546 // Parent constructor
10547 OO
.ui
.ComboBoxInputWidget
.parent
.call( this, config
);
10550 this.$overlay
= config
.$overlay
|| this.$element
;
10551 this.dropdownButton
= new OO
.ui
.ButtonWidget( {
10552 classes
: [ 'oo-ui-comboBoxInputWidget-dropdownButton' ],
10554 disabled
: this.disabled
10556 this.menu
= new OO
.ui
.MenuSelectWidget( $.extend(
10560 $floatableContainer
: this.$element
,
10561 disabled
: this.isDisabled()
10567 this.connect( this, {
10568 change
: 'onInputChange',
10569 enter
: 'onInputEnter'
10571 this.dropdownButton
.connect( this, {
10572 click
: 'onDropdownButtonClick'
10574 this.menu
.connect( this, {
10575 choose
: 'onMenuChoose',
10576 add
: 'onMenuItemsChange',
10577 remove
: 'onMenuItemsChange'
10581 this.$input
.attr( {
10583 'aria-owns': this.menu
.getElementId(),
10584 'aria-autocomplete': 'list'
10586 // Do not override options set via config.menu.items
10587 if ( config
.options
!== undefined ) {
10588 this.setOptions( config
.options
);
10590 this.$field
= $( '<div>' )
10591 .addClass( 'oo-ui-comboBoxInputWidget-field' )
10592 .append( this.$input
, this.dropdownButton
.$element
);
10594 .addClass( 'oo-ui-comboBoxInputWidget' )
10595 .append( this.$field
);
10596 this.$overlay
.append( this.menu
.$element
);
10597 this.onMenuItemsChange();
10602 OO
.inheritClass( OO
.ui
.ComboBoxInputWidget
, OO
.ui
.TextInputWidget
);
10607 * Get the combobox's menu.
10609 * @return {OO.ui.MenuSelectWidget} Menu widget
10611 OO
.ui
.ComboBoxInputWidget
.prototype.getMenu = function () {
10616 * Get the combobox's text input widget.
10618 * @return {OO.ui.TextInputWidget} Text input widget
10620 OO
.ui
.ComboBoxInputWidget
.prototype.getInput = function () {
10625 * Handle input change events.
10628 * @param {string} value New value
10630 OO
.ui
.ComboBoxInputWidget
.prototype.onInputChange = function ( value
) {
10631 var match
= this.menu
.getItemFromData( value
);
10633 this.menu
.selectItem( match
);
10634 if ( this.menu
.getHighlightedItem() ) {
10635 this.menu
.highlightItem( match
);
10638 if ( !this.isDisabled() ) {
10639 this.menu
.toggle( true );
10644 * Handle input enter events.
10648 OO
.ui
.ComboBoxInputWidget
.prototype.onInputEnter = function () {
10649 if ( !this.isDisabled() ) {
10650 this.menu
.toggle( false );
10655 * Handle button click events.
10659 OO
.ui
.ComboBoxInputWidget
.prototype.onDropdownButtonClick = function () {
10660 this.menu
.toggle();
10665 * Handle menu choose events.
10668 * @param {OO.ui.OptionWidget} item Chosen item
10670 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuChoose = function ( item
) {
10671 this.setValue( item
.getData() );
10675 * Handle menu item change events.
10679 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuItemsChange = function () {
10680 var match
= this.menu
.getItemFromData( this.getValue() );
10681 this.menu
.selectItem( match
);
10682 if ( this.menu
.getHighlightedItem() ) {
10683 this.menu
.highlightItem( match
);
10685 this.$element
.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu
.isEmpty() );
10691 OO
.ui
.ComboBoxInputWidget
.prototype.setDisabled = function ( disabled
) {
10693 OO
.ui
.ComboBoxInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
10695 if ( this.dropdownButton
) {
10696 this.dropdownButton
.setDisabled( this.isDisabled() );
10699 this.menu
.setDisabled( this.isDisabled() );
10706 * Set the options available for this input.
10708 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10711 OO
.ui
.ComboBoxInputWidget
.prototype.setOptions = function ( options
) {
10714 .addItems( options
.map( function ( opt
) {
10715 return new OO
.ui
.MenuOptionWidget( {
10717 label
: opt
.label
!== undefined ? opt
.label
: opt
.data
10725 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
10726 * which is a widget that is specified by reference before any optional configuration settings.
10728 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
10730 * - **left**: The label is placed before the field-widget and aligned with the left margin.
10731 * A left-alignment is used for forms with many fields.
10732 * - **right**: The label is placed before the field-widget and aligned to the right margin.
10733 * A right-alignment is used for long but familiar forms which users tab through,
10734 * verifying the current field with a quick glance at the label.
10735 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
10736 * that users fill out from top to bottom.
10737 * - **inline**: The label is placed after the field-widget and aligned to the left.
10738 * An inline-alignment is best used with checkboxes or radio buttons.
10740 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
10741 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
10743 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
10746 * @extends OO.ui.Layout
10747 * @mixins OO.ui.mixin.LabelElement
10748 * @mixins OO.ui.mixin.TitledElement
10751 * @param {OO.ui.Widget} fieldWidget Field widget
10752 * @param {Object} [config] Configuration options
10753 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
10754 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
10755 * The array may contain strings or OO.ui.HtmlSnippet instances.
10756 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
10757 * The array may contain strings or OO.ui.HtmlSnippet instances.
10758 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
10759 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
10760 * For important messages, you are advised to use `notices`, as they are always shown.
10761 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
10762 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
10764 * @throws {Error} An error is thrown if no widget is specified
10766 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
10767 // Allow passing positional parameters inside the config object
10768 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
10769 config
= fieldWidget
;
10770 fieldWidget
= config
.fieldWidget
;
10773 // Make sure we have required constructor arguments
10774 if ( fieldWidget
=== undefined ) {
10775 throw new Error( 'Widget not found' );
10778 // Configuration initialization
10779 config
= $.extend( { align
: 'left' }, config
);
10781 // Parent constructor
10782 OO
.ui
.FieldLayout
.parent
.call( this, config
);
10784 // Mixin constructors
10785 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, {
10786 $label
: $( '<label>' )
10788 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
10791 this.fieldWidget
= fieldWidget
;
10794 this.$field
= this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
10795 this.$messages
= $( '<ul>' );
10796 this.$header
= $( '<span>' );
10797 this.$body
= $( '<div>' );
10799 if ( config
.help
) {
10800 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
10801 $overlay
: config
.$overlay
,
10805 classes
: [ 'oo-ui-fieldLayout-help' ],
10809 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
10810 this.popupButtonWidget
.getPopup().$body
.html( config
.help
.toString() );
10812 this.popupButtonWidget
.getPopup().$body
.text( config
.help
);
10814 this.$help
= this.popupButtonWidget
.$element
;
10816 this.$help
= $( [] );
10820 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
10823 if ( this.fieldWidget
.getInputId() ) {
10824 this.$label
.attr( 'for', this.fieldWidget
.getInputId() );
10826 this.$label
.on( 'click', function () {
10827 this.fieldWidget
.simulateLabelClick();
10832 .addClass( 'oo-ui-fieldLayout' )
10833 .toggleClass( 'oo-ui-fieldLayout-disabled', this.fieldWidget
.isDisabled() )
10834 .append( this.$body
);
10835 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
10836 this.$header
.addClass( 'oo-ui-fieldLayout-header' );
10837 this.$messages
.addClass( 'oo-ui-fieldLayout-messages' );
10839 .addClass( 'oo-ui-fieldLayout-field' )
10840 .append( this.fieldWidget
.$element
);
10842 this.setErrors( config
.errors
|| [] );
10843 this.setNotices( config
.notices
|| [] );
10844 this.setAlignment( config
.align
);
10849 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
10850 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.LabelElement
);
10851 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.TitledElement
);
10856 * Handle field disable events.
10859 * @param {boolean} value Field is disabled
10861 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
10862 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
10866 * Get the widget contained by the field.
10868 * @return {OO.ui.Widget} Field widget
10870 OO
.ui
.FieldLayout
.prototype.getField = function () {
10871 return this.fieldWidget
;
10875 * Return `true` if the given field widget can be used with `'inline'` alignment (see
10876 * #setAlignment). Return `false` if it can't or if this can't be determined.
10878 * @return {boolean}
10880 OO
.ui
.FieldLayout
.prototype.isFieldInline = function () {
10881 // This is very simplistic, but should be good enough.
10882 return this.getField().$element
.prop( 'tagName' ).toLowerCase() === 'span';
10887 * @param {string} kind 'error' or 'notice'
10888 * @param {string|OO.ui.HtmlSnippet} text
10891 OO
.ui
.FieldLayout
.prototype.makeMessage = function ( kind
, text
) {
10892 var $listItem
, $icon
, message
;
10893 $listItem
= $( '<li>' );
10894 if ( kind
=== 'error' ) {
10895 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'warning' ] } ).$element
;
10896 } else if ( kind
=== 'notice' ) {
10897 $icon
= new OO
.ui
.IconWidget( { icon
: 'info' } ).$element
;
10901 message
= new OO
.ui
.LabelWidget( { label
: text
} );
10903 .append( $icon
, message
.$element
)
10904 .addClass( 'oo-ui-fieldLayout-messages-' + kind
);
10909 * Set the field alignment mode.
10912 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
10915 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
10916 if ( value
!== this.align
) {
10917 // Default to 'left'
10918 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
10922 if ( value
=== 'inline' && !this.isFieldInline() ) {
10925 // Reorder elements
10926 if ( value
=== 'top' ) {
10927 this.$header
.append( this.$label
, this.$help
);
10928 this.$body
.append( this.$header
, this.$field
);
10929 } else if ( value
=== 'inline' ) {
10930 this.$header
.append( this.$label
, this.$help
);
10931 this.$body
.append( this.$field
, this.$header
);
10933 this.$header
.append( this.$label
);
10934 this.$body
.append( this.$header
, this.$help
, this.$field
);
10936 // Set classes. The following classes can be used here:
10937 // * oo-ui-fieldLayout-align-left
10938 // * oo-ui-fieldLayout-align-right
10939 // * oo-ui-fieldLayout-align-top
10940 // * oo-ui-fieldLayout-align-inline
10941 if ( this.align
) {
10942 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
10944 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
10945 this.align
= value
;
10952 * Set the list of error messages.
10954 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
10955 * The array may contain strings or OO.ui.HtmlSnippet instances.
10958 OO
.ui
.FieldLayout
.prototype.setErrors = function ( errors
) {
10959 this.errors
= errors
.slice();
10960 this.updateMessages();
10965 * Set the list of notice messages.
10967 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
10968 * The array may contain strings or OO.ui.HtmlSnippet instances.
10971 OO
.ui
.FieldLayout
.prototype.setNotices = function ( notices
) {
10972 this.notices
= notices
.slice();
10973 this.updateMessages();
10978 * Update the rendering of error and notice messages.
10982 OO
.ui
.FieldLayout
.prototype.updateMessages = function () {
10984 this.$messages
.empty();
10986 if ( this.errors
.length
|| this.notices
.length
) {
10987 this.$body
.after( this.$messages
);
10989 this.$messages
.remove();
10993 for ( i
= 0; i
< this.notices
.length
; i
++ ) {
10994 this.$messages
.append( this.makeMessage( 'notice', this.notices
[ i
] ) );
10996 for ( i
= 0; i
< this.errors
.length
; i
++ ) {
10997 this.$messages
.append( this.makeMessage( 'error', this.errors
[ i
] ) );
11002 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
11003 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
11004 * is required and is specified before any optional configuration settings.
11006 * Labels can be aligned in one of four ways:
11008 * - **left**: The label is placed before the field-widget and aligned with the left margin.
11009 * A left-alignment is used for forms with many fields.
11010 * - **right**: The label is placed before the field-widget and aligned to the right margin.
11011 * A right-alignment is used for long but familiar forms which users tab through,
11012 * verifying the current field with a quick glance at the label.
11013 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
11014 * that users fill out from top to bottom.
11015 * - **inline**: The label is placed after the field-widget and aligned to the left.
11016 * An inline-alignment is best used with checkboxes or radio buttons.
11018 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
11019 * text is specified.
11022 * // Example of an ActionFieldLayout
11023 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
11024 * new OO.ui.TextInputWidget( {
11025 * placeholder: 'Field widget'
11027 * new OO.ui.ButtonWidget( {
11031 * label: 'An ActionFieldLayout. This label is aligned top',
11033 * help: 'This is help text'
11037 * $( 'body' ).append( actionFieldLayout.$element );
11040 * @extends OO.ui.FieldLayout
11043 * @param {OO.ui.Widget} fieldWidget Field widget
11044 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
11045 * @param {Object} config
11047 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
11048 // Allow passing positional parameters inside the config object
11049 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
11050 config
= fieldWidget
;
11051 fieldWidget
= config
.fieldWidget
;
11052 buttonWidget
= config
.buttonWidget
;
11055 // Parent constructor
11056 OO
.ui
.ActionFieldLayout
.parent
.call( this, fieldWidget
, config
);
11059 this.buttonWidget
= buttonWidget
;
11060 this.$button
= $( '<span>' );
11061 this.$input
= this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
11065 .addClass( 'oo-ui-actionFieldLayout' );
11067 .addClass( 'oo-ui-actionFieldLayout-button' )
11068 .append( this.buttonWidget
.$element
);
11070 .addClass( 'oo-ui-actionFieldLayout-input' )
11071 .append( this.fieldWidget
.$element
);
11073 .append( this.$input
, this.$button
);
11078 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
11081 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
11082 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
11083 * configured with a label as well. For more information and examples,
11084 * please see the [OOjs UI documentation on MediaWiki][1].
11087 * // Example of a fieldset layout
11088 * var input1 = new OO.ui.TextInputWidget( {
11089 * placeholder: 'A text input field'
11092 * var input2 = new OO.ui.TextInputWidget( {
11093 * placeholder: 'A text input field'
11096 * var fieldset = new OO.ui.FieldsetLayout( {
11097 * label: 'Example of a fieldset layout'
11100 * fieldset.addItems( [
11101 * new OO.ui.FieldLayout( input1, {
11102 * label: 'Field One'
11104 * new OO.ui.FieldLayout( input2, {
11105 * label: 'Field Two'
11108 * $( 'body' ).append( fieldset.$element );
11110 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
11113 * @extends OO.ui.Layout
11114 * @mixins OO.ui.mixin.IconElement
11115 * @mixins OO.ui.mixin.LabelElement
11116 * @mixins OO.ui.mixin.GroupElement
11119 * @param {Object} [config] Configuration options
11120 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
11121 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
11122 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
11123 * For important messages, you are advised to use `notices`, as they are always shown.
11124 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
11125 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
11127 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
11128 // Configuration initialization
11129 config
= config
|| {};
11131 // Parent constructor
11132 OO
.ui
.FieldsetLayout
.parent
.call( this, config
);
11134 // Mixin constructors
11135 OO
.ui
.mixin
.IconElement
.call( this, config
);
11136 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: $( '<div>' ) } ) );
11137 OO
.ui
.mixin
.GroupElement
.call( this, config
);
11140 this.$header
= $( '<div>' );
11141 if ( config
.help
) {
11142 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
11143 $overlay
: config
.$overlay
,
11147 classes
: [ 'oo-ui-fieldsetLayout-help' ],
11151 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
11152 this.popupButtonWidget
.getPopup().$body
.html( config
.help
.toString() );
11154 this.popupButtonWidget
.getPopup().$body
.text( config
.help
);
11156 this.$help
= this.popupButtonWidget
.$element
;
11158 this.$help
= $( [] );
11163 .addClass( 'oo-ui-fieldsetLayout-header' )
11164 .append( this.$icon
, this.$label
, this.$help
);
11165 this.$group
.addClass( 'oo-ui-fieldsetLayout-group' );
11167 .addClass( 'oo-ui-fieldsetLayout' )
11168 .prepend( this.$header
, this.$group
);
11169 if ( Array
.isArray( config
.items
) ) {
11170 this.addItems( config
.items
);
11176 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
11177 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.IconElement
);
11178 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.LabelElement
);
11179 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.GroupElement
);
11181 /* Static Properties */
11187 OO
.ui
.FieldsetLayout
.static.tagName
= 'fieldset';
11190 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
11191 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
11192 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
11193 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
11195 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
11196 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
11197 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
11198 * some fancier controls. Some controls have both regular and InputWidget variants, for example
11199 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
11200 * often have simplified APIs to match the capabilities of HTML forms.
11201 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
11203 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
11204 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11207 * // Example of a form layout that wraps a fieldset layout
11208 * var input1 = new OO.ui.TextInputWidget( {
11209 * placeholder: 'Username'
11211 * var input2 = new OO.ui.TextInputWidget( {
11212 * placeholder: 'Password',
11215 * var submit = new OO.ui.ButtonInputWidget( {
11219 * var fieldset = new OO.ui.FieldsetLayout( {
11220 * label: 'A form layout'
11222 * fieldset.addItems( [
11223 * new OO.ui.FieldLayout( input1, {
11224 * label: 'Username',
11227 * new OO.ui.FieldLayout( input2, {
11228 * label: 'Password',
11231 * new OO.ui.FieldLayout( submit )
11233 * var form = new OO.ui.FormLayout( {
11234 * items: [ fieldset ],
11235 * action: '/api/formhandler',
11238 * $( 'body' ).append( form.$element );
11241 * @extends OO.ui.Layout
11242 * @mixins OO.ui.mixin.GroupElement
11245 * @param {Object} [config] Configuration options
11246 * @cfg {string} [method] HTML form `method` attribute
11247 * @cfg {string} [action] HTML form `action` attribute
11248 * @cfg {string} [enctype] HTML form `enctype` attribute
11249 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
11251 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
11254 // Configuration initialization
11255 config
= config
|| {};
11257 // Parent constructor
11258 OO
.ui
.FormLayout
.parent
.call( this, config
);
11260 // Mixin constructors
11261 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
11264 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
11266 // Make sure the action is safe
11267 action
= config
.action
;
11268 if ( action
!== undefined && !OO
.ui
.isSafeUrl( action
) ) {
11269 action
= './' + action
;
11274 .addClass( 'oo-ui-formLayout' )
11276 method
: config
.method
,
11278 enctype
: config
.enctype
11280 if ( Array
.isArray( config
.items
) ) {
11281 this.addItems( config
.items
);
11287 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
11288 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.mixin
.GroupElement
);
11293 * A 'submit' event is emitted when the form is submitted.
11298 /* Static Properties */
11304 OO
.ui
.FormLayout
.static.tagName
= 'form';
11309 * Handle form submit events.
11312 * @param {jQuery.Event} e Submit event
11315 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
11316 if ( this.emit( 'submit' ) ) {
11322 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
11323 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
11326 * // Example of a panel layout
11327 * var panel = new OO.ui.PanelLayout( {
11331 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
11333 * $( 'body' ).append( panel.$element );
11336 * @extends OO.ui.Layout
11339 * @param {Object} [config] Configuration options
11340 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
11341 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
11342 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
11343 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
11345 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
11346 // Configuration initialization
11347 config
= $.extend( {
11354 // Parent constructor
11355 OO
.ui
.PanelLayout
.parent
.call( this, config
);
11358 this.$element
.addClass( 'oo-ui-panelLayout' );
11359 if ( config
.scrollable
) {
11360 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
11362 if ( config
.padded
) {
11363 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
11365 if ( config
.expanded
) {
11366 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
11368 if ( config
.framed
) {
11369 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
11375 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
11380 * Focus the panel layout
11382 * The default implementation just focuses the first focusable element in the panel
11384 OO
.ui
.PanelLayout
.prototype.focus = function () {
11385 OO
.ui
.findFocusable( this.$element
).focus();
11389 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
11390 * items), with small margins between them. Convenient when you need to put a number of block-level
11391 * widgets on a single line next to each other.
11393 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
11396 * // HorizontalLayout with a text input and a label
11397 * var layout = new OO.ui.HorizontalLayout( {
11399 * new OO.ui.LabelWidget( { label: 'Label' } ),
11400 * new OO.ui.TextInputWidget( { value: 'Text' } )
11403 * $( 'body' ).append( layout.$element );
11406 * @extends OO.ui.Layout
11407 * @mixins OO.ui.mixin.GroupElement
11410 * @param {Object} [config] Configuration options
11411 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
11413 OO
.ui
.HorizontalLayout
= function OoUiHorizontalLayout( config
) {
11414 // Configuration initialization
11415 config
= config
|| {};
11417 // Parent constructor
11418 OO
.ui
.HorizontalLayout
.parent
.call( this, config
);
11420 // Mixin constructors
11421 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
11424 this.$element
.addClass( 'oo-ui-horizontalLayout' );
11425 if ( Array
.isArray( config
.items
) ) {
11426 this.addItems( config
.items
);
11432 OO
.inheritClass( OO
.ui
.HorizontalLayout
, OO
.ui
.Layout
);
11433 OO
.mixinClass( OO
.ui
.HorizontalLayout
, OO
.ui
.mixin
.GroupElement
);
11437 //# sourceMappingURL=oojs-ui-core.js.map