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-03-15T17:06:24Z
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 from :focusable in jQueryUI v1.11.4 - 2015-04-14
78 * @param {jQuery} $element Element to test
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
.filters
.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, 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
239 * @param {number} wait
240 * @param {boolean} immediate
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
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
286 * @param {number} wait
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
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 // Configuration initialization
583 config
= config
|| {};
588 this.data
= config
.data
;
589 this.$element
= config
.$element
||
590 $( document
.createElement( this.getTagName() ) );
591 this.elementGroup
= null;
594 if ( Array
.isArray( config
.classes
) ) {
595 this.$element
.addClass( config
.classes
.join( ' ' ) );
598 this.$element
.attr( 'id', config
.id
);
601 this.$element
.text( config
.text
);
603 if ( config
.content
) {
604 // The `content` property treats plain strings as text; use an
605 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
606 // appropriate $element appended.
607 this.$element
.append( config
.content
.map( function ( v
) {
608 if ( typeof v
=== 'string' ) {
609 // Escape string so it is properly represented in HTML.
610 return document
.createTextNode( v
);
611 } else if ( v
instanceof OO
.ui
.HtmlSnippet
) {
614 } else if ( v
instanceof OO
.ui
.Element
) {
620 if ( config
.$content
) {
621 // The `$content` property treats plain strings as HTML.
622 this.$element
.append( config
.$content
);
628 OO
.initClass( OO
.ui
.Element
);
630 /* Static Properties */
633 * The name of the HTML tag used by the element.
635 * The static value may be ignored if the #getTagName method is overridden.
641 OO
.ui
.Element
.static.tagName
= 'div';
646 * Reconstitute a JavaScript object corresponding to a widget created
647 * by the PHP implementation.
649 * @param {string|HTMLElement|jQuery} idOrNode
650 * A DOM id (if a string) or node for the widget to infuse.
651 * @return {OO.ui.Element}
652 * The `OO.ui.Element` corresponding to this (infusable) document node.
653 * For `Tag` objects emitted on the HTML side (used occasionally for content)
654 * the value returned is a newly-created Element wrapping around the existing
657 OO
.ui
.Element
.static.infuse = function ( idOrNode
) {
658 var obj
= OO
.ui
.Element
.static.unsafeInfuse( idOrNode
, false );
659 // Verify that the type matches up.
660 // FIXME: uncomment after T89721 is fixed (see T90929)
662 if ( !( obj instanceof this['class'] ) ) {
663 throw new Error( 'Infusion type mismatch!' );
670 * Implementation helper for `infuse`; skips the type check and has an
671 * extra property so that only the top-level invocation touches the DOM.
674 * @param {string|HTMLElement|jQuery} idOrNode
675 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
676 * when the top-level widget of this infusion is inserted into DOM,
677 * replacing the original node; or false for top-level invocation.
678 * @return {OO.ui.Element}
680 OO
.ui
.Element
.static.unsafeInfuse = function ( idOrNode
, domPromise
) {
681 // look for a cached result of a previous infusion.
682 var id
, $elem
, data
, cls
, parts
, parent
, obj
, top
, state
, infusedChildren
;
683 if ( typeof idOrNode
=== 'string' ) {
685 $elem
= $( document
.getElementById( id
) );
687 $elem
= $( idOrNode
);
688 id
= $elem
.attr( 'id' );
690 if ( !$elem
.length
) {
691 throw new Error( 'Widget not found: ' + id
);
693 if ( $elem
[ 0 ].oouiInfused
) {
694 $elem
= $elem
[ 0 ].oouiInfused
;
696 data
= $elem
.data( 'ooui-infused' );
699 if ( data
=== true ) {
700 throw new Error( 'Circular dependency! ' + id
);
703 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
704 state
= data
.constructor.static.gatherPreInfuseState( $elem
, data
);
705 // restore dynamic state after the new element is re-inserted into DOM under infused parent
706 domPromise
.done( data
.restorePreInfuseState
.bind( data
, state
) );
707 infusedChildren
= $elem
.data( 'ooui-infused-children' );
708 if ( infusedChildren
&& infusedChildren
.length
) {
709 infusedChildren
.forEach( function ( data
) {
710 var state
= data
.constructor.static.gatherPreInfuseState( $elem
, data
);
711 domPromise
.done( data
.restorePreInfuseState
.bind( data
, state
) );
717 data
= $elem
.attr( 'data-ooui' );
719 throw new Error( 'No infusion data found: ' + id
);
722 data
= $.parseJSON( data
);
726 if ( !( data
&& data
._
) ) {
727 throw new Error( 'No valid infusion data found: ' + id
);
729 if ( data
._
=== 'Tag' ) {
730 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
731 return new OO
.ui
.Element( { $element
: $elem
} );
733 parts
= data
._
.split( '.' );
734 cls
= OO
.getProp
.apply( OO
, [ window
].concat( parts
) );
735 if ( cls
=== undefined ) {
736 // The PHP output might be old and not including the "OO.ui" prefix
737 // TODO: Remove this back-compat after next major release
738 cls
= OO
.getProp
.apply( OO
, [ OO
.ui
].concat( parts
) );
739 if ( cls
=== undefined ) {
740 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
744 // Verify that we're creating an OO.ui.Element instance
747 while ( parent
!== undefined ) {
748 if ( parent
=== OO
.ui
.Element
) {
753 parent
= parent
.parent
;
756 if ( parent
!== OO
.ui
.Element
) {
757 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
760 if ( domPromise
=== false ) {
762 domPromise
= top
.promise();
764 $elem
.data( 'ooui-infused', true ); // prevent loops
765 data
.id
= id
; // implicit
766 infusedChildren
= [];
767 data
= OO
.copy( data
, null, function deserialize( value
) {
769 if ( OO
.isPlainObject( value
) ) {
771 infused
= OO
.ui
.Element
.static.unsafeInfuse( value
.tag
, domPromise
);
772 infusedChildren
.push( infused
);
773 // Flatten the structure
774 infusedChildren
.push
.apply( infusedChildren
, infused
.$element
.data( 'ooui-infused-children' ) || [] );
775 infused
.$element
.removeData( 'ooui-infused-children' );
778 if ( value
.html
!== undefined ) {
779 return new OO
.ui
.HtmlSnippet( value
.html
);
783 // allow widgets to reuse parts of the DOM
784 data
= cls
.static.reusePreInfuseDOM( $elem
[ 0 ], data
);
785 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
786 state
= cls
.static.gatherPreInfuseState( $elem
[ 0 ], data
);
788 // eslint-disable-next-line new-cap
789 obj
= new cls( data
);
790 // now replace old DOM with this new DOM.
792 // An efficient constructor might be able to reuse the entire DOM tree of the original element,
793 // so only mutate the DOM if we need to.
794 if ( $elem
[ 0 ] !== obj
.$element
[ 0 ] ) {
795 $elem
.replaceWith( obj
.$element
);
796 // This element is now gone from the DOM, but if anyone is holding a reference to it,
797 // let's allow them to OO.ui.infuse() it and do what they expect (T105828).
798 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
799 $elem
[ 0 ].oouiInfused
= obj
.$element
;
803 obj
.$element
.data( 'ooui-infused', obj
);
804 obj
.$element
.data( 'ooui-infused-children', infusedChildren
);
805 // set the 'data-ooui' attribute so we can identify infused widgets
806 obj
.$element
.attr( 'data-ooui', '' );
807 // restore dynamic state after the new element is inserted into DOM
808 domPromise
.done( obj
.restorePreInfuseState
.bind( obj
, state
) );
813 * Pick out parts of `node`'s DOM to be reused when infusing a widget.
815 * This method **must not** make any changes to the DOM, only find interesting pieces and add them
816 * to `config` (which should then be returned). Actual DOM juggling should then be done by the
817 * constructor, which will be given the enhanced config.
820 * @param {HTMLElement} node
821 * @param {Object} config
824 OO
.ui
.Element
.static.reusePreInfuseDOM = function ( node
, config
) {
829 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of an HTML DOM node
830 * (and its children) that represent an Element of the same class and the given configuration,
831 * generated by the PHP implementation.
833 * This method is called just before `node` is detached from the DOM. The return value of this
834 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
835 * is inserted into DOM to replace `node`.
838 * @param {HTMLElement} node
839 * @param {Object} config
842 OO
.ui
.Element
.static.gatherPreInfuseState = function () {
847 * Get a jQuery function within a specific document.
850 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
851 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
853 * @return {Function} Bound jQuery function
855 OO
.ui
.Element
.static.getJQuery = function ( context
, $iframe
) {
856 function wrapper( selector
) {
857 return $( selector
, wrapper
.context
);
860 wrapper
.context
= this.getDocument( context
);
863 wrapper
.$iframe
= $iframe
;
870 * Get the document of an element.
873 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
874 * @return {HTMLDocument|null} Document object
876 OO
.ui
.Element
.static.getDocument = function ( obj
) {
877 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
878 return ( obj
[ 0 ] && obj
[ 0 ].ownerDocument
) ||
879 // Empty jQuery selections might have a context
886 ( obj
.nodeType
=== 9 && obj
) ||
891 * Get the window of an element or document.
894 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
895 * @return {Window} Window object
897 OO
.ui
.Element
.static.getWindow = function ( obj
) {
898 var doc
= this.getDocument( obj
);
899 return doc
.defaultView
;
903 * Get the direction of an element or document.
906 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
907 * @return {string} Text direction, either 'ltr' or 'rtl'
909 OO
.ui
.Element
.static.getDir = function ( obj
) {
912 if ( obj
instanceof jQuery
) {
915 isDoc
= obj
.nodeType
=== 9;
916 isWin
= obj
.document
!== undefined;
917 if ( isDoc
|| isWin
) {
923 return $( obj
).css( 'direction' );
927 * Get the offset between two frames.
929 * TODO: Make this function not use recursion.
932 * @param {Window} from Window of the child frame
933 * @param {Window} [to=window] Window of the parent frame
934 * @param {Object} [offset] Offset to start with, used internally
935 * @return {Object} Offset object, containing left and top properties
937 OO
.ui
.Element
.static.getFrameOffset = function ( from, to
, offset
) {
938 var i
, len
, frames
, frame
, rect
;
944 offset
= { top
: 0, left
: 0 };
946 if ( from.parent
=== from ) {
950 // Get iframe element
951 frames
= from.parent
.document
.getElementsByTagName( 'iframe' );
952 for ( i
= 0, len
= frames
.length
; i
< len
; i
++ ) {
953 if ( frames
[ i
].contentWindow
=== from ) {
959 // Recursively accumulate offset values
961 rect
= frame
.getBoundingClientRect();
962 offset
.left
+= rect
.left
;
963 offset
.top
+= rect
.top
;
965 this.getFrameOffset( from.parent
, offset
);
972 * Get the offset between two elements.
974 * The two elements may be in a different frame, but in that case the frame $element is in must
975 * be contained in the frame $anchor is in.
978 * @param {jQuery} $element Element whose position to get
979 * @param {jQuery} $anchor Element to get $element's position relative to
980 * @return {Object} Translated position coordinates, containing top and left properties
982 OO
.ui
.Element
.static.getRelativePosition = function ( $element
, $anchor
) {
983 var iframe
, iframePos
,
984 pos
= $element
.offset(),
985 anchorPos
= $anchor
.offset(),
986 elementDocument
= this.getDocument( $element
),
987 anchorDocument
= this.getDocument( $anchor
);
989 // If $element isn't in the same document as $anchor, traverse up
990 while ( elementDocument
!== anchorDocument
) {
991 iframe
= elementDocument
.defaultView
.frameElement
;
993 throw new Error( '$element frame is not contained in $anchor frame' );
995 iframePos
= $( iframe
).offset();
996 pos
.left
+= iframePos
.left
;
997 pos
.top
+= iframePos
.top
;
998 elementDocument
= iframe
.ownerDocument
;
1000 pos
.left
-= anchorPos
.left
;
1001 pos
.top
-= anchorPos
.top
;
1006 * Get element border sizes.
1009 * @param {HTMLElement} el Element to measure
1010 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1012 OO
.ui
.Element
.static.getBorders = function ( el
) {
1013 var doc
= el
.ownerDocument
,
1014 win
= doc
.defaultView
,
1015 style
= win
.getComputedStyle( el
, null ),
1017 top
= parseFloat( style
? style
.borderTopWidth
: $el
.css( 'borderTopWidth' ) ) || 0,
1018 left
= parseFloat( style
? style
.borderLeftWidth
: $el
.css( 'borderLeftWidth' ) ) || 0,
1019 bottom
= parseFloat( style
? style
.borderBottomWidth
: $el
.css( 'borderBottomWidth' ) ) || 0,
1020 right
= parseFloat( style
? style
.borderRightWidth
: $el
.css( 'borderRightWidth' ) ) || 0;
1031 * Get dimensions of an element or window.
1034 * @param {HTMLElement|Window} el Element to measure
1035 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1037 OO
.ui
.Element
.static.getDimensions = function ( el
) {
1039 doc
= el
.ownerDocument
|| el
.document
,
1040 win
= doc
.defaultView
;
1042 if ( win
=== el
|| el
=== doc
.documentElement
) {
1045 borders
: { top
: 0, left
: 0, bottom
: 0, right
: 0 },
1047 top
: $win
.scrollTop(),
1048 left
: $win
.scrollLeft()
1050 scrollbar
: { right
: 0, bottom
: 0 },
1054 bottom
: $win
.innerHeight(),
1055 right
: $win
.innerWidth()
1061 borders
: this.getBorders( el
),
1063 top
: $el
.scrollTop(),
1064 left
: $el
.scrollLeft()
1067 right
: $el
.innerWidth() - el
.clientWidth
,
1068 bottom
: $el
.innerHeight() - el
.clientHeight
1070 rect
: el
.getBoundingClientRect()
1076 * Get the number of pixels that an element's content is scrolled to the left.
1078 * Adapted from <https://github.com/othree/jquery.rtl-scroll-type>.
1079 * Original code copyright 2012 Wei-Ko Kao, licensed under the MIT License.
1081 * This function smooths out browser inconsistencies (nicely described in the README at
1082 * <https://github.com/othree/jquery.rtl-scroll-type>) and produces a result consistent
1083 * with Firefox's 'scrollLeft', which seems the sanest.
1087 * @param {HTMLElement|Window} el Element to measure
1088 * @return {number} Scroll position from the left.
1089 * If the element's direction is LTR, this is a positive number between `0` (initial scroll position)
1090 * and `el.scrollWidth - el.clientWidth` (furthest possible scroll position).
1091 * If the element's direction is RTL, this is a negative number between `0` (initial scroll position)
1092 * and `-el.scrollWidth + el.clientWidth` (furthest possible scroll position).
1094 OO
.ui
.Element
.static.getScrollLeft
= ( function () {
1095 var rtlScrollType
= null;
1098 var $definer
= $( '<div dir="rtl" style="font-size: 14px; width: 1px; height: 1px; position: absolute; top: -1000px; overflow: scroll">A</div>' ),
1099 definer
= $definer
[ 0 ];
1101 $definer
.appendTo( 'body' );
1102 if ( definer
.scrollLeft
> 0 ) {
1104 rtlScrollType
= 'default';
1106 definer
.scrollLeft
= 1;
1107 if ( definer
.scrollLeft
=== 0 ) {
1108 // Firefox, old Opera
1109 rtlScrollType
= 'negative';
1111 // Internet Explorer, Edge
1112 rtlScrollType
= 'reverse';
1118 return function getScrollLeft( el
) {
1119 var isRoot
= el
.window
=== el
||
1120 el
=== el
.ownerDocument
.body
||
1121 el
=== el
.ownerDocument
.documentElement
,
1122 scrollLeft
= isRoot
? $( window
).scrollLeft() : el
.scrollLeft
,
1123 // All browsers use the correct scroll type ('negative') on the root, so don't
1124 // do any fixups when looking at the root element
1125 direction
= isRoot
? 'ltr' : $( el
).css( 'direction' );
1127 if ( direction
=== 'rtl' ) {
1128 if ( rtlScrollType
=== null ) {
1131 if ( rtlScrollType
=== 'reverse' ) {
1132 scrollLeft
= -scrollLeft
;
1133 } else if ( rtlScrollType
=== 'default' ) {
1134 scrollLeft
= scrollLeft
- el
.scrollWidth
+ el
.clientWidth
;
1143 * Get scrollable object parent
1145 * documentElement can't be used to get or set the scrollTop
1146 * property on Blink. Changing and testing its value lets us
1147 * use 'body' or 'documentElement' based on what is working.
1149 * https://code.google.com/p/chromium/issues/detail?id=303131
1152 * @param {HTMLElement} el Element to find scrollable parent for
1153 * @return {HTMLElement} Scrollable parent
1155 OO
.ui
.Element
.static.getRootScrollableElement = function ( el
) {
1156 var scrollTop
, body
;
1158 if ( OO
.ui
.scrollableElement
=== undefined ) {
1159 body
= el
.ownerDocument
.body
;
1160 scrollTop
= body
.scrollTop
;
1163 if ( body
.scrollTop
=== 1 ) {
1164 body
.scrollTop
= scrollTop
;
1165 OO
.ui
.scrollableElement
= 'body';
1167 OO
.ui
.scrollableElement
= 'documentElement';
1171 return el
.ownerDocument
[ OO
.ui
.scrollableElement
];
1175 * Get closest scrollable container.
1177 * Traverses up until either a scrollable element or the root is reached, in which case the window
1181 * @param {HTMLElement} el Element to find scrollable container for
1182 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1183 * @return {HTMLElement} Closest scrollable container
1185 OO
.ui
.Element
.static.getClosestScrollableContainer = function ( el
, dimension
) {
1187 // Browsers do not correctly return the computed value of 'overflow' when 'overflow-x' and
1188 // 'overflow-y' have different values, so we need to check the separate properties.
1189 props
= [ 'overflow-x', 'overflow-y' ],
1190 $parent
= $( el
).parent();
1192 if ( dimension
=== 'x' || dimension
=== 'y' ) {
1193 props
= [ 'overflow-' + dimension
];
1196 while ( $parent
.length
) {
1197 if ( $parent
[ 0 ] === this.getRootScrollableElement( el
) ) {
1198 return $parent
[ 0 ];
1202 val
= $parent
.css( props
[ i
] );
1203 // We assume that elements with 'overflow' (in any direction) set to 'hidden' will never be
1204 // scrolled in that direction, but they can actually be scrolled programatically. The user can
1205 // unintentionally perform a scroll in such case even if the application doesn't scroll
1206 // programatically, e.g. when jumping to an anchor, or when using built-in find functionality.
1207 // This could cause funny issues...
1208 if ( val
=== 'auto' || val
=== 'scroll' ) {
1209 return $parent
[ 0 ];
1212 $parent
= $parent
.parent();
1214 return this.getDocument( el
).body
;
1218 * Scroll element into view.
1221 * @param {HTMLElement} el Element to scroll into view
1222 * @param {Object} [config] Configuration options
1223 * @param {string} [config.duration='fast'] jQuery animation duration value
1224 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1225 * to scroll in both directions
1226 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1228 OO
.ui
.Element
.static.scrollIntoView = function ( el
, config
) {
1229 var position
, animations
, container
, $container
, elementDimensions
, containerDimensions
, $window
,
1230 deferred
= $.Deferred();
1232 // Configuration initialization
1233 config
= config
|| {};
1236 container
= this.getClosestScrollableContainer( el
, config
.direction
);
1237 $container
= $( container
);
1238 elementDimensions
= this.getDimensions( el
);
1239 containerDimensions
= this.getDimensions( container
);
1240 $window
= $( this.getWindow( el
) );
1242 // Compute the element's position relative to the container
1243 if ( $container
.is( 'html, body' ) ) {
1244 // If the scrollable container is the root, this is easy
1246 top
: elementDimensions
.rect
.top
,
1247 bottom
: $window
.innerHeight() - elementDimensions
.rect
.bottom
,
1248 left
: elementDimensions
.rect
.left
,
1249 right
: $window
.innerWidth() - elementDimensions
.rect
.right
1252 // Otherwise, we have to subtract el's coordinates from container's coordinates
1254 top
: elementDimensions
.rect
.top
- ( containerDimensions
.rect
.top
+ containerDimensions
.borders
.top
),
1255 bottom
: containerDimensions
.rect
.bottom
- containerDimensions
.borders
.bottom
- containerDimensions
.scrollbar
.bottom
- elementDimensions
.rect
.bottom
,
1256 left
: elementDimensions
.rect
.left
- ( containerDimensions
.rect
.left
+ containerDimensions
.borders
.left
),
1257 right
: containerDimensions
.rect
.right
- containerDimensions
.borders
.right
- containerDimensions
.scrollbar
.right
- elementDimensions
.rect
.right
1261 if ( !config
.direction
|| config
.direction
=== 'y' ) {
1262 if ( position
.top
< 0 ) {
1263 animations
.scrollTop
= containerDimensions
.scroll
.top
+ position
.top
;
1264 } else if ( position
.top
> 0 && position
.bottom
< 0 ) {
1265 animations
.scrollTop
= containerDimensions
.scroll
.top
+ Math
.min( position
.top
, -position
.bottom
);
1268 if ( !config
.direction
|| config
.direction
=== 'x' ) {
1269 if ( position
.left
< 0 ) {
1270 animations
.scrollLeft
= containerDimensions
.scroll
.left
+ position
.left
;
1271 } else if ( position
.left
> 0 && position
.right
< 0 ) {
1272 animations
.scrollLeft
= containerDimensions
.scroll
.left
+ Math
.min( position
.left
, -position
.right
);
1275 if ( !$.isEmptyObject( animations
) ) {
1276 $container
.stop( true ).animate( animations
, config
.duration
=== undefined ? 'fast' : config
.duration
);
1277 $container
.queue( function ( next
) {
1284 return deferred
.promise();
1288 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1289 * and reserve space for them, because it probably doesn't.
1291 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1292 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1293 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1294 * and then reattach (or show) them back.
1297 * @param {HTMLElement} el Element to reconsider the scrollbars on
1299 OO
.ui
.Element
.static.reconsiderScrollbars = function ( el
) {
1300 var i
, len
, scrollLeft
, scrollTop
, nodes
= [];
1301 // Save scroll position
1302 scrollLeft
= el
.scrollLeft
;
1303 scrollTop
= el
.scrollTop
;
1304 // Detach all children
1305 while ( el
.firstChild
) {
1306 nodes
.push( el
.firstChild
);
1307 el
.removeChild( el
.firstChild
);
1310 void el
.offsetHeight
;
1311 // Reattach all children
1312 for ( i
= 0, len
= nodes
.length
; i
< len
; i
++ ) {
1313 el
.appendChild( nodes
[ i
] );
1315 // Restore scroll position (no-op if scrollbars disappeared)
1316 el
.scrollLeft
= scrollLeft
;
1317 el
.scrollTop
= scrollTop
;
1323 * Toggle visibility of an element.
1325 * @param {boolean} [show] Make element visible, omit to toggle visibility
1329 OO
.ui
.Element
.prototype.toggle = function ( show
) {
1330 show
= show
=== undefined ? !this.visible
: !!show
;
1332 if ( show
!== this.isVisible() ) {
1333 this.visible
= show
;
1334 this.$element
.toggleClass( 'oo-ui-element-hidden', !this.visible
);
1335 this.emit( 'toggle', show
);
1342 * Check if element is visible.
1344 * @return {boolean} element is visible
1346 OO
.ui
.Element
.prototype.isVisible = function () {
1347 return this.visible
;
1353 * @return {Mixed} Element data
1355 OO
.ui
.Element
.prototype.getData = function () {
1362 * @param {Mixed} data Element data
1365 OO
.ui
.Element
.prototype.setData = function ( data
) {
1371 * Check if element supports one or more methods.
1373 * @param {string|string[]} methods Method or list of methods to check
1374 * @return {boolean} All methods are supported
1376 OO
.ui
.Element
.prototype.supports = function ( methods
) {
1380 methods
= Array
.isArray( methods
) ? methods
: [ methods
];
1381 for ( i
= 0, len
= methods
.length
; i
< len
; i
++ ) {
1382 if ( $.isFunction( this[ methods
[ i
] ] ) ) {
1387 return methods
.length
=== support
;
1391 * Update the theme-provided classes.
1393 * @localdoc This is called in element mixins and widget classes any time state changes.
1394 * Updating is debounced, minimizing overhead of changing multiple attributes and
1395 * guaranteeing that theme updates do not occur within an element's constructor
1397 OO
.ui
.Element
.prototype.updateThemeClasses = function () {
1398 OO
.ui
.theme
.queueUpdateElementClasses( this );
1402 * Get the HTML tag name.
1404 * Override this method to base the result on instance information.
1406 * @return {string} HTML tag name
1408 OO
.ui
.Element
.prototype.getTagName = function () {
1409 return this.constructor.static.tagName
;
1413 * Check if the element is attached to the DOM
1415 * @return {boolean} The element is attached to the DOM
1417 OO
.ui
.Element
.prototype.isElementAttached = function () {
1418 return $.contains( this.getElementDocument(), this.$element
[ 0 ] );
1422 * Get the DOM document.
1424 * @return {HTMLDocument} Document object
1426 OO
.ui
.Element
.prototype.getElementDocument = function () {
1427 // Don't cache this in other ways either because subclasses could can change this.$element
1428 return OO
.ui
.Element
.static.getDocument( this.$element
);
1432 * Get the DOM window.
1434 * @return {Window} Window object
1436 OO
.ui
.Element
.prototype.getElementWindow = function () {
1437 return OO
.ui
.Element
.static.getWindow( this.$element
);
1441 * Get closest scrollable container.
1443 * @return {HTMLElement} Closest scrollable container
1445 OO
.ui
.Element
.prototype.getClosestScrollableElementContainer = function () {
1446 return OO
.ui
.Element
.static.getClosestScrollableContainer( this.$element
[ 0 ] );
1450 * Get group element is in.
1452 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1454 OO
.ui
.Element
.prototype.getElementGroup = function () {
1455 return this.elementGroup
;
1459 * Set group element is in.
1461 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1464 OO
.ui
.Element
.prototype.setElementGroup = function ( group
) {
1465 this.elementGroup
= group
;
1470 * Scroll element into view.
1472 * @param {Object} [config] Configuration options
1473 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1475 OO
.ui
.Element
.prototype.scrollElementIntoView = function ( config
) {
1477 !this.isElementAttached() ||
1478 !this.isVisible() ||
1479 ( this.getElementGroup() && !this.getElementGroup().isVisible() )
1481 return $.Deferred().resolve();
1483 return OO
.ui
.Element
.static.scrollIntoView( this.$element
[ 0 ], config
);
1487 * Restore the pre-infusion dynamic state for this widget.
1489 * This method is called after #$element has been inserted into DOM. The parameter is the return
1490 * value of #gatherPreInfuseState.
1493 * @param {Object} state
1495 OO
.ui
.Element
.prototype.restorePreInfuseState = function () {
1499 * Wraps an HTML snippet for use with configuration values which default
1500 * to strings. This bypasses the default html-escaping done to string
1506 * @param {string} [content] HTML content
1508 OO
.ui
.HtmlSnippet
= function OoUiHtmlSnippet( content
) {
1510 this.content
= content
;
1515 OO
.initClass( OO
.ui
.HtmlSnippet
);
1522 * @return {string} Unchanged HTML snippet.
1524 OO
.ui
.HtmlSnippet
.prototype.toString = function () {
1525 return this.content
;
1529 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1530 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1531 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1532 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1533 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1537 * @extends OO.ui.Element
1538 * @mixins OO.EventEmitter
1541 * @param {Object} [config] Configuration options
1543 OO
.ui
.Layout
= function OoUiLayout( config
) {
1544 // Configuration initialization
1545 config
= config
|| {};
1547 // Parent constructor
1548 OO
.ui
.Layout
.parent
.call( this, config
);
1550 // Mixin constructors
1551 OO
.EventEmitter
.call( this );
1554 this.$element
.addClass( 'oo-ui-layout' );
1559 OO
.inheritClass( OO
.ui
.Layout
, OO
.ui
.Element
);
1560 OO
.mixinClass( OO
.ui
.Layout
, OO
.EventEmitter
);
1563 * Widgets are compositions of one or more OOjs UI elements that users can both view
1564 * and interact with. All widgets can be configured and modified via a standard API,
1565 * and their state can change dynamically according to a model.
1569 * @extends OO.ui.Element
1570 * @mixins OO.EventEmitter
1573 * @param {Object} [config] Configuration options
1574 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1575 * appearance reflects this state.
1577 OO
.ui
.Widget
= function OoUiWidget( config
) {
1578 // Initialize config
1579 config
= $.extend( { disabled
: false }, config
);
1581 // Parent constructor
1582 OO
.ui
.Widget
.parent
.call( this, config
);
1584 // Mixin constructors
1585 OO
.EventEmitter
.call( this );
1588 this.disabled
= null;
1589 this.wasDisabled
= null;
1592 this.$element
.addClass( 'oo-ui-widget' );
1593 this.setDisabled( !!config
.disabled
);
1598 OO
.inheritClass( OO
.ui
.Widget
, OO
.ui
.Element
);
1599 OO
.mixinClass( OO
.ui
.Widget
, OO
.EventEmitter
);
1601 /* Static Properties */
1604 * Whether this widget will behave reasonably when wrapped in an HTML `<label>`. If this is true,
1605 * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click
1610 * @property {boolean}
1612 OO
.ui
.Widget
.static.supportsSimpleLabel
= false;
1619 * A 'disable' event is emitted when the disabled state of the widget changes
1620 * (i.e. on disable **and** enable).
1622 * @param {boolean} disabled Widget is disabled
1628 * A 'toggle' event is emitted when the visibility of the widget changes.
1630 * @param {boolean} visible Widget is visible
1636 * Check if the widget is disabled.
1638 * @return {boolean} Widget is disabled
1640 OO
.ui
.Widget
.prototype.isDisabled = function () {
1641 return this.disabled
;
1645 * Set the 'disabled' state of the widget.
1647 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1649 * @param {boolean} disabled Disable widget
1652 OO
.ui
.Widget
.prototype.setDisabled = function ( disabled
) {
1655 this.disabled
= !!disabled
;
1656 isDisabled
= this.isDisabled();
1657 if ( isDisabled
!== this.wasDisabled
) {
1658 this.$element
.toggleClass( 'oo-ui-widget-disabled', isDisabled
);
1659 this.$element
.toggleClass( 'oo-ui-widget-enabled', !isDisabled
);
1660 this.$element
.attr( 'aria-disabled', isDisabled
.toString() );
1661 this.emit( 'disable', isDisabled
);
1662 this.updateThemeClasses();
1664 this.wasDisabled
= isDisabled
;
1670 * Update the disabled state, in case of changes in parent widget.
1674 OO
.ui
.Widget
.prototype.updateDisabled = function () {
1675 this.setDisabled( this.disabled
);
1687 OO
.ui
.Theme
= function OoUiTheme() {
1688 this.elementClassesQueue
= [];
1689 this.debouncedUpdateQueuedElementClasses
= OO
.ui
.debounce( this.updateQueuedElementClasses
);
1694 OO
.initClass( OO
.ui
.Theme
);
1699 * Get a list of classes to be applied to a widget.
1701 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
1702 * otherwise state transitions will not work properly.
1704 * @param {OO.ui.Element} element Element for which to get classes
1705 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
1707 OO
.ui
.Theme
.prototype.getElementClasses = function () {
1708 return { on
: [], off
: [] };
1712 * Update CSS classes provided by the theme.
1714 * For elements with theme logic hooks, this should be called any time there's a state change.
1716 * @param {OO.ui.Element} element Element for which to update classes
1718 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
1719 var $elements
= $( [] ),
1720 classes
= this.getElementClasses( element
);
1722 if ( element
.$icon
) {
1723 $elements
= $elements
.add( element
.$icon
);
1725 if ( element
.$indicator
) {
1726 $elements
= $elements
.add( element
.$indicator
);
1730 .removeClass( classes
.off
.join( ' ' ) )
1731 .addClass( classes
.on
.join( ' ' ) );
1737 OO
.ui
.Theme
.prototype.updateQueuedElementClasses = function () {
1739 for ( i
= 0; i
< this.elementClassesQueue
.length
; i
++ ) {
1740 this.updateElementClasses( this.elementClassesQueue
[ i
] );
1743 this.elementClassesQueue
= [];
1747 * Queue #updateElementClasses to be called for this element.
1749 * @localdoc QUnit tests override this method to directly call #queueUpdateElementClasses,
1750 * to make them synchronous.
1752 * @param {OO.ui.Element} element Element for which to update classes
1754 OO
.ui
.Theme
.prototype.queueUpdateElementClasses = function ( element
) {
1755 // Keep items in the queue unique. Use lastIndexOf to start checking from the end because that's
1756 // the most common case (this method is often called repeatedly for the same element).
1757 if ( this.elementClassesQueue
.lastIndexOf( element
) !== -1 ) {
1760 this.elementClassesQueue
.push( element
);
1761 this.debouncedUpdateQueuedElementClasses();
1765 * Get the transition duration in milliseconds for dialogs opening/closing
1767 * The dialog should be fully rendered this many milliseconds after the
1768 * ready process has executed.
1770 * @return {number} Transition duration in milliseconds
1772 OO
.ui
.Theme
.prototype.getDialogTransitionDuration = function () {
1777 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
1778 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
1779 * order in which users will navigate through the focusable elements via the "tab" key.
1782 * // TabIndexedElement is mixed into the ButtonWidget class
1783 * // to provide a tabIndex property.
1784 * var button1 = new OO.ui.ButtonWidget( {
1788 * var button2 = new OO.ui.ButtonWidget( {
1792 * var button3 = new OO.ui.ButtonWidget( {
1796 * var button4 = new OO.ui.ButtonWidget( {
1800 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
1806 * @param {Object} [config] Configuration options
1807 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
1808 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
1809 * functionality will be applied to it instead.
1810 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
1811 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
1812 * to remove the element from the tab-navigation flow.
1814 OO
.ui
.mixin
.TabIndexedElement
= function OoUiMixinTabIndexedElement( config
) {
1815 // Configuration initialization
1816 config
= $.extend( { tabIndex
: 0 }, config
);
1819 this.$tabIndexed
= null;
1820 this.tabIndex
= null;
1823 this.connect( this, { disable
: 'onTabIndexedElementDisable' } );
1826 this.setTabIndex( config
.tabIndex
);
1827 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
1832 OO
.initClass( OO
.ui
.mixin
.TabIndexedElement
);
1837 * Set the element that should use the tabindex functionality.
1839 * This method is used to retarget a tabindex mixin so that its functionality applies
1840 * to the specified element. If an element is currently using the functionality, the mixin’s
1841 * effect on that element is removed before the new element is set up.
1843 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
1846 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
1847 var tabIndex
= this.tabIndex
;
1848 // Remove attributes from old $tabIndexed
1849 this.setTabIndex( null );
1850 // Force update of new $tabIndexed
1851 this.$tabIndexed
= $tabIndexed
;
1852 this.tabIndex
= tabIndex
;
1853 return this.updateTabIndex();
1857 * Set the value of the tabindex.
1859 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
1862 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
1863 tabIndex
= typeof tabIndex
=== 'number' ? tabIndex
: null;
1865 if ( this.tabIndex
!== tabIndex
) {
1866 this.tabIndex
= tabIndex
;
1867 this.updateTabIndex();
1874 * Update the `tabindex` attribute, in case of changes to tab index or
1880 OO
.ui
.mixin
.TabIndexedElement
.prototype.updateTabIndex = function () {
1881 if ( this.$tabIndexed
) {
1882 if ( this.tabIndex
!== null ) {
1883 // Do not index over disabled elements
1884 this.$tabIndexed
.attr( {
1885 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
1886 // Support: ChromeVox and NVDA
1887 // These do not seem to inherit aria-disabled from parent elements
1888 'aria-disabled': this.isDisabled().toString()
1891 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
1898 * Handle disable events.
1901 * @param {boolean} disabled Element is disabled
1903 OO
.ui
.mixin
.TabIndexedElement
.prototype.onTabIndexedElementDisable = function () {
1904 this.updateTabIndex();
1908 * Get the value of the tabindex.
1910 * @return {number|null} Tabindex value
1912 OO
.ui
.mixin
.TabIndexedElement
.prototype.getTabIndex = function () {
1913 return this.tabIndex
;
1917 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
1918 * interface element that can be configured with access keys for accessibility.
1919 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
1921 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
1927 * @param {Object} [config] Configuration options
1928 * @cfg {jQuery} [$button] The button element created by the class.
1929 * If this configuration is omitted, the button element will use a generated `<a>`.
1930 * @cfg {boolean} [framed=true] Render the button with a frame
1932 OO
.ui
.mixin
.ButtonElement
= function OoUiMixinButtonElement( config
) {
1933 // Configuration initialization
1934 config
= config
|| {};
1937 this.$button
= null;
1939 this.active
= config
.active
!== undefined && config
.active
;
1940 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
1941 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
1942 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
1943 this.onKeyUpHandler
= this.onKeyUp
.bind( this );
1944 this.onClickHandler
= this.onClick
.bind( this );
1945 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
1948 this.$element
.addClass( 'oo-ui-buttonElement' );
1949 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
1950 this.setButtonElement( config
.$button
|| $( '<a>' ) );
1955 OO
.initClass( OO
.ui
.mixin
.ButtonElement
);
1957 /* Static Properties */
1960 * Cancel mouse down events.
1962 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
1963 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
1964 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
1969 * @property {boolean}
1971 OO
.ui
.mixin
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
1976 * A 'click' event is emitted when the button element is clicked.
1984 * Set the button element.
1986 * This method is used to retarget a button mixin so that its functionality applies to
1987 * the specified button element instead of the one created by the class. If a button element
1988 * is already set, the method will remove the mixin’s effect on that element.
1990 * @param {jQuery} $button Element to use as button
1992 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
1993 if ( this.$button
) {
1995 .removeClass( 'oo-ui-buttonElement-button' )
1996 .removeAttr( 'role accesskey' )
1998 mousedown
: this.onMouseDownHandler
,
1999 keydown
: this.onKeyDownHandler
,
2000 click
: this.onClickHandler
,
2001 keypress
: this.onKeyPressHandler
2005 this.$button
= $button
2006 .addClass( 'oo-ui-buttonElement-button' )
2008 mousedown
: this.onMouseDownHandler
,
2009 keydown
: this.onKeyDownHandler
,
2010 click
: this.onClickHandler
,
2011 keypress
: this.onKeyPressHandler
2014 // Add `role="button"` on `<a>` elements, where it's needed
2015 // `toUppercase()` is added for XHTML documents
2016 if ( this.$button
.prop( 'tagName' ).toUpperCase() === 'A' ) {
2017 this.$button
.attr( 'role', 'button' );
2022 * Handles mouse down events.
2025 * @param {jQuery.Event} e Mouse down event
2027 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown = function ( e
) {
2028 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
2031 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
2032 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
2033 // reliably remove the pressed class
2034 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
2035 // Prevent change of focus unless specifically configured otherwise
2036 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
2042 * Handles mouse up events.
2045 * @param {MouseEvent} e Mouse up event
2047 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp = function ( e
) {
2048 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
2051 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
2052 // Stop listening for mouseup, since we only needed this once
2053 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
2057 * Handles mouse click events.
2060 * @param {jQuery.Event} e Mouse click event
2063 OO
.ui
.mixin
.ButtonElement
.prototype.onClick = function ( e
) {
2064 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
2065 if ( this.emit( 'click' ) ) {
2072 * Handles key down events.
2075 * @param {jQuery.Event} e Key down event
2077 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyDown = function ( e
) {
2078 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
2081 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
2082 // Run the keyup handler no matter where the key is when the button is let go, so we can
2083 // reliably remove the pressed class
2084 this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler
, true );
2088 * Handles key up events.
2091 * @param {KeyboardEvent} e Key up event
2093 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyUp = function ( e
) {
2094 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
2097 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
2098 // Stop listening for keyup, since we only needed this once
2099 this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler
, true );
2103 * Handles key press events.
2106 * @param {jQuery.Event} e Key press event
2109 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyPress = function ( e
) {
2110 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
2111 if ( this.emit( 'click' ) ) {
2118 * Check if button has a frame.
2120 * @return {boolean} Button is framed
2122 OO
.ui
.mixin
.ButtonElement
.prototype.isFramed = function () {
2127 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
2129 * @param {boolean} [framed] Make button framed, omit to toggle
2132 OO
.ui
.mixin
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
2133 framed
= framed
=== undefined ? !this.framed
: !!framed
;
2134 if ( framed
!== this.framed
) {
2135 this.framed
= framed
;
2137 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
2138 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
2139 this.updateThemeClasses();
2146 * Set the button's active state.
2148 * The active state can be set on:
2150 * - {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} when it is selected
2151 * - {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} when it is toggle on
2152 * - {@link OO.ui.ButtonWidget ButtonWidget} when clicking the button would only refresh the page
2155 * @param {boolean} value Make button active
2158 OO
.ui
.mixin
.ButtonElement
.prototype.setActive = function ( value
) {
2159 this.active
= !!value
;
2160 this.$element
.toggleClass( 'oo-ui-buttonElement-active', this.active
);
2161 this.updateThemeClasses();
2166 * Check if the button is active
2169 * @return {boolean} The button is active
2171 OO
.ui
.mixin
.ButtonElement
.prototype.isActive = function () {
2176 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
2177 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
2178 * items from the group is done through the interface the class provides.
2179 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2181 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
2187 * @param {Object} [config] Configuration options
2188 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
2189 * is omitted, the group element will use a generated `<div>`.
2191 OO
.ui
.mixin
.GroupElement
= function OoUiMixinGroupElement( config
) {
2192 // Configuration initialization
2193 config
= config
|| {};
2198 this.aggregateItemEvents
= {};
2201 this.setGroupElement( config
.$group
|| $( '<div>' ) );
2209 * A change event is emitted when the set of selected items changes.
2211 * @param {OO.ui.Element[]} items Items currently in the group
2217 * Set the group element.
2219 * If an element is already set, items will be moved to the new element.
2221 * @param {jQuery} $group Element to use as group
2223 OO
.ui
.mixin
.GroupElement
.prototype.setGroupElement = function ( $group
) {
2226 this.$group
= $group
;
2227 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2228 this.$group
.append( this.items
[ i
].$element
);
2233 * Check if a group contains no items.
2235 * @return {boolean} Group is empty
2237 OO
.ui
.mixin
.GroupElement
.prototype.isEmpty = function () {
2238 return !this.items
.length
;
2242 * Get all items in the group.
2244 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
2245 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
2248 * @return {OO.ui.Element[]} An array of items.
2250 OO
.ui
.mixin
.GroupElement
.prototype.getItems = function () {
2251 return this.items
.slice( 0 );
2255 * Get an item by its data.
2257 * Only the first item with matching data will be returned. To return all matching items,
2258 * use the #getItemsFromData method.
2260 * @param {Object} data Item data to search for
2261 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
2263 OO
.ui
.mixin
.GroupElement
.prototype.getItemFromData = function ( data
) {
2265 hash
= OO
.getHash( data
);
2267 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2268 item
= this.items
[ i
];
2269 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2278 * Get items by their data.
2280 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
2282 * @param {Object} data Item data to search for
2283 * @return {OO.ui.Element[]} Items with equivalent data
2285 OO
.ui
.mixin
.GroupElement
.prototype.getItemsFromData = function ( data
) {
2287 hash
= OO
.getHash( data
),
2290 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2291 item
= this.items
[ i
];
2292 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2301 * Aggregate the events emitted by the group.
2303 * When events are aggregated, the group will listen to all contained items for the event,
2304 * and then emit the event under a new name. The new event will contain an additional leading
2305 * parameter containing the item that emitted the original event. Other arguments emitted from
2306 * the original event are passed through.
2308 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
2309 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
2310 * A `null` value will remove aggregated events.
2312 * @throws {Error} An error is thrown if aggregation already exists.
2314 OO
.ui
.mixin
.GroupElement
.prototype.aggregate = function ( events
) {
2315 var i
, len
, item
, add
, remove
, itemEvent
, groupEvent
;
2317 for ( itemEvent
in events
) {
2318 groupEvent
= events
[ itemEvent
];
2320 // Remove existing aggregated event
2321 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
2322 // Don't allow duplicate aggregations
2324 throw new Error( 'Duplicate item event aggregation for ' + itemEvent
);
2326 // Remove event aggregation from existing items
2327 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2328 item
= this.items
[ i
];
2329 if ( item
.connect
&& item
.disconnect
) {
2331 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
2332 item
.disconnect( this, remove
);
2335 // Prevent future items from aggregating event
2336 delete this.aggregateItemEvents
[ itemEvent
];
2339 // Add new aggregate event
2341 // Make future items aggregate event
2342 this.aggregateItemEvents
[ itemEvent
] = groupEvent
;
2343 // Add event aggregation to existing items
2344 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2345 item
= this.items
[ i
];
2346 if ( item
.connect
&& item
.disconnect
) {
2348 add
[ itemEvent
] = [ 'emit', groupEvent
, item
];
2349 item
.connect( this, add
);
2357 * Add items to the group.
2359 * Items will be added to the end of the group array unless the optional `index` parameter specifies
2360 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
2362 * @param {OO.ui.Element[]} items An array of items to add to the group
2363 * @param {number} [index] Index of the insertion point
2366 OO
.ui
.mixin
.GroupElement
.prototype.addItems = function ( items
, index
) {
2367 var i
, len
, item
, itemEvent
, events
, currentIndex
,
2370 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
2373 // Check if item exists then remove it first, effectively "moving" it
2374 currentIndex
= this.items
.indexOf( item
);
2375 if ( currentIndex
>= 0 ) {
2376 this.removeItems( [ item
] );
2377 // Adjust index to compensate for removal
2378 if ( currentIndex
< index
) {
2383 if ( item
.connect
&& item
.disconnect
&& !$.isEmptyObject( this.aggregateItemEvents
) ) {
2385 for ( itemEvent
in this.aggregateItemEvents
) {
2386 events
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
2388 item
.connect( this, events
);
2390 item
.setElementGroup( this );
2391 itemElements
.push( item
.$element
.get( 0 ) );
2394 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
2395 this.$group
.append( itemElements
);
2396 this.items
.push
.apply( this.items
, items
);
2397 } else if ( index
=== 0 ) {
2398 this.$group
.prepend( itemElements
);
2399 this.items
.unshift
.apply( this.items
, items
);
2401 this.items
[ index
].$element
.before( itemElements
);
2402 this.items
.splice
.apply( this.items
, [ index
, 0 ].concat( items
) );
2405 this.emit( 'change', this.getItems() );
2410 * Remove the specified items from a group.
2412 * Removed items are detached (not removed) from the DOM so that they may be reused.
2413 * To remove all items from a group, you may wish to use the #clearItems method instead.
2415 * @param {OO.ui.Element[]} items An array of items to remove
2418 OO
.ui
.mixin
.GroupElement
.prototype.removeItems = function ( items
) {
2419 var i
, len
, item
, index
, events
, itemEvent
;
2421 // Remove specific items
2422 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
2424 index
= this.items
.indexOf( item
);
2425 if ( index
!== -1 ) {
2426 if ( item
.connect
&& item
.disconnect
&& !$.isEmptyObject( this.aggregateItemEvents
) ) {
2428 for ( itemEvent
in this.aggregateItemEvents
) {
2429 events
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
2431 item
.disconnect( this, events
);
2433 item
.setElementGroup( null );
2434 this.items
.splice( index
, 1 );
2435 item
.$element
.detach();
2439 this.emit( 'change', this.getItems() );
2444 * Clear all items from the group.
2446 * Cleared items are detached from the DOM, not removed, so that they may be reused.
2447 * To remove only a subset of items from a group, use the #removeItems method.
2451 OO
.ui
.mixin
.GroupElement
.prototype.clearItems = function () {
2452 var i
, len
, item
, remove
, itemEvent
;
2455 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2456 item
= this.items
[ i
];
2458 item
.connect
&& item
.disconnect
&&
2459 !$.isEmptyObject( this.aggregateItemEvents
)
2462 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
2463 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
2465 item
.disconnect( this, remove
);
2467 item
.setElementGroup( null );
2468 item
.$element
.detach();
2471 this.emit( 'change', this.getItems() );
2477 * IconElement is often mixed into other classes to generate an icon.
2478 * Icons are graphics, about the size of normal text. They are used to aid the user
2479 * in locating a control or to convey information in a space-efficient way. See the
2480 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
2481 * included in the library.
2483 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
2489 * @param {Object} [config] Configuration options
2490 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
2491 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
2492 * the icon element be set to an existing icon instead of the one generated by this class, set a
2493 * value using a jQuery selection. For example:
2495 * // Use a <div> tag instead of a <span>
2497 * // Use an existing icon element instead of the one generated by the class
2498 * $icon: this.$element
2499 * // Use an icon element from a child widget
2500 * $icon: this.childwidget.$element
2501 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
2502 * symbolic names. A map is used for i18n purposes and contains a `default` icon
2503 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
2504 * by the user's language.
2506 * Example of an i18n map:
2508 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2509 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
2510 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
2511 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
2512 * text. The icon title is displayed when users move the mouse over the icon.
2514 OO
.ui
.mixin
.IconElement
= function OoUiMixinIconElement( config
) {
2515 // Configuration initialization
2516 config
= config
|| {};
2521 this.iconTitle
= null;
2524 this.setIcon( config
.icon
|| this.constructor.static.icon
);
2525 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
2526 this.setIconElement( config
.$icon
|| $( '<span>' ) );
2531 OO
.initClass( OO
.ui
.mixin
.IconElement
);
2533 /* Static Properties */
2536 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
2537 * for i18n purposes and contains a `default` icon name and additional names keyed by
2538 * language code. The `default` name is used when no icon is keyed by the user's language.
2540 * Example of an i18n map:
2542 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2544 * Note: the static property will be overridden if the #icon configuration is used.
2548 * @property {Object|string}
2550 OO
.ui
.mixin
.IconElement
.static.icon
= null;
2553 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
2554 * function that returns title text, or `null` for no title.
2556 * The static property will be overridden if the #iconTitle configuration is used.
2560 * @property {string|Function|null}
2562 OO
.ui
.mixin
.IconElement
.static.iconTitle
= null;
2567 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
2568 * applies to the specified icon element instead of the one created by the class. If an icon
2569 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
2570 * and mixin methods will no longer affect the element.
2572 * @param {jQuery} $icon Element to use as icon
2574 OO
.ui
.mixin
.IconElement
.prototype.setIconElement = function ( $icon
) {
2577 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
2578 .removeAttr( 'title' );
2582 .addClass( 'oo-ui-iconElement-icon' )
2583 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
2584 if ( this.iconTitle
!== null ) {
2585 this.$icon
.attr( 'title', this.iconTitle
);
2588 this.updateThemeClasses();
2592 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
2593 * The icon parameter can also be set to a map of icon names. See the #icon config setting
2596 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
2597 * by language code, or `null` to remove the icon.
2600 OO
.ui
.mixin
.IconElement
.prototype.setIcon = function ( icon
) {
2601 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
2602 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
2604 if ( this.icon
!== icon
) {
2606 if ( this.icon
!== null ) {
2607 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
2609 if ( icon
!== null ) {
2610 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
2616 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
2617 this.updateThemeClasses();
2623 * Set the icon title. Use `null` to remove the title.
2625 * @param {string|Function|null} iconTitle A text string used as the icon title,
2626 * a function that returns title text, or `null` for no title.
2629 OO
.ui
.mixin
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
2630 iconTitle
= typeof iconTitle
=== 'function' ||
2631 ( typeof iconTitle
=== 'string' && iconTitle
.length
) ?
2632 OO
.ui
.resolveMsg( iconTitle
) : null;
2634 if ( this.iconTitle
!== iconTitle
) {
2635 this.iconTitle
= iconTitle
;
2637 if ( this.iconTitle
!== null ) {
2638 this.$icon
.attr( 'title', iconTitle
);
2640 this.$icon
.removeAttr( 'title' );
2649 * Get the symbolic name of the icon.
2651 * @return {string} Icon name
2653 OO
.ui
.mixin
.IconElement
.prototype.getIcon = function () {
2658 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
2660 * @return {string} Icon title text
2662 OO
.ui
.mixin
.IconElement
.prototype.getIconTitle = function () {
2663 return this.iconTitle
;
2667 * IndicatorElement is often mixed into other classes to generate an indicator.
2668 * Indicators are small graphics that are generally used in two ways:
2670 * - To draw attention to the status of an item. For example, an indicator might be
2671 * used to show that an item in a list has errors that need to be resolved.
2672 * - To clarify the function of a control that acts in an exceptional way (a button
2673 * that opens a menu instead of performing an action directly, for example).
2675 * For a list of indicators included in the library, please see the
2676 * [OOjs UI documentation on MediaWiki] [1].
2678 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2684 * @param {Object} [config] Configuration options
2685 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
2686 * configuration is omitted, the indicator element will use a generated `<span>`.
2687 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2688 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
2690 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2691 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
2692 * or a function that returns title text. The indicator title is displayed when users move
2693 * the mouse over the indicator.
2695 OO
.ui
.mixin
.IndicatorElement
= function OoUiMixinIndicatorElement( config
) {
2696 // Configuration initialization
2697 config
= config
|| {};
2700 this.$indicator
= null;
2701 this.indicator
= null;
2702 this.indicatorTitle
= null;
2705 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
2706 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
2707 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
2712 OO
.initClass( OO
.ui
.mixin
.IndicatorElement
);
2714 /* Static Properties */
2717 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2718 * The static property will be overridden if the #indicator configuration is used.
2722 * @property {string|null}
2724 OO
.ui
.mixin
.IndicatorElement
.static.indicator
= null;
2727 * A text string used as the indicator title, a function that returns title text, or `null`
2728 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
2732 * @property {string|Function|null}
2734 OO
.ui
.mixin
.IndicatorElement
.static.indicatorTitle
= null;
2739 * Set the indicator element.
2741 * If an element is already set, it will be cleaned up before setting up the new element.
2743 * @param {jQuery} $indicator Element to use as indicator
2745 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
2746 if ( this.$indicator
) {
2748 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
2749 .removeAttr( 'title' );
2752 this.$indicator
= $indicator
2753 .addClass( 'oo-ui-indicatorElement-indicator' )
2754 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
2755 if ( this.indicatorTitle
!== null ) {
2756 this.$indicator
.attr( 'title', this.indicatorTitle
);
2759 this.updateThemeClasses();
2763 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
2765 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
2768 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
2769 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
2771 if ( this.indicator
!== indicator
) {
2772 if ( this.$indicator
) {
2773 if ( this.indicator
!== null ) {
2774 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
2776 if ( indicator
!== null ) {
2777 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
2780 this.indicator
= indicator
;
2783 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
2784 this.updateThemeClasses();
2790 * Set the indicator title.
2792 * The title is displayed when a user moves the mouse over the indicator.
2794 * @param {string|Function|null} indicatorTitle Indicator title text, a function that returns text, or
2795 * `null` for no indicator title
2798 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorTitle = function ( indicatorTitle
) {
2799 indicatorTitle
= typeof indicatorTitle
=== 'function' ||
2800 ( typeof indicatorTitle
=== 'string' && indicatorTitle
.length
) ?
2801 OO
.ui
.resolveMsg( indicatorTitle
) : null;
2803 if ( this.indicatorTitle
!== indicatorTitle
) {
2804 this.indicatorTitle
= indicatorTitle
;
2805 if ( this.$indicator
) {
2806 if ( this.indicatorTitle
!== null ) {
2807 this.$indicator
.attr( 'title', indicatorTitle
);
2809 this.$indicator
.removeAttr( 'title' );
2818 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2820 * @return {string} Symbolic name of indicator
2822 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicator = function () {
2823 return this.indicator
;
2827 * Get the indicator title.
2829 * The title is displayed when a user moves the mouse over the indicator.
2831 * @return {string} Indicator title text
2833 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicatorTitle = function () {
2834 return this.indicatorTitle
;
2838 * LabelElement is often mixed into other classes to generate a label, which
2839 * helps identify the function of an interface element.
2840 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
2842 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
2848 * @param {Object} [config] Configuration options
2849 * @cfg {jQuery} [$label] The label element created by the class. If this
2850 * configuration is omitted, the label element will use a generated `<span>`.
2851 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
2852 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
2853 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
2854 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
2856 OO
.ui
.mixin
.LabelElement
= function OoUiMixinLabelElement( config
) {
2857 // Configuration initialization
2858 config
= config
|| {};
2865 this.setLabel( config
.label
|| this.constructor.static.label
);
2866 this.setLabelElement( config
.$label
|| $( '<span>' ) );
2871 OO
.initClass( OO
.ui
.mixin
.LabelElement
);
2876 * @event labelChange
2877 * @param {string} value
2880 /* Static Properties */
2883 * The label text. The label can be specified as a plaintext string, a function that will
2884 * produce a string in the future, or `null` for no label. The static value will
2885 * be overridden if a label is specified with the #label config option.
2889 * @property {string|Function|null}
2891 OO
.ui
.mixin
.LabelElement
.static.label
= null;
2893 /* Static methods */
2896 * Highlight the first occurrence of the query in the given text
2898 * @param {string} text Text
2899 * @param {string} query Query to find
2900 * @return {jQuery} Text with the first match of the query
2901 * sub-string wrapped in highlighted span
2903 OO
.ui
.mixin
.LabelElement
.static.highlightQuery = function ( text
, query
) {
2904 var $result
= $( '<span>' ),
2905 offset
= text
.toLowerCase().indexOf( query
.toLowerCase() );
2907 if ( !query
.length
|| offset
=== -1 ) {
2908 return $result
.text( text
);
2911 document
.createTextNode( text
.slice( 0, offset
) ),
2913 .addClass( 'oo-ui-labelElement-label-highlight' )
2914 .text( text
.slice( offset
, offset
+ query
.length
) ),
2915 document
.createTextNode( text
.slice( offset
+ query
.length
) )
2917 return $result
.contents();
2923 * Set the label element.
2925 * If an element is already set, it will be cleaned up before setting up the new element.
2927 * @param {jQuery} $label Element to use as label
2929 OO
.ui
.mixin
.LabelElement
.prototype.setLabelElement = function ( $label
) {
2930 if ( this.$label
) {
2931 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
2934 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
2935 this.setLabelContent( this.label
);
2941 * An empty string will result in the label being hidden. A string containing only whitespace will
2942 * be converted to a single ` `.
2944 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
2945 * text; or null for no label
2948 OO
.ui
.mixin
.LabelElement
.prototype.setLabel = function ( label
) {
2949 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
2950 label
= ( ( typeof label
=== 'string' || label
instanceof jQuery
) && label
.length
) || ( label
instanceof OO
.ui
.HtmlSnippet
&& label
.toString().length
) ? label
: null;
2952 if ( this.label
!== label
) {
2953 if ( this.$label
) {
2954 this.setLabelContent( label
);
2957 this.emit( 'labelChange' );
2960 this.$element
.toggleClass( 'oo-ui-labelElement', !!this.label
);
2966 * Set the label as plain text with a highlighted query
2968 * @param {string} text Text label to set
2969 * @param {string} query Substring of text to highlight
2972 OO
.ui
.mixin
.LabelElement
.prototype.setHighlightedQuery = function ( text
, query
) {
2973 return this.setLabel( this.constructor.static.highlightQuery( text
, query
) );
2979 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
2980 * text; or null for no label
2982 OO
.ui
.mixin
.LabelElement
.prototype.getLabel = function () {
2987 * Set the content of the label.
2989 * Do not call this method until after the label element has been set by #setLabelElement.
2992 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
2993 * text; or null for no label
2995 OO
.ui
.mixin
.LabelElement
.prototype.setLabelContent = function ( label
) {
2996 if ( typeof label
=== 'string' ) {
2997 if ( label
.match( /^\s*$/ ) ) {
2998 // Convert whitespace only string to a single non-breaking space
2999 this.$label
.html( ' ' );
3001 this.$label
.text( label
);
3003 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
3004 this.$label
.html( label
.toString() );
3005 } else if ( label
instanceof jQuery
) {
3006 this.$label
.empty().append( label
);
3008 this.$label
.empty();
3013 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
3014 * additional functionality to an element created by another class. The class provides
3015 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
3016 * which are used to customize the look and feel of a widget to better describe its
3017 * importance and functionality.
3019 * The library currently contains the following styling flags for general use:
3021 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
3022 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
3023 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
3025 * The flags affect the appearance of the buttons:
3028 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
3029 * var button1 = new OO.ui.ButtonWidget( {
3030 * label: 'Constructive',
3031 * flags: 'constructive'
3033 * var button2 = new OO.ui.ButtonWidget( {
3034 * label: 'Destructive',
3035 * flags: 'destructive'
3037 * var button3 = new OO.ui.ButtonWidget( {
3038 * label: 'Progressive',
3039 * flags: 'progressive'
3041 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
3043 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
3044 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
3046 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
3052 * @param {Object} [config] Configuration options
3053 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
3054 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
3055 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
3056 * @cfg {jQuery} [$flagged] The flagged element. By default,
3057 * the flagged functionality is applied to the element created by the class ($element).
3058 * If a different element is specified, the flagged functionality will be applied to it instead.
3060 OO
.ui
.mixin
.FlaggedElement
= function OoUiMixinFlaggedElement( config
) {
3061 // Configuration initialization
3062 config
= config
|| {};
3066 this.$flagged
= null;
3069 this.setFlags( config
.flags
);
3070 this.setFlaggedElement( config
.$flagged
|| this.$element
);
3077 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
3078 * parameter contains the name of each modified flag and indicates whether it was
3081 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
3082 * that the flag was added, `false` that the flag was removed.
3088 * Set the flagged element.
3090 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
3091 * If an element is already set, the method will remove the mixin’s effect on that element.
3093 * @param {jQuery} $flagged Element that should be flagged
3095 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
3096 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
3097 return 'oo-ui-flaggedElement-' + flag
;
3100 if ( this.$flagged
) {
3101 this.$flagged
.removeClass( classNames
);
3104 this.$flagged
= $flagged
.addClass( classNames
);
3108 * Check if the specified flag is set.
3110 * @param {string} flag Name of flag
3111 * @return {boolean} The flag is set
3113 OO
.ui
.mixin
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
3114 // This may be called before the constructor, thus before this.flags is set
3115 return this.flags
&& ( flag
in this.flags
);
3119 * Get the names of all flags set.
3121 * @return {string[]} Flag names
3123 OO
.ui
.mixin
.FlaggedElement
.prototype.getFlags = function () {
3124 // This may be called before the constructor, thus before this.flags is set
3125 return Object
.keys( this.flags
|| {} );
3134 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags = function () {
3135 var flag
, className
,
3138 classPrefix
= 'oo-ui-flaggedElement-';
3140 for ( flag
in this.flags
) {
3141 className
= classPrefix
+ flag
;
3142 changes
[ flag
] = false;
3143 delete this.flags
[ flag
];
3144 remove
.push( className
);
3147 if ( this.$flagged
) {
3148 this.$flagged
.removeClass( remove
.join( ' ' ) );
3151 this.updateThemeClasses();
3152 this.emit( 'flag', changes
);
3158 * Add one or more flags.
3160 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
3161 * or an object keyed by flag name with a boolean value that indicates whether the flag should
3162 * be added (`true`) or removed (`false`).
3166 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags = function ( flags
) {
3167 var i
, len
, flag
, className
,
3171 classPrefix
= 'oo-ui-flaggedElement-';
3173 if ( typeof flags
=== 'string' ) {
3174 className
= classPrefix
+ flags
;
3176 if ( !this.flags
[ flags
] ) {
3177 this.flags
[ flags
] = true;
3178 add
.push( className
);
3180 } else if ( Array
.isArray( flags
) ) {
3181 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
3183 className
= classPrefix
+ flag
;
3185 if ( !this.flags
[ flag
] ) {
3186 changes
[ flag
] = true;
3187 this.flags
[ flag
] = true;
3188 add
.push( className
);
3191 } else if ( OO
.isPlainObject( flags
) ) {
3192 for ( flag
in flags
) {
3193 className
= classPrefix
+ flag
;
3194 if ( flags
[ flag
] ) {
3196 if ( !this.flags
[ flag
] ) {
3197 changes
[ flag
] = true;
3198 this.flags
[ flag
] = true;
3199 add
.push( className
);
3203 if ( this.flags
[ flag
] ) {
3204 changes
[ flag
] = false;
3205 delete this.flags
[ flag
];
3206 remove
.push( className
);
3212 if ( this.$flagged
) {
3214 .addClass( add
.join( ' ' ) )
3215 .removeClass( remove
.join( ' ' ) );
3218 this.updateThemeClasses();
3219 this.emit( 'flag', changes
);
3225 * TitledElement is mixed into other classes to provide a `title` attribute.
3226 * Titles are rendered by the browser and are made visible when the user moves
3227 * the mouse over the element. Titles are not visible on touch devices.
3230 * // TitledElement provides a 'title' attribute to the
3231 * // ButtonWidget class
3232 * var button = new OO.ui.ButtonWidget( {
3233 * label: 'Button with Title',
3234 * title: 'I am a button'
3236 * $( 'body' ).append( button.$element );
3242 * @param {Object} [config] Configuration options
3243 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
3244 * If this config is omitted, the title functionality is applied to $element, the
3245 * element created by the class.
3246 * @cfg {string|Function} [title] The title text or a function that returns text. If
3247 * this config is omitted, the value of the {@link #static-title static title} property is used.
3249 OO
.ui
.mixin
.TitledElement
= function OoUiMixinTitledElement( config
) {
3250 // Configuration initialization
3251 config
= config
|| {};
3254 this.$titled
= null;
3258 this.setTitle( config
.title
!== undefined ? config
.title
: this.constructor.static.title
);
3259 this.setTitledElement( config
.$titled
|| this.$element
);
3264 OO
.initClass( OO
.ui
.mixin
.TitledElement
);
3266 /* Static Properties */
3269 * The title text, a function that returns text, or `null` for no title. The value of the static property
3270 * is overridden if the #title config option is used.
3274 * @property {string|Function|null}
3276 OO
.ui
.mixin
.TitledElement
.static.title
= null;
3281 * Set the titled element.
3283 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
3284 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
3286 * @param {jQuery} $titled Element that should use the 'titled' functionality
3288 OO
.ui
.mixin
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
3289 if ( this.$titled
) {
3290 this.$titled
.removeAttr( 'title' );
3293 this.$titled
= $titled
;
3295 this.$titled
.attr( 'title', this.title
);
3302 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
3305 OO
.ui
.mixin
.TitledElement
.prototype.setTitle = function ( title
) {
3306 title
= typeof title
=== 'function' ? OO
.ui
.resolveMsg( title
) : title
;
3307 title
= ( typeof title
=== 'string' && title
.length
) ? title
: null;
3309 if ( this.title
!== title
) {
3310 if ( this.$titled
) {
3311 if ( title
!== null ) {
3312 this.$titled
.attr( 'title', title
);
3314 this.$titled
.removeAttr( 'title' );
3326 * @return {string} Title string
3328 OO
.ui
.mixin
.TitledElement
.prototype.getTitle = function () {
3333 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
3334 * Accesskeys allow an user to go to a specific element by using
3335 * a shortcut combination of a browser specific keys + the key
3339 * // AccessKeyedElement provides an 'accesskey' attribute to the
3340 * // ButtonWidget class
3341 * var button = new OO.ui.ButtonWidget( {
3342 * label: 'Button with Accesskey',
3345 * $( 'body' ).append( button.$element );
3351 * @param {Object} [config] Configuration options
3352 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
3353 * If this config is omitted, the accesskey functionality is applied to $element, the
3354 * element created by the class.
3355 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
3356 * this config is omitted, no accesskey will be added.
3358 OO
.ui
.mixin
.AccessKeyedElement
= function OoUiMixinAccessKeyedElement( config
) {
3359 // Configuration initialization
3360 config
= config
|| {};
3363 this.$accessKeyed
= null;
3364 this.accessKey
= null;
3367 this.setAccessKey( config
.accessKey
|| null );
3368 this.setAccessKeyedElement( config
.$accessKeyed
|| this.$element
);
3373 OO
.initClass( OO
.ui
.mixin
.AccessKeyedElement
);
3375 /* Static Properties */
3378 * The access key, a function that returns a key, or `null` for no accesskey.
3382 * @property {string|Function|null}
3384 OO
.ui
.mixin
.AccessKeyedElement
.static.accessKey
= null;
3389 * Set the accesskeyed element.
3391 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
3392 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
3394 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
3396 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKeyedElement = function ( $accessKeyed
) {
3397 if ( this.$accessKeyed
) {
3398 this.$accessKeyed
.removeAttr( 'accesskey' );
3401 this.$accessKeyed
= $accessKeyed
;
3402 if ( this.accessKey
) {
3403 this.$accessKeyed
.attr( 'accesskey', this.accessKey
);
3410 * @param {string|Function|null} accessKey Key, a function that returns a key, or `null` for no accesskey
3413 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKey = function ( accessKey
) {
3414 accessKey
= typeof accessKey
=== 'string' ? OO
.ui
.resolveMsg( accessKey
) : null;
3416 if ( this.accessKey
!== accessKey
) {
3417 if ( this.$accessKeyed
) {
3418 if ( accessKey
!== null ) {
3419 this.$accessKeyed
.attr( 'accesskey', accessKey
);
3421 this.$accessKeyed
.removeAttr( 'accesskey' );
3424 this.accessKey
= accessKey
;
3433 * @return {string} accessKey string
3435 OO
.ui
.mixin
.AccessKeyedElement
.prototype.getAccessKey = function () {
3436 return this.accessKey
;
3440 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
3441 * feels, and functionality can be customized via the class’s configuration options
3442 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
3445 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
3448 * // A button widget
3449 * var button = new OO.ui.ButtonWidget( {
3450 * label: 'Button with Icon',
3452 * iconTitle: 'Remove'
3454 * $( 'body' ).append( button.$element );
3456 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
3459 * @extends OO.ui.Widget
3460 * @mixins OO.ui.mixin.ButtonElement
3461 * @mixins OO.ui.mixin.IconElement
3462 * @mixins OO.ui.mixin.IndicatorElement
3463 * @mixins OO.ui.mixin.LabelElement
3464 * @mixins OO.ui.mixin.TitledElement
3465 * @mixins OO.ui.mixin.FlaggedElement
3466 * @mixins OO.ui.mixin.TabIndexedElement
3467 * @mixins OO.ui.mixin.AccessKeyedElement
3470 * @param {Object} [config] Configuration options
3471 * @cfg {boolean} [active=false] Whether button should be shown as active
3472 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
3473 * @cfg {string} [target] The frame or window in which to open the hyperlink.
3474 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
3476 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
3477 // Configuration initialization
3478 config
= config
|| {};
3480 // Parent constructor
3481 OO
.ui
.ButtonWidget
.parent
.call( this, config
);
3483 // Mixin constructors
3484 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
3485 OO
.ui
.mixin
.IconElement
.call( this, config
);
3486 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
3487 OO
.ui
.mixin
.LabelElement
.call( this, config
);
3488 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
3489 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
3490 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
3491 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$button
} ) );
3496 this.noFollow
= false;
3499 this.connect( this, { disable
: 'onDisable' } );
3502 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
3504 .addClass( 'oo-ui-buttonWidget' )
3505 .append( this.$button
);
3506 this.setActive( config
.active
);
3507 this.setHref( config
.href
);
3508 this.setTarget( config
.target
);
3509 this.setNoFollow( config
.noFollow
);
3514 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
3515 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
3516 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IconElement
);
3517 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
3518 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.LabelElement
);
3519 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TitledElement
);
3520 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
3521 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
3522 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
3524 /* Static Properties */
3530 OO
.ui
.ButtonWidget
.static.cancelButtonMouseDownEvents
= false;
3536 OO
.ui
.ButtonWidget
.static.tagName
= 'span';
3541 * Get hyperlink location.
3543 * @return {string} Hyperlink location
3545 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
3550 * Get hyperlink target.
3552 * @return {string} Hyperlink target
3554 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
3559 * Get search engine traversal hint.
3561 * @return {boolean} Whether search engines should avoid traversing this hyperlink
3563 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
3564 return this.noFollow
;
3568 * Set hyperlink location.
3570 * @param {string|null} href Hyperlink location, null to remove
3572 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
3573 href
= typeof href
=== 'string' ? href
: null;
3574 if ( href
!== null && !OO
.ui
.isSafeUrl( href
) ) {
3578 if ( href
!== this.href
) {
3587 * Update the `href` attribute, in case of changes to href or
3593 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
3594 if ( this.href
!== null && !this.isDisabled() ) {
3595 this.$button
.attr( 'href', this.href
);
3597 this.$button
.removeAttr( 'href' );
3604 * Handle disable events.
3607 * @param {boolean} disabled Element is disabled
3609 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
3614 * Set hyperlink target.
3616 * @param {string|null} target Hyperlink target, null to remove
3618 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
3619 target
= typeof target
=== 'string' ? target
: null;
3621 if ( target
!== this.target
) {
3622 this.target
= target
;
3623 if ( target
!== null ) {
3624 this.$button
.attr( 'target', target
);
3626 this.$button
.removeAttr( 'target' );
3634 * Set search engine traversal hint.
3636 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
3638 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
3639 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
3641 if ( noFollow
!== this.noFollow
) {
3642 this.noFollow
= noFollow
;
3644 this.$button
.attr( 'rel', 'nofollow' );
3646 this.$button
.removeAttr( 'rel' );
3653 // Override method visibility hints from ButtonElement
3662 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
3663 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
3664 * removed, and cleared from the group.
3667 * // Example: A ButtonGroupWidget with two buttons
3668 * var button1 = new OO.ui.PopupButtonWidget( {
3669 * label: 'Select a category',
3672 * $content: $( '<p>List of categories...</p>' ),
3677 * var button2 = new OO.ui.ButtonWidget( {
3680 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
3681 * items: [button1, button2]
3683 * $( 'body' ).append( buttonGroup.$element );
3686 * @extends OO.ui.Widget
3687 * @mixins OO.ui.mixin.GroupElement
3690 * @param {Object} [config] Configuration options
3691 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
3693 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
3694 // Configuration initialization
3695 config
= config
|| {};
3697 // Parent constructor
3698 OO
.ui
.ButtonGroupWidget
.parent
.call( this, config
);
3700 // Mixin constructors
3701 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
3704 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
3705 if ( Array
.isArray( config
.items
) ) {
3706 this.addItems( config
.items
);
3712 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
3713 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.GroupElement
);
3715 /* Static Properties */
3721 OO
.ui
.ButtonGroupWidget
.static.tagName
= 'span';
3724 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
3725 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
3726 * for a list of icons included in the library.
3729 * // An icon widget with a label
3730 * var myIcon = new OO.ui.IconWidget( {
3734 * // Create a label.
3735 * var iconLabel = new OO.ui.LabelWidget( {
3738 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
3740 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
3743 * @extends OO.ui.Widget
3744 * @mixins OO.ui.mixin.IconElement
3745 * @mixins OO.ui.mixin.TitledElement
3746 * @mixins OO.ui.mixin.FlaggedElement
3749 * @param {Object} [config] Configuration options
3751 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
3752 // Configuration initialization
3753 config
= config
|| {};
3755 // Parent constructor
3756 OO
.ui
.IconWidget
.parent
.call( this, config
);
3758 // Mixin constructors
3759 OO
.ui
.mixin
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
3760 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
3761 OO
.ui
.mixin
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
3764 this.$element
.addClass( 'oo-ui-iconWidget' );
3769 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
3770 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.IconElement
);
3771 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.TitledElement
);
3772 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.FlaggedElement
);
3774 /* Static Properties */
3780 OO
.ui
.IconWidget
.static.tagName
= 'span';
3783 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
3784 * attention to the status of an item or to clarify the function of a control. For a list of
3785 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
3788 * // Example of an indicator widget
3789 * var indicator1 = new OO.ui.IndicatorWidget( {
3790 * indicator: 'alert'
3793 * // Create a fieldset layout to add a label
3794 * var fieldset = new OO.ui.FieldsetLayout();
3795 * fieldset.addItems( [
3796 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
3798 * $( 'body' ).append( fieldset.$element );
3800 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3803 * @extends OO.ui.Widget
3804 * @mixins OO.ui.mixin.IndicatorElement
3805 * @mixins OO.ui.mixin.TitledElement
3808 * @param {Object} [config] Configuration options
3810 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
3811 // Configuration initialization
3812 config
= config
|| {};
3814 // Parent constructor
3815 OO
.ui
.IndicatorWidget
.parent
.call( this, config
);
3817 // Mixin constructors
3818 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
3819 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
3822 this.$element
.addClass( 'oo-ui-indicatorWidget' );
3827 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
3828 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.IndicatorElement
);
3829 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.TitledElement
);
3831 /* Static Properties */
3837 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
3840 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
3841 * be configured with a `label` option that is set to a string, a label node, or a function:
3843 * - String: a plaintext string
3844 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
3845 * label that includes a link or special styling, such as a gray color or additional graphical elements.
3846 * - Function: a function that will produce a string in the future. Functions are used
3847 * in cases where the value of the label is not currently defined.
3849 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
3850 * will come into focus when the label is clicked.
3853 * // Examples of LabelWidgets
3854 * var label1 = new OO.ui.LabelWidget( {
3855 * label: 'plaintext label'
3857 * var label2 = new OO.ui.LabelWidget( {
3858 * label: $( '<a href="default.html">jQuery label</a>' )
3860 * // Create a fieldset layout with fields for each example
3861 * var fieldset = new OO.ui.FieldsetLayout();
3862 * fieldset.addItems( [
3863 * new OO.ui.FieldLayout( label1 ),
3864 * new OO.ui.FieldLayout( label2 )
3866 * $( 'body' ).append( fieldset.$element );
3869 * @extends OO.ui.Widget
3870 * @mixins OO.ui.mixin.LabelElement
3871 * @mixins OO.ui.mixin.TitledElement
3874 * @param {Object} [config] Configuration options
3875 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
3876 * Clicking the label will focus the specified input field.
3878 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
3879 // Configuration initialization
3880 config
= config
|| {};
3882 // Parent constructor
3883 OO
.ui
.LabelWidget
.parent
.call( this, config
);
3885 // Mixin constructors
3886 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
3887 OO
.ui
.mixin
.TitledElement
.call( this, config
);
3890 this.input
= config
.input
;
3893 if ( this.input
instanceof OO
.ui
.InputWidget
) {
3894 if ( this.input
.getInputId() ) {
3895 this.$element
.attr( 'for', this.input
.getInputId() );
3897 this.$label
.on( 'click', function () {
3898 this.fieldWidget
.focus();
3903 this.$element
.addClass( 'oo-ui-labelWidget' );
3908 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
3909 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.LabelElement
);
3910 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.TitledElement
);
3912 /* Static Properties */
3918 OO
.ui
.LabelWidget
.static.tagName
= 'label';
3921 * PendingElement is a mixin that is used to create elements that notify users that something is happening
3922 * and that they should wait before proceeding. The pending state is visually represented with a pending
3923 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
3924 * field of a {@link OO.ui.TextInputWidget text input widget}.
3926 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
3927 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
3928 * in process dialogs.
3931 * function MessageDialog( config ) {
3932 * MessageDialog.parent.call( this, config );
3934 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
3936 * MessageDialog.static.name = 'myMessageDialog';
3937 * MessageDialog.static.actions = [
3938 * { action: 'save', label: 'Done', flags: 'primary' },
3939 * { label: 'Cancel', flags: 'safe' }
3942 * MessageDialog.prototype.initialize = function () {
3943 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
3944 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
3945 * 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>' );
3946 * this.$body.append( this.content.$element );
3948 * MessageDialog.prototype.getBodyHeight = function () {
3951 * MessageDialog.prototype.getActionProcess = function ( action ) {
3952 * var dialog = this;
3953 * if ( action === 'save' ) {
3954 * dialog.getActions().get({actions: 'save'})[0].pushPending();
3955 * return new OO.ui.Process()
3957 * .next( function () {
3958 * dialog.getActions().get({actions: 'save'})[0].popPending();
3961 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
3964 * var windowManager = new OO.ui.WindowManager();
3965 * $( 'body' ).append( windowManager.$element );
3967 * var dialog = new MessageDialog();
3968 * windowManager.addWindows( [ dialog ] );
3969 * windowManager.openWindow( dialog );
3975 * @param {Object} [config] Configuration options
3976 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
3978 OO
.ui
.mixin
.PendingElement
= function OoUiMixinPendingElement( config
) {
3979 // Configuration initialization
3980 config
= config
|| {};
3984 this.$pending
= null;
3987 this.setPendingElement( config
.$pending
|| this.$element
);
3992 OO
.initClass( OO
.ui
.mixin
.PendingElement
);
3997 * Set the pending element (and clean up any existing one).
3999 * @param {jQuery} $pending The element to set to pending.
4001 OO
.ui
.mixin
.PendingElement
.prototype.setPendingElement = function ( $pending
) {
4002 if ( this.$pending
) {
4003 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
4006 this.$pending
= $pending
;
4007 if ( this.pending
> 0 ) {
4008 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
4013 * Check if an element is pending.
4015 * @return {boolean} Element is pending
4017 OO
.ui
.mixin
.PendingElement
.prototype.isPending = function () {
4018 return !!this.pending
;
4022 * Increase the pending counter. The pending state will remain active until the counter is zero
4023 * (i.e., the number of calls to #pushPending and #popPending is the same).
4027 OO
.ui
.mixin
.PendingElement
.prototype.pushPending = function () {
4028 if ( this.pending
=== 0 ) {
4029 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
4030 this.updateThemeClasses();
4038 * Decrease the pending counter. The pending state will remain active until the counter is zero
4039 * (i.e., the number of calls to #pushPending and #popPending is the same).
4043 OO
.ui
.mixin
.PendingElement
.prototype.popPending = function () {
4044 if ( this.pending
=== 1 ) {
4045 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
4046 this.updateThemeClasses();
4048 this.pending
= Math
.max( 0, this.pending
- 1 );
4054 * Element that will stick adjacent to a specified container, even when it is inserted elsewhere
4055 * in the document (for example, in an OO.ui.Window's $overlay).
4057 * The elements's position is automatically calculated and maintained when window is resized or the
4058 * page is scrolled. If you reposition the container manually, you have to call #position to make
4059 * sure the element is still placed correctly.
4061 * As positioning is only possible when both the element and the container are attached to the DOM
4062 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
4063 * the #toggle method to display a floating popup, for example.
4069 * @param {Object} [config] Configuration options
4070 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
4071 * @cfg {jQuery} [$floatableContainer] Node to position adjacent to
4072 * @cfg {string} [verticalPosition='below'] Where to position $floatable vertically:
4073 * 'below': Directly below $floatableContainer, aligning f's top edge with fC's bottom edge
4074 * 'above': Directly above $floatableContainer, aligning f's bottom edge with fC's top edge
4075 * 'top': Align the top edge with $floatableContainer's top edge
4076 * 'bottom': Align the bottom edge with $floatableContainer's bottom edge
4077 * 'center': Vertically align the center with $floatableContainer's center
4078 * @cfg {string} [horizontalPosition='start'] Where to position $floatable horizontally:
4079 * 'before': Directly before $floatableContainer, aligning f's end edge with fC's start edge
4080 * 'after': Directly after $floatableContainer, algining f's start edge with fC's end edge
4081 * 'start': Align the start (left in LTR, right in RTL) edge with $floatableContainer's start edge
4082 * 'end': Align the end (right in LTR, left in RTL) edge with $floatableContainer's end edge
4083 * 'center': Horizontally align the center with $floatableContainer's center
4084 * @cfg {boolean} [hideWhenOutOfView=true] Whether to hide the floatable element if the container
4087 OO
.ui
.mixin
.FloatableElement
= function OoUiMixinFloatableElement( config
) {
4088 // Configuration initialization
4089 config
= config
|| {};
4092 this.$floatable
= null;
4093 this.$floatableContainer
= null;
4094 this.$floatableWindow
= null;
4095 this.$floatableClosestScrollable
= null;
4096 this.onFloatableScrollHandler
= this.position
.bind( this );
4097 this.onFloatableWindowResizeHandler
= this.position
.bind( this );
4100 this.setFloatableContainer( config
.$floatableContainer
);
4101 this.setFloatableElement( config
.$floatable
|| this.$element
);
4102 this.setVerticalPosition( config
.verticalPosition
|| 'below' );
4103 this.setHorizontalPosition( config
.horizontalPosition
|| 'start' );
4104 this.hideWhenOutOfView
= config
.hideWhenOutOfView
=== undefined ? true : !!config
.hideWhenOutOfView
;
4110 * Set floatable element.
4112 * If an element is already set, it will be cleaned up before setting up the new element.
4114 * @param {jQuery} $floatable Element to make floatable
4116 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableElement = function ( $floatable
) {
4117 if ( this.$floatable
) {
4118 this.$floatable
.removeClass( 'oo-ui-floatableElement-floatable' );
4119 this.$floatable
.css( { left
: '', top
: '' } );
4122 this.$floatable
= $floatable
.addClass( 'oo-ui-floatableElement-floatable' );
4127 * Set floatable container.
4129 * The element will be positioned relative to the specified container.
4131 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
4133 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableContainer = function ( $floatableContainer
) {
4134 this.$floatableContainer
= $floatableContainer
;
4135 if ( this.$floatable
) {
4141 * Change how the element is positioned vertically.
4143 * @param {string} position 'below', 'above', 'top', 'bottom' or 'center'
4145 OO
.ui
.mixin
.FloatableElement
.prototype.setVerticalPosition = function ( position
) {
4146 if ( [ 'below', 'above', 'top', 'bottom', 'center' ].indexOf( position
) === -1 ) {
4147 throw new Error( 'Invalid value for vertical position: ' + position
);
4149 if ( this.verticalPosition
!== position
) {
4150 this.verticalPosition
= position
;
4151 if ( this.$floatable
) {
4158 * Change how the element is positioned horizontally.
4160 * @param {string} position 'before', 'after', 'start', 'end' or 'center'
4162 OO
.ui
.mixin
.FloatableElement
.prototype.setHorizontalPosition = function ( position
) {
4163 if ( [ 'before', 'after', 'start', 'end', 'center' ].indexOf( position
) === -1 ) {
4164 throw new Error( 'Invalid value for horizontal position: ' + position
);
4166 if ( this.horizontalPosition
!== position
) {
4167 this.horizontalPosition
= position
;
4168 if ( this.$floatable
) {
4175 * Toggle positioning.
4177 * Do not turn positioning on until after the element is attached to the DOM and visible.
4179 * @param {boolean} [positioning] Enable positioning, omit to toggle
4182 OO
.ui
.mixin
.FloatableElement
.prototype.togglePositioning = function ( positioning
) {
4183 var closestScrollableOfContainer
;
4185 if ( !this.$floatable
|| !this.$floatableContainer
) {
4189 positioning
= positioning
=== undefined ? !this.positioning
: !!positioning
;
4191 if ( positioning
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
4192 OO
.ui
.warnDeprecation( 'FloatableElement#togglePositioning: Before calling this method, the element must be attached to the DOM.' );
4193 this.warnedUnattached
= true;
4196 if ( this.positioning
!== positioning
) {
4197 this.positioning
= positioning
;
4199 this.needsCustomPosition
=
4200 this.verticalPostion
!== 'below' ||
4201 this.horizontalPosition
!== 'start' ||
4202 !OO
.ui
.contains( this.$floatableContainer
[ 0 ], this.$floatable
[ 0 ] );
4204 closestScrollableOfContainer
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatableContainer
[ 0 ] );
4205 // If the scrollable is the root, we have to listen to scroll events
4206 // on the window because of browser inconsistencies.
4207 if ( $( closestScrollableOfContainer
).is( 'html, body' ) ) {
4208 closestScrollableOfContainer
= OO
.ui
.Element
.static.getWindow( closestScrollableOfContainer
);
4211 if ( positioning
) {
4212 this.$floatableWindow
= $( this.getElementWindow() );
4213 this.$floatableWindow
.on( 'resize', this.onFloatableWindowResizeHandler
);
4215 this.$floatableClosestScrollable
= $( closestScrollableOfContainer
);
4216 this.$floatableClosestScrollable
.on( 'scroll', this.onFloatableScrollHandler
);
4218 // Initial position after visible
4221 if ( this.$floatableWindow
) {
4222 this.$floatableWindow
.off( 'resize', this.onFloatableWindowResizeHandler
);
4223 this.$floatableWindow
= null;
4226 if ( this.$floatableClosestScrollable
) {
4227 this.$floatableClosestScrollable
.off( 'scroll', this.onFloatableScrollHandler
);
4228 this.$floatableClosestScrollable
= null;
4231 this.$floatable
.css( { left
: '', right
: '', top
: '' } );
4239 * Check whether the bottom edge of the given element is within the viewport of the given container.
4242 * @param {jQuery} $element
4243 * @param {jQuery} $container
4246 OO
.ui
.mixin
.FloatableElement
.prototype.isElementInViewport = function ( $element
, $container
) {
4247 var elemRect
, contRect
, topEdgeInBounds
, bottomEdgeInBounds
, leftEdgeInBounds
, rightEdgeInBounds
,
4248 startEdgeInBounds
, endEdgeInBounds
,
4249 direction
= $element
.css( 'direction' );
4251 elemRect
= $element
[ 0 ].getBoundingClientRect();
4252 if ( $container
[ 0 ] === window
) {
4256 right
: document
.documentElement
.clientWidth
,
4257 bottom
: document
.documentElement
.clientHeight
4260 contRect
= $container
[ 0 ].getBoundingClientRect();
4263 topEdgeInBounds
= elemRect
.top
>= contRect
.top
&& elemRect
.top
<= contRect
.bottom
;
4264 bottomEdgeInBounds
= elemRect
.bottom
>= contRect
.top
&& elemRect
.bottom
<= contRect
.bottom
;
4265 leftEdgeInBounds
= elemRect
.left
>= contRect
.left
&& elemRect
.left
<= contRect
.right
;
4266 rightEdgeInBounds
= elemRect
.right
>= contRect
.left
&& elemRect
.right
<= contRect
.right
;
4267 if ( direction
=== 'rtl' ) {
4268 startEdgeInBounds
= rightEdgeInBounds
;
4269 endEdgeInBounds
= leftEdgeInBounds
;
4271 startEdgeInBounds
= leftEdgeInBounds
;
4272 endEdgeInBounds
= rightEdgeInBounds
;
4275 if ( this.verticalPosition
=== 'below' && !bottomEdgeInBounds
) {
4278 if ( this.verticalPosition
=== 'above' && !topEdgeInBounds
) {
4281 if ( this.horizontalPosition
=== 'before' && !startEdgeInBounds
) {
4284 if ( this.horizontalPosition
=== 'after' && !endEdgeInBounds
) {
4288 // The other positioning values are all about being inside the container,
4289 // so in those cases all we care about is that any part of the container is visible.
4290 return elemRect
.top
<= contRect
.bottom
&& elemRect
.bottom
>= contRect
.top
&&
4291 elemRect
.left
<= contRect
.right
&& elemRect
.right
>= contRect
.left
;
4295 * Position the floatable below its container.
4297 * This should only be done when both of them are attached to the DOM and visible.
4301 OO
.ui
.mixin
.FloatableElement
.prototype.position = function () {
4302 if ( !this.positioning
) {
4306 if ( this.hideWhenOutOfView
&& !this.isElementInViewport( this.$floatableContainer
, this.$floatableClosestScrollable
) ) {
4307 this.$floatable
.addClass( 'oo-ui-element-hidden' );
4310 this.$floatable
.removeClass( 'oo-ui-element-hidden' );
4313 if ( !this.needsCustomPosition
) {
4317 this.$floatable
.css( this.computePosition() );
4319 // We updated the position, so re-evaluate the clipping state.
4320 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
4321 // will not notice the need to update itself.)
4322 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
4323 // it not listen to the right events in the right places?
4332 * Compute how #$floatable should be positioned based on the position of #$floatableContainer
4333 * and the positioning settings. This is a helper for #position that shouldn't be called directly,
4334 * but may be overridden by subclasses if they want to change or add to the positioning logic.
4336 * @return {Object} New position to apply with .css(). Keys are 'top', 'left', 'bottom' and 'right'.
4338 OO
.ui
.mixin
.FloatableElement
.prototype.computePosition = function () {
4339 var isBody
, scrollableX
, scrollableY
, containerPos
,
4340 horizScrollbarHeight
, vertScrollbarWidth
, scrollTop
, scrollLeft
,
4341 newPos
= { top
: '', left
: '', bottom
: '', right
: '' },
4342 direction
= this.$floatableContainer
.css( 'direction' ),
4343 $offsetParent
= this.$floatable
.offsetParent();
4345 if ( $offsetParent
.is( 'html' ) ) {
4346 // The innerHeight/Width and clientHeight/Width calculations don't work well on the
4347 // <html> element, but they do work on the <body>
4348 $offsetParent
= $( $offsetParent
[ 0 ].ownerDocument
.body
);
4350 isBody
= $offsetParent
.is( 'body' );
4351 scrollableX
= $offsetParent
.css( 'overflow-x' ) === 'scroll' || $offsetParent
.css( 'overflow-x' ) === 'auto';
4352 scrollableY
= $offsetParent
.css( 'overflow-y' ) === 'scroll' || $offsetParent
.css( 'overflow-y' ) === 'auto';
4354 vertScrollbarWidth
= $offsetParent
.innerWidth() - $offsetParent
.prop( 'clientWidth' );
4355 horizScrollbarHeight
= $offsetParent
.innerHeight() - $offsetParent
.prop( 'clientHeight' );
4356 // We don't need to compute and add scrollTop and scrollLeft if the scrollable container is the body,
4357 // or if it isn't scrollable
4358 scrollTop
= scrollableY
&& !isBody
? $offsetParent
.scrollTop() : 0;
4359 scrollLeft
= scrollableX
&& !isBody
? OO
.ui
.Element
.static.getScrollLeft( $offsetParent
[ 0 ] ) : 0;
4361 // Avoid passing the <body> to getRelativePosition(), because it won't return what we expect
4362 // if the <body> has a margin
4363 containerPos
= isBody
?
4364 this.$floatableContainer
.offset() :
4365 OO
.ui
.Element
.static.getRelativePosition( this.$floatableContainer
, $offsetParent
);
4366 containerPos
.bottom
= containerPos
.top
+ this.$floatableContainer
.outerHeight();
4367 containerPos
.right
= containerPos
.left
+ this.$floatableContainer
.outerWidth();
4368 containerPos
.start
= direction
=== 'rtl' ? containerPos
.right
: containerPos
.left
;
4369 containerPos
.end
= direction
=== 'rtl' ? containerPos
.left
: containerPos
.right
;
4371 if ( this.verticalPosition
=== 'below' ) {
4372 newPos
.top
= containerPos
.bottom
;
4373 } else if ( this.verticalPosition
=== 'above' ) {
4374 newPos
.bottom
= $offsetParent
.outerHeight() - containerPos
.top
;
4375 } else if ( this.verticalPosition
=== 'top' ) {
4376 newPos
.top
= containerPos
.top
;
4377 } else if ( this.verticalPosition
=== 'bottom' ) {
4378 newPos
.bottom
= $offsetParent
.outerHeight() - containerPos
.bottom
;
4379 } else if ( this.verticalPosition
=== 'center' ) {
4380 newPos
.top
= containerPos
.top
+
4381 ( this.$floatableContainer
.height() - this.$floatable
.height() ) / 2;
4384 if ( this.horizontalPosition
=== 'before' ) {
4385 newPos
.end
= containerPos
.start
;
4386 } else if ( this.horizontalPosition
=== 'after' ) {
4387 newPos
.start
= containerPos
.end
;
4388 } else if ( this.horizontalPosition
=== 'start' ) {
4389 newPos
.start
= containerPos
.start
;
4390 } else if ( this.horizontalPosition
=== 'end' ) {
4391 newPos
.end
= containerPos
.end
;
4392 } else if ( this.horizontalPosition
=== 'center' ) {
4393 newPos
.left
= containerPos
.left
+
4394 ( this.$floatableContainer
.width() - this.$floatable
.width() ) / 2;
4397 if ( newPos
.start
!== undefined ) {
4398 if ( direction
=== 'rtl' ) {
4399 newPos
.right
= ( isBody
? $( $offsetParent
[ 0 ].ownerDocument
.documentElement
) : $offsetParent
).outerWidth() - newPos
.start
;
4401 newPos
.left
= newPos
.start
;
4403 delete newPos
.start
;
4405 if ( newPos
.end
!== undefined ) {
4406 if ( direction
=== 'rtl' ) {
4407 newPos
.left
= newPos
.end
;
4409 newPos
.right
= ( isBody
? $( $offsetParent
[ 0 ].ownerDocument
.documentElement
) : $offsetParent
).outerWidth() - newPos
.end
;
4414 // Account for scroll position
4415 if ( newPos
.top
!== '' ) {
4416 newPos
.top
+= scrollTop
;
4418 if ( newPos
.bottom
!== '' ) {
4419 newPos
.bottom
-= scrollTop
;
4421 if ( newPos
.left
!== '' ) {
4422 newPos
.left
+= scrollLeft
;
4424 if ( newPos
.right
!== '' ) {
4425 newPos
.right
-= scrollLeft
;
4428 // Account for scrollbar gutter
4429 if ( newPos
.bottom
!== '' ) {
4430 newPos
.bottom
-= horizScrollbarHeight
;
4432 if ( direction
=== 'rtl' ) {
4433 if ( newPos
.left
!== '' ) {
4434 newPos
.left
-= vertScrollbarWidth
;
4437 if ( newPos
.right
!== '' ) {
4438 newPos
.right
-= vertScrollbarWidth
;
4446 * Element that can be automatically clipped to visible boundaries.
4448 * Whenever the element's natural height changes, you have to call
4449 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
4450 * clipping correctly.
4452 * The dimensions of #$clippableContainer will be compared to the boundaries of the
4453 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
4454 * then #$clippable will be given a fixed reduced height and/or width and will be made
4455 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
4456 * but you can build a static footer by setting #$clippableContainer to an element that contains
4457 * #$clippable and the footer.
4463 * @param {Object} [config] Configuration options
4464 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
4465 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
4466 * omit to use #$clippable
4468 OO
.ui
.mixin
.ClippableElement
= function OoUiMixinClippableElement( config
) {
4469 // Configuration initialization
4470 config
= config
|| {};
4473 this.$clippable
= null;
4474 this.$clippableContainer
= null;
4475 this.clipping
= false;
4476 this.clippedHorizontally
= false;
4477 this.clippedVertically
= false;
4478 this.$clippableScrollableContainer
= null;
4479 this.$clippableScroller
= null;
4480 this.$clippableWindow
= null;
4481 this.idealWidth
= null;
4482 this.idealHeight
= null;
4483 this.onClippableScrollHandler
= this.clip
.bind( this );
4484 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
4487 if ( config
.$clippableContainer
) {
4488 this.setClippableContainer( config
.$clippableContainer
);
4490 this.setClippableElement( config
.$clippable
|| this.$element
);
4496 * Set clippable element.
4498 * If an element is already set, it will be cleaned up before setting up the new element.
4500 * @param {jQuery} $clippable Element to make clippable
4502 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
4503 if ( this.$clippable
) {
4504 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
4505 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
4506 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4509 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
4514 * Set clippable container.
4516 * This is the container that will be measured when deciding whether to clip. When clipping,
4517 * #$clippable will be resized in order to keep the clippable container fully visible.
4519 * If the clippable container is unset, #$clippable will be used.
4521 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
4523 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableContainer = function ( $clippableContainer
) {
4524 this.$clippableContainer
= $clippableContainer
;
4525 if ( this.$clippable
) {
4533 * Do not turn clipping on until after the element is attached to the DOM and visible.
4535 * @param {boolean} [clipping] Enable clipping, omit to toggle
4538 OO
.ui
.mixin
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
4539 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
4541 if ( clipping
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
4542 OO
.ui
.warnDeprecation( 'ClippableElement#toggleClipping: Before calling this method, the element must be attached to the DOM.' );
4543 this.warnedUnattached
= true;
4546 if ( this.clipping
!== clipping
) {
4547 this.clipping
= clipping
;
4549 this.$clippableScrollableContainer
= $( this.getClosestScrollableElementContainer() );
4550 // If the clippable container is the root, we have to listen to scroll events and check
4551 // jQuery.scrollTop on the window because of browser inconsistencies
4552 this.$clippableScroller
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
4553 $( OO
.ui
.Element
.static.getWindow( this.$clippableScrollableContainer
) ) :
4554 this.$clippableScrollableContainer
;
4555 this.$clippableScroller
.on( 'scroll', this.onClippableScrollHandler
);
4556 this.$clippableWindow
= $( this.getElementWindow() )
4557 .on( 'resize', this.onClippableWindowResizeHandler
);
4558 // Initial clip after visible
4561 this.$clippable
.css( {
4569 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4571 this.$clippableScrollableContainer
= null;
4572 this.$clippableScroller
.off( 'scroll', this.onClippableScrollHandler
);
4573 this.$clippableScroller
= null;
4574 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
4575 this.$clippableWindow
= null;
4583 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
4585 * @return {boolean} Element will be clipped to the visible area
4587 OO
.ui
.mixin
.ClippableElement
.prototype.isClipping = function () {
4588 return this.clipping
;
4592 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
4594 * @return {boolean} Part of the element is being clipped
4596 OO
.ui
.mixin
.ClippableElement
.prototype.isClipped = function () {
4597 return this.clippedHorizontally
|| this.clippedVertically
;
4601 * Check if the right of the element is being clipped by the nearest scrollable container.
4603 * @return {boolean} Part of the element is being clipped
4605 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedHorizontally = function () {
4606 return this.clippedHorizontally
;
4610 * Check if the bottom of the element is being clipped by the nearest scrollable container.
4612 * @return {boolean} Part of the element is being clipped
4614 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedVertically = function () {
4615 return this.clippedVertically
;
4619 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
4621 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
4622 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
4624 OO
.ui
.mixin
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
4625 this.idealWidth
= width
;
4626 this.idealHeight
= height
;
4628 if ( !this.clipping
) {
4629 // Update dimensions
4630 this.$clippable
.css( { width
: width
, height
: height
} );
4632 // While clipping, idealWidth and idealHeight are not considered
4636 * Clip element to visible boundaries and allow scrolling when needed. You should call this method
4637 * when the element's natural height changes.
4639 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
4640 * overlapped by, the visible area of the nearest scrollable container.
4642 * Because calling clip() when the natural height changes isn't always possible, we also set
4643 * max-height when the element isn't being clipped. This means that if the element tries to grow
4644 * beyond the edge, something reasonable will happen before clip() is called.
4648 OO
.ui
.mixin
.ClippableElement
.prototype.clip = function () {
4649 var $container
, extraHeight
, extraWidth
, ccOffset
,
4650 $scrollableContainer
, scOffset
, scHeight
, scWidth
,
4651 ccWidth
, scrollerIsWindow
, scrollTop
, scrollLeft
,
4652 desiredWidth
, desiredHeight
, allotedWidth
, allotedHeight
,
4653 naturalWidth
, naturalHeight
, clipWidth
, clipHeight
,
4654 buffer
= 7; // Chosen by fair dice roll
4656 if ( !this.clipping
) {
4657 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
4661 $container
= this.$clippableContainer
|| this.$clippable
;
4662 extraHeight
= $container
.outerHeight() - this.$clippable
.outerHeight();
4663 extraWidth
= $container
.outerWidth() - this.$clippable
.outerWidth();
4664 ccOffset
= $container
.offset();
4665 if ( this.$clippableScrollableContainer
.is( 'html, body' ) ) {
4666 $scrollableContainer
= this.$clippableWindow
;
4667 scOffset
= { top
: 0, left
: 0 };
4669 $scrollableContainer
= this.$clippableScrollableContainer
;
4670 scOffset
= $scrollableContainer
.offset();
4672 scHeight
= $scrollableContainer
.innerHeight() - buffer
;
4673 scWidth
= $scrollableContainer
.innerWidth() - buffer
;
4674 ccWidth
= $container
.outerWidth() + buffer
;
4675 scrollerIsWindow
= this.$clippableScroller
[ 0 ] === this.$clippableWindow
[ 0 ];
4676 scrollTop
= scrollerIsWindow
? this.$clippableScroller
.scrollTop() : 0;
4677 scrollLeft
= scrollerIsWindow
? this.$clippableScroller
.scrollLeft() : 0;
4678 desiredWidth
= ccOffset
.left
< 0 ?
4679 ccWidth
+ ccOffset
.left
:
4680 ( scOffset
.left
+ scrollLeft
+ scWidth
) - ccOffset
.left
;
4681 desiredHeight
= ( scOffset
.top
+ scrollTop
+ scHeight
) - ccOffset
.top
;
4682 // It should never be desirable to exceed the dimensions of the browser viewport... right?
4683 desiredWidth
= Math
.min( desiredWidth
, document
.documentElement
.clientWidth
);
4684 desiredHeight
= Math
.min( desiredHeight
, document
.documentElement
.clientHeight
);
4685 allotedWidth
= Math
.ceil( desiredWidth
- extraWidth
);
4686 allotedHeight
= Math
.ceil( desiredHeight
- extraHeight
);
4687 naturalWidth
= this.$clippable
.prop( 'scrollWidth' );
4688 naturalHeight
= this.$clippable
.prop( 'scrollHeight' );
4689 clipWidth
= allotedWidth
< naturalWidth
;
4690 clipHeight
= allotedHeight
< naturalHeight
;
4693 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. (T157672)
4694 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
4695 this.$clippable
.css( 'overflowX', 'scroll' );
4696 void this.$clippable
[ 0 ].offsetHeight
; // Force reflow
4697 this.$clippable
.css( {
4698 width
: Math
.max( 0, allotedWidth
),
4702 this.$clippable
.css( {
4704 width
: this.idealWidth
? this.idealWidth
- extraWidth
: '',
4705 maxWidth
: Math
.max( 0, allotedWidth
)
4709 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. (T157672)
4710 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
4711 this.$clippable
.css( 'overflowY', 'scroll' );
4712 void this.$clippable
[ 0 ].offsetHeight
; // Force reflow
4713 this.$clippable
.css( {
4714 height
: Math
.max( 0, allotedHeight
),
4718 this.$clippable
.css( {
4720 height
: this.idealHeight
? this.idealHeight
- extraHeight
: '',
4721 maxHeight
: Math
.max( 0, allotedHeight
)
4725 // If we stopped clipping in at least one of the dimensions
4726 if ( ( this.clippedHorizontally
&& !clipWidth
) || ( this.clippedVertically
&& !clipHeight
) ) {
4727 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4730 this.clippedHorizontally
= clipWidth
;
4731 this.clippedVertically
= clipHeight
;
4737 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
4738 * By default, each popup has an anchor that points toward its origin.
4739 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
4741 * Unlike most widgets, PopupWidget is initially hidden and must be shown by calling #toggle.
4744 * // A popup widget.
4745 * var popup = new OO.ui.PopupWidget( {
4746 * $content: $( '<p>Hi there!</p>' ),
4751 * $( 'body' ).append( popup.$element );
4752 * // To display the popup, toggle the visibility to 'true'.
4753 * popup.toggle( true );
4755 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
4758 * @extends OO.ui.Widget
4759 * @mixins OO.ui.mixin.LabelElement
4760 * @mixins OO.ui.mixin.ClippableElement
4761 * @mixins OO.ui.mixin.FloatableElement
4764 * @param {Object} [config] Configuration options
4765 * @cfg {number} [width=320] Width of popup in pixels
4766 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
4767 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
4768 * @cfg {string} [position='below'] Where to position the popup relative to $floatableContainer
4769 * 'above': Put popup above $floatableContainer; anchor points down to the start edge of $floatableContainer
4770 * 'below': Put popup below $floatableContainer; anchor points up to the start edge of $floatableContainer
4771 * 'before': Put popup to the left (LTR) / right (RTL) of $floatableContainer; anchor points
4772 * endwards (right/left) to the vertical center of $floatableContainer
4773 * 'after': Put popup to the right (LTR) / left (RTL) of $floatableContainer; anchor points
4774 * startwards (left/right) to the vertical center of $floatableContainer
4775 * @cfg {string} [align='center'] How to align the popup to $floatableContainer
4776 * 'forwards': If position is above/below, move the popup as far endwards (right in LTR, left in RTL)
4777 * as possible while still keeping the anchor within the popup;
4778 * if position is before/after, move the popup as far downwards as possible.
4779 * 'backwards': If position is above/below, move the popup as far startwards (left in LTR, right in RTL)
4780 * as possible while still keeping the anchor within the popup;
4781 * if position in before/after, move the popup as far upwards as possible.
4782 * 'center': Horizontally (if position is above/below) or vertically (before/after) align the center
4783 * of the popup with the center of $floatableContainer.
4784 * 'force-left': Alias for 'forwards' in LTR and 'backwards' in RTL
4785 * 'force-right': Alias for 'backwards' in RTL and 'forwards' in LTR
4786 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
4787 * See the [OOjs UI docs on MediaWiki][3] for an example.
4788 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
4789 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
4790 * @cfg {jQuery} [$content] Content to append to the popup's body
4791 * @cfg {jQuery} [$footer] Content to append to the popup's footer
4792 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
4793 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
4794 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
4796 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
4797 * @cfg {boolean} [head=false] Show a popup header that contains a #label (if specified) and close
4799 * @cfg {boolean} [padded=false] Add padding to the popup's body
4801 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
4802 // Configuration initialization
4803 config
= config
|| {};
4805 // Parent constructor
4806 OO
.ui
.PopupWidget
.parent
.call( this, config
);
4808 // Properties (must be set before ClippableElement constructor call)
4809 this.$body
= $( '<div>' );
4810 this.$popup
= $( '<div>' );
4812 // Mixin constructors
4813 OO
.ui
.mixin
.LabelElement
.call( this, config
);
4814 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, {
4815 $clippable
: this.$body
,
4816 $clippableContainer
: this.$popup
4818 OO
.ui
.mixin
.FloatableElement
.call( this, config
);
4821 this.$anchor
= $( '<div>' );
4822 // If undefined, will be computed lazily in updateDimensions()
4823 this.$container
= config
.$container
;
4824 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
4825 this.autoClose
= !!config
.autoClose
;
4826 this.$autoCloseIgnore
= config
.$autoCloseIgnore
;
4827 this.transitionTimeout
= null;
4828 this.anchored
= false;
4829 this.width
= config
.width
!== undefined ? config
.width
: 320;
4830 this.height
= config
.height
!== undefined ? config
.height
: null;
4831 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
4832 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
4835 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
4836 this.setAlignment( config
.align
|| 'center' );
4837 this.setPosition( config
.position
|| 'below' );
4838 this.$body
.addClass( 'oo-ui-popupWidget-body' );
4839 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
4841 .addClass( 'oo-ui-popupWidget-popup' )
4842 .append( this.$body
);
4844 .addClass( 'oo-ui-popupWidget' )
4845 .append( this.$popup
, this.$anchor
);
4846 // Move content, which was added to #$element by OO.ui.Widget, to the body
4847 // FIXME This is gross, we should use '$body' or something for the config
4848 if ( config
.$content
instanceof jQuery
) {
4849 this.$body
.append( config
.$content
);
4852 if ( config
.padded
) {
4853 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
4856 if ( config
.head
) {
4857 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
4858 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
4859 this.$head
= $( '<div>' )
4860 .addClass( 'oo-ui-popupWidget-head' )
4861 .append( this.$label
, this.closeButton
.$element
);
4862 this.$popup
.prepend( this.$head
);
4865 if ( config
.$footer
) {
4866 this.$footer
= $( '<div>' )
4867 .addClass( 'oo-ui-popupWidget-footer' )
4868 .append( config
.$footer
);
4869 this.$popup
.append( this.$footer
);
4872 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
4873 // that reference properties not initialized at that time of parent class construction
4874 // TODO: Find a better way to handle post-constructor setup
4875 this.visible
= false;
4876 this.$element
.addClass( 'oo-ui-element-hidden' );
4881 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
4882 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.LabelElement
);
4883 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.ClippableElement
);
4884 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.FloatableElement
);
4889 * Handles mouse down events.
4892 * @param {MouseEvent} e Mouse down event
4894 OO
.ui
.PopupWidget
.prototype.onMouseDown = function ( e
) {
4897 !OO
.ui
.contains( this.$element
.add( this.$autoCloseIgnore
).get(), e
.target
, true )
4899 this.toggle( false );
4904 * Bind mouse down listener.
4908 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
4909 // Capture clicks outside popup
4910 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler
, true );
4914 * Handles close button click events.
4918 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
4919 if ( this.isVisible() ) {
4920 this.toggle( false );
4925 * Unbind mouse down listener.
4929 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
4930 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler
, true );
4934 * Handles key down events.
4937 * @param {KeyboardEvent} e Key down event
4939 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
4941 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
4944 this.toggle( false );
4946 e
.stopPropagation();
4951 * Bind key down listener.
4955 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
4956 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
4960 * Unbind key down listener.
4964 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
4965 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
4969 * Show, hide, or toggle the visibility of the anchor.
4971 * @param {boolean} [show] Show anchor, omit to toggle
4973 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
4974 show
= show
=== undefined ? !this.anchored
: !!show
;
4976 if ( this.anchored
!== show
) {
4978 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
4980 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
4982 this.anchored
= show
;
4986 * Change which edge the anchor appears on.
4988 * @param {string} edge 'top', 'bottom', 'start' or 'end'
4990 OO
.ui
.PopupWidget
.prototype.setAnchorEdge = function ( edge
) {
4991 if ( [ 'top', 'bottom', 'start', 'end' ].indexOf( edge
) === -1 ) {
4992 throw new Error( 'Invalid value for edge: ' + edge
);
4994 if ( this.anchorEdge
!== null ) {
4995 this.$element
.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
4997 this.anchorEdge
= edge
;
4998 this.$element
.addClass( 'oo-ui-popupWidget-anchored-' + edge
);
5002 * Check if the anchor is visible.
5004 * @return {boolean} Anchor is visible
5006 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
5007 return this.anchored
;
5011 * Toggle visibility of the popup. The popup is initially hidden and must be shown by calling
5012 * `.toggle( true )` after its #$element is attached to the DOM.
5014 * Do not show the popup while it is not attached to the DOM. The calculations required to display
5015 * it in the right place and with the right dimensions only work correctly while it is attached.
5016 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
5017 * strictly enforced, so currently it only generates a warning in the browser console.
5021 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
5023 show
= show
=== undefined ? !this.isVisible() : !!show
;
5025 change
= show
!== this.isVisible();
5027 if ( show
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
5028 OO
.ui
.warnDeprecation( 'PopupWidget#toggle: Before calling this method, the popup must be attached to the DOM.' );
5029 this.warnedUnattached
= true;
5031 if ( show
&& !this.$floatableContainer
&& this.isElementAttached() ) {
5032 // Fall back to the parent node if the floatableContainer is not set
5033 this.setFloatableContainer( this.$element
.parent() );
5037 OO
.ui
.PopupWidget
.parent
.prototype.toggle
.call( this, show
);
5040 this.togglePositioning( show
&& !!this.$floatableContainer
);
5043 if ( this.autoClose
) {
5044 this.bindMouseDownListener();
5045 this.bindKeyDownListener();
5047 this.updateDimensions();
5048 this.toggleClipping( true );
5050 this.toggleClipping( false );
5051 if ( this.autoClose
) {
5052 this.unbindMouseDownListener();
5053 this.unbindKeyDownListener();
5062 * Set the size of the popup.
5064 * Changing the size may also change the popup's position depending on the alignment.
5066 * @param {number} width Width in pixels
5067 * @param {number} height Height in pixels
5068 * @param {boolean} [transition=false] Use a smooth transition
5071 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
5073 this.height
= height
!== undefined ? height
: null;
5074 if ( this.isVisible() ) {
5075 this.updateDimensions( transition
);
5080 * Update the size and position.
5082 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
5083 * be called automatically.
5085 * @param {boolean} [transition=false] Use a smooth transition
5088 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
5091 // Prevent transition from being interrupted
5092 clearTimeout( this.transitionTimeout
);
5094 // Enable transition
5095 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
5101 // Prevent transitioning after transition is complete
5102 this.transitionTimeout
= setTimeout( function () {
5103 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
5106 // Prevent transitioning immediately
5107 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
5114 OO
.ui
.PopupWidget
.prototype.computePosition = function () {
5115 var direction
, align
, vertical
, start
, end
, near
, far
, sizeProp
, popupSize
, anchorSize
, anchorPos
,
5116 anchorOffset
, anchorMargin
, parentPosition
, positionProp
, positionAdjustment
, floatablePos
,
5117 offsetParentPos
, containerPos
,
5119 anchorCss
= { left
: '', right
: '', top
: '', bottom
: '' },
5122 'force-left': 'backwards',
5123 'force-right': 'forwards'
5126 'force-left': 'forwards',
5127 'force-right': 'backwards'
5147 if ( !this.$container
) {
5148 // Lazy-initialize $container if not specified in constructor
5149 this.$container
= $( this.getClosestScrollableElementContainer() );
5151 direction
= this.$container
.css( 'direction' );
5153 // Set height and width before we do anything else, since it might cause our measurements
5154 // to change (e.g. due to scrollbars appearing or disappearing), and it also affects centering
5157 height
: this.height
!== null ? this.height
: 'auto'
5160 align
= alignMap
[ direction
][ this.align
] || this.align
;
5161 // If the popup is positioned before or after, then the anchor positioning is vertical, otherwise horizontal
5162 vertical
= this.popupPosition
=== 'before' || this.popupPosition
=== 'after';
5163 start
= vertical
? 'top' : ( direction
=== 'rtl' ? 'right' : 'left' );
5164 end
= vertical
? 'bottom' : ( direction
=== 'rtl' ? 'left' : 'right' );
5165 near
= vertical
? 'top' : 'left';
5166 far
= vertical
? 'bottom' : 'right';
5167 sizeProp
= vertical
? 'Height' : 'Width';
5168 popupSize
= vertical
? ( this.height
|| this.$popup
.height() ) : this.width
;
5170 this.setAnchorEdge( anchorEdgeMap
[ this.popupPosition
] );
5171 this.horizontalPosition
= vertical
? this.popupPosition
: hPosMap
[ align
];
5172 this.verticalPosition
= vertical
? vPosMap
[ align
] : this.popupPosition
;
5175 parentPosition
= OO
.ui
.mixin
.FloatableElement
.prototype.computePosition
.call( this );
5176 // Find out which property FloatableElement used for positioning, and adjust that value
5177 positionProp
= vertical
?
5178 ( parentPosition
.top
!== '' ? 'top' : 'bottom' ) :
5179 ( parentPosition
.left
!== '' ? 'left' : 'right' );
5181 // Figure out where the near and far edges of the popup and $floatableContainer are
5182 floatablePos
= this.$floatableContainer
.offset();
5183 floatablePos
[ far
] = floatablePos
[ near
] + this.$floatableContainer
[ 'outer' + sizeProp
]();
5184 // Measure where the offsetParent is and compute our position based on that and parentPosition
5185 offsetParentPos
= this.$element
.offsetParent().offset();
5187 if ( positionProp
=== near
) {
5188 popupPos
[ near
] = offsetParentPos
[ near
] + parentPosition
[ near
];
5189 popupPos
[ far
] = popupPos
[ near
] + popupSize
;
5191 popupPos
[ far
] = offsetParentPos
[ near
] +
5192 this.$element
.offsetParent()[ 'inner' + sizeProp
]() - parentPosition
[ far
];
5193 popupPos
[ near
] = popupPos
[ far
] - popupSize
;
5196 // Position the anchor (which is positioned relative to the popup) to point to $floatableContainer
5197 // For popups above/below, we point to the start edge; for popups before/after, we point to the center
5198 anchorPos
= vertical
? ( floatablePos
[ start
] + floatablePos
[ end
] ) / 2 : floatablePos
[ start
];
5199 anchorOffset
= ( start
=== far
? -1 : 1 ) * ( anchorPos
- popupPos
[ start
] );
5201 // If the anchor is less than 2*anchorSize from either edge, move the popup to make more space
5202 // this.$anchor.width()/height() returns 0 because of the CSS trickery we use, so use scrollWidth/Height
5203 anchorSize
= this.$anchor
[ 0 ][ 'scroll' + sizeProp
];
5204 anchorMargin
= parseFloat( this.$anchor
.css( 'margin-' + start
) );
5205 if ( anchorOffset
+ anchorMargin
< 2 * anchorSize
) {
5206 // Not enough space for the anchor on the start side; pull the popup startwards
5207 positionAdjustment
= ( positionProp
=== start
? -1 : 1 ) *
5208 ( 2 * anchorSize
- ( anchorOffset
+ anchorMargin
) );
5209 } else if ( anchorOffset
+ anchorMargin
> popupSize
- 2 * anchorSize
) {
5210 // Not enough space for the anchor on the end side; pull the popup endwards
5211 positionAdjustment
= ( positionProp
=== end
? -1 : 1 ) *
5212 ( anchorOffset
+ anchorMargin
- ( popupSize
- 2 * anchorSize
) );
5214 positionAdjustment
= 0;
5217 // Check if the popup will go beyond the edge of this.$container
5218 containerPos
= this.$container
.offset();
5219 containerPos
[ far
] = containerPos
[ near
] + this.$container
[ 'inner' + sizeProp
]();
5220 // Take into account how much the popup will move because of the adjustments we're going to make
5221 popupPos
[ near
] += ( positionProp
=== near
? 1 : -1 ) * positionAdjustment
;
5222 popupPos
[ far
] += ( positionProp
=== near
? 1 : -1 ) * positionAdjustment
;
5223 if ( containerPos
[ near
] + this.containerPadding
> popupPos
[ near
] ) {
5224 // Popup goes beyond the near (left/top) edge, move it to the right/bottom
5225 positionAdjustment
+= ( positionProp
=== near
? 1 : -1 ) *
5226 ( containerPos
[ near
] + this.containerPadding
- popupPos
[ near
] );
5227 } else if ( containerPos
[ far
] - this.containerPadding
< popupPos
[ far
] ) {
5228 // Popup goes beyond the far (right/bottom) edge, move it to the left/top
5229 positionAdjustment
+= ( positionProp
=== far
? 1 : -1 ) *
5230 ( popupPos
[ far
] - ( containerPos
[ far
] - this.containerPadding
) );
5233 // Adjust anchorOffset for positionAdjustment
5234 anchorOffset
+= ( positionProp
=== start
? -1 : 1 ) * positionAdjustment
;
5236 // Position the anchor
5237 anchorCss
[ start
] = anchorOffset
;
5238 this.$anchor
.css( anchorCss
);
5239 // Move the popup if needed
5240 parentPosition
[ positionProp
] += positionAdjustment
;
5242 return parentPosition
;
5246 * Set popup alignment
5248 * @param {string} [align=center] Alignment of the popup, `center`, `force-left`, `force-right`,
5249 * `backwards` or `forwards`.
5251 OO
.ui
.PopupWidget
.prototype.setAlignment = function ( align
) {
5252 // Validate alignment
5253 if ( [ 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align
) > -1 ) {
5256 this.align
= 'center';
5262 * Get popup alignment
5264 * @return {string} Alignment of the popup, `center`, `force-left`, `force-right`,
5265 * `backwards` or `forwards`.
5267 OO
.ui
.PopupWidget
.prototype.getAlignment = function () {
5272 * Change the positioning of the popup.
5274 * @param {string} position 'above', 'below', 'before' or 'after'
5276 OO
.ui
.PopupWidget
.prototype.setPosition = function ( position
) {
5277 if ( [ 'above', 'below', 'before', 'after' ].indexOf( position
) === -1 ) {
5280 this.popupPosition
= position
;
5285 * Get popup positioning.
5287 * @return {string} 'above', 'below', 'before' or 'after'
5289 OO
.ui
.PopupWidget
.prototype.getPosition = function () {
5290 return this.popupPosition
;
5294 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5295 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5296 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5297 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5303 * @param {Object} [config] Configuration options
5304 * @cfg {Object} [popup] Configuration to pass to popup
5305 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5307 OO
.ui
.mixin
.PopupElement
= function OoUiMixinPopupElement( config
) {
5308 // Configuration initialization
5309 config
= config
|| {};
5312 this.popup
= new OO
.ui
.PopupWidget( $.extend(
5315 $floatableContainer
: this.$element
5319 $autoCloseIgnore
: this.$element
.add( config
.popup
&& config
.popup
.$autoCloseIgnore
)
5329 * @return {OO.ui.PopupWidget} Popup widget
5331 OO
.ui
.mixin
.PopupElement
.prototype.getPopup = function () {
5336 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
5337 * which is used to display additional information or options.
5340 * // Example of a popup button.
5341 * var popupButton = new OO.ui.PopupButtonWidget( {
5342 * label: 'Popup button with options',
5345 * $content: $( '<p>Additional options here.</p>' ),
5347 * align: 'force-left'
5350 * // Append the button to the DOM.
5351 * $( 'body' ).append( popupButton.$element );
5354 * @extends OO.ui.ButtonWidget
5355 * @mixins OO.ui.mixin.PopupElement
5358 * @param {Object} [config] Configuration options
5359 * @cfg {jQuery} [$overlay] Render the popup into a separate layer. This configuration is useful in cases where
5360 * the expanded popup is larger than its containing `<div>`. The specified overlay layer is usually on top of the
5361 * containing `<div>` and has a larger area. By default, the popup uses relative positioning.
5363 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
5364 // Parent constructor
5365 OO
.ui
.PopupButtonWidget
.parent
.call( this, config
);
5367 // Mixin constructors
5368 OO
.ui
.mixin
.PopupElement
.call( this, config
);
5371 this.$overlay
= config
.$overlay
|| this.$element
;
5374 this.connect( this, { click
: 'onAction' } );
5378 .addClass( 'oo-ui-popupButtonWidget' )
5379 .attr( 'aria-haspopup', 'true' );
5381 .addClass( 'oo-ui-popupButtonWidget-popup' )
5382 .toggleClass( 'oo-ui-popupButtonWidget-framed-popup', this.isFramed() )
5383 .toggleClass( 'oo-ui-popupButtonWidget-frameless-popup', !this.isFramed() );
5384 this.$overlay
.append( this.popup
.$element
);
5389 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
5390 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.mixin
.PopupElement
);
5395 * Handle the button action being triggered.
5399 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
5400 this.popup
.toggle();
5404 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
5406 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
5411 * @mixins OO.ui.mixin.GroupElement
5414 * @param {Object} [config] Configuration options
5416 OO
.ui
.mixin
.GroupWidget
= function OoUiMixinGroupWidget( config
) {
5417 // Mixin constructors
5418 OO
.ui
.mixin
.GroupElement
.call( this, config
);
5423 OO
.mixinClass( OO
.ui
.mixin
.GroupWidget
, OO
.ui
.mixin
.GroupElement
);
5428 * Set the disabled state of the widget.
5430 * This will also update the disabled state of child widgets.
5432 * @param {boolean} disabled Disable widget
5435 OO
.ui
.mixin
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
5439 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
5440 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
5442 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
5444 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5445 this.items
[ i
].updateDisabled();
5453 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
5455 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
5456 * allows bidirectional communication.
5458 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
5466 OO
.ui
.mixin
.ItemWidget
= function OoUiMixinItemWidget() {
5473 * Check if widget is disabled.
5475 * Checks parent if present, making disabled state inheritable.
5477 * @return {boolean} Widget is disabled
5479 OO
.ui
.mixin
.ItemWidget
.prototype.isDisabled = function () {
5480 return this.disabled
||
5481 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
5485 * Set group element is in.
5487 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
5490 OO
.ui
.mixin
.ItemWidget
.prototype.setElementGroup = function ( group
) {
5492 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
5493 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
5495 // Initialize item disabled states
5496 this.updateDisabled();
5502 * OptionWidgets are special elements that can be selected and configured with data. The
5503 * data is often unique for each option, but it does not have to be. OptionWidgets are used
5504 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
5505 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
5507 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5510 * @extends OO.ui.Widget
5511 * @mixins OO.ui.mixin.ItemWidget
5512 * @mixins OO.ui.mixin.LabelElement
5513 * @mixins OO.ui.mixin.FlaggedElement
5514 * @mixins OO.ui.mixin.AccessKeyedElement
5517 * @param {Object} [config] Configuration options
5519 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
5520 // Configuration initialization
5521 config
= config
|| {};
5523 // Parent constructor
5524 OO
.ui
.OptionWidget
.parent
.call( this, config
);
5526 // Mixin constructors
5527 OO
.ui
.mixin
.ItemWidget
.call( this );
5528 OO
.ui
.mixin
.LabelElement
.call( this, config
);
5529 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
5530 OO
.ui
.mixin
.AccessKeyedElement
.call( this, config
);
5533 this.selected
= false;
5534 this.highlighted
= false;
5535 this.pressed
= false;
5539 .data( 'oo-ui-optionWidget', this )
5540 // Allow programmatic focussing (and by accesskey), but not tabbing
5541 .attr( 'tabindex', '-1' )
5542 .attr( 'role', 'option' )
5543 .attr( 'aria-selected', 'false' )
5544 .addClass( 'oo-ui-optionWidget' )
5545 .append( this.$label
);
5550 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
5551 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.ItemWidget
);
5552 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.LabelElement
);
5553 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.FlaggedElement
);
5554 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
5556 /* Static Properties */
5559 * Whether this option can be selected. See #setSelected.
5563 * @property {boolean}
5565 OO
.ui
.OptionWidget
.static.selectable
= true;
5568 * Whether this option can be highlighted. See #setHighlighted.
5572 * @property {boolean}
5574 OO
.ui
.OptionWidget
.static.highlightable
= true;
5577 * Whether this option can be pressed. See #setPressed.
5581 * @property {boolean}
5583 OO
.ui
.OptionWidget
.static.pressable
= true;
5586 * Whether this option will be scrolled into view when it is selected.
5590 * @property {boolean}
5592 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
5597 * Check if the option can be selected.
5599 * @return {boolean} Item is selectable
5601 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
5602 return this.constructor.static.selectable
&& !this.isDisabled() && this.isVisible();
5606 * Check if the option can be highlighted. A highlight indicates that the option
5607 * may be selected when a user presses enter or clicks. Disabled items cannot
5610 * @return {boolean} Item is highlightable
5612 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
5613 return this.constructor.static.highlightable
&& !this.isDisabled() && this.isVisible();
5617 * Check if the option can be pressed. The pressed state occurs when a user mouses
5618 * down on an item, but has not yet let go of the mouse.
5620 * @return {boolean} Item is pressable
5622 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
5623 return this.constructor.static.pressable
&& !this.isDisabled() && this.isVisible();
5627 * Check if the option is selected.
5629 * @return {boolean} Item is selected
5631 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
5632 return this.selected
;
5636 * Check if the option is highlighted. A highlight indicates that the
5637 * item may be selected when a user presses enter or clicks.
5639 * @return {boolean} Item is highlighted
5641 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
5642 return this.highlighted
;
5646 * Check if the option is pressed. The pressed state occurs when a user mouses
5647 * down on an item, but has not yet let go of the mouse. The item may appear
5648 * selected, but it will not be selected until the user releases the mouse.
5650 * @return {boolean} Item is pressed
5652 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
5653 return this.pressed
;
5657 * Set the option’s selected state. In general, all modifications to the selection
5658 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
5659 * method instead of this method.
5661 * @param {boolean} [state=false] Select option
5664 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
5665 if ( this.constructor.static.selectable
) {
5666 this.selected
= !!state
;
5668 .toggleClass( 'oo-ui-optionWidget-selected', state
)
5669 .attr( 'aria-selected', state
.toString() );
5670 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
5671 this.scrollElementIntoView();
5673 this.updateThemeClasses();
5679 * Set the option’s highlighted state. In general, all programmatic
5680 * modifications to the highlight should be handled by the
5681 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
5682 * method instead of this method.
5684 * @param {boolean} [state=false] Highlight option
5687 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
5688 if ( this.constructor.static.highlightable
) {
5689 this.highlighted
= !!state
;
5690 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
5691 this.updateThemeClasses();
5697 * Set the option’s pressed state. In general, all
5698 * programmatic modifications to the pressed state should be handled by the
5699 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
5700 * method instead of this method.
5702 * @param {boolean} [state=false] Press option
5705 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
5706 if ( this.constructor.static.pressable
) {
5707 this.pressed
= !!state
;
5708 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
5709 this.updateThemeClasses();
5715 * Get text to match search strings against.
5717 * The default implementation returns the label text, but subclasses
5718 * can override this to provide more complex behavior.
5720 * @return {string|boolean} String to match search string against
5722 OO
.ui
.OptionWidget
.prototype.getMatchText = function () {
5723 var label
= this.getLabel();
5724 return typeof label
=== 'string' ? label
: this.$label
.text();
5728 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
5729 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
5730 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
5733 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
5734 * information, please see the [OOjs UI documentation on MediaWiki][1].
5737 * // Example of a select widget with three options
5738 * var select = new OO.ui.SelectWidget( {
5740 * new OO.ui.OptionWidget( {
5742 * label: 'Option One',
5744 * new OO.ui.OptionWidget( {
5746 * label: 'Option Two',
5748 * new OO.ui.OptionWidget( {
5750 * label: 'Option Three',
5754 * $( 'body' ).append( select.$element );
5756 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5760 * @extends OO.ui.Widget
5761 * @mixins OO.ui.mixin.GroupWidget
5764 * @param {Object} [config] Configuration options
5765 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
5766 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
5767 * the [OOjs UI documentation on MediaWiki] [2] for examples.
5768 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5770 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
5771 // Configuration initialization
5772 config
= config
|| {};
5774 // Parent constructor
5775 OO
.ui
.SelectWidget
.parent
.call( this, config
);
5777 // Mixin constructors
5778 OO
.ui
.mixin
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
5781 this.pressed
= false;
5782 this.selecting
= null;
5783 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
5784 this.onMouseMoveHandler
= this.onMouseMove
.bind( this );
5785 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
5786 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
5787 this.keyPressBuffer
= '';
5788 this.keyPressBufferTimer
= null;
5789 this.blockMouseOverEvents
= 0;
5792 this.connect( this, {
5796 focusin
: this.onFocus
.bind( this ),
5797 mousedown
: this.onMouseDown
.bind( this ),
5798 mouseover
: this.onMouseOver
.bind( this ),
5799 mouseleave
: this.onMouseLeave
.bind( this )
5804 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
5805 .attr( 'role', 'listbox' );
5806 if ( Array
.isArray( config
.items
) ) {
5807 this.addItems( config
.items
);
5813 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
5814 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupWidget
);
5821 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
5823 * @param {OO.ui.OptionWidget|null} item Highlighted item
5829 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
5830 * pressed state of an option.
5832 * @param {OO.ui.OptionWidget|null} item Pressed item
5838 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
5840 * @param {OO.ui.OptionWidget|null} item Selected item
5845 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
5846 * @param {OO.ui.OptionWidget} item Chosen item
5852 * An `add` event is emitted when options are added to the select with the #addItems method.
5854 * @param {OO.ui.OptionWidget[]} items Added items
5855 * @param {number} index Index of insertion point
5861 * A `remove` event is emitted when options are removed from the select with the #clearItems
5862 * or #removeItems methods.
5864 * @param {OO.ui.OptionWidget[]} items Removed items
5870 * Handle focus events
5873 * @param {jQuery.Event} event
5875 OO
.ui
.SelectWidget
.prototype.onFocus = function ( event
) {
5877 if ( event
.target
=== this.$element
[ 0 ] ) {
5878 // This widget was focussed, e.g. by the user tabbing to it.
5879 // The styles for focus state depend on one of the items being selected.
5880 if ( !this.getSelectedItem() ) {
5881 item
= this.getFirstSelectableItem();
5884 // One of the options got focussed (and the event bubbled up here).
5885 // They can't be tabbed to, but they can be activated using accesskeys.
5886 item
= this.getTargetItem( event
);
5890 if ( item
.constructor.static.highlightable
) {
5891 this.highlightItem( item
);
5893 this.selectItem( item
);
5897 if ( event
.target
!== this.$element
[ 0 ] ) {
5898 this.$element
.focus();
5903 * Handle mouse down events.
5906 * @param {jQuery.Event} e Mouse down event
5908 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
5911 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
5912 this.togglePressed( true );
5913 item
= this.getTargetItem( e
);
5914 if ( item
&& item
.isSelectable() ) {
5915 this.pressItem( item
);
5916 this.selecting
= item
;
5917 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
5918 this.getElementDocument().addEventListener( 'mousemove', this.onMouseMoveHandler
, true );
5925 * Handle mouse up events.
5928 * @param {MouseEvent} e Mouse up event
5930 OO
.ui
.SelectWidget
.prototype.onMouseUp = function ( e
) {
5933 this.togglePressed( false );
5934 if ( !this.selecting
) {
5935 item
= this.getTargetItem( e
);
5936 if ( item
&& item
.isSelectable() ) {
5937 this.selecting
= item
;
5940 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
&& this.selecting
) {
5941 this.pressItem( null );
5942 this.chooseItem( this.selecting
);
5943 this.selecting
= null;
5946 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
5947 this.getElementDocument().removeEventListener( 'mousemove', this.onMouseMoveHandler
, true );
5953 * Handle mouse move events.
5956 * @param {MouseEvent} e Mouse move event
5958 OO
.ui
.SelectWidget
.prototype.onMouseMove = function ( e
) {
5961 if ( !this.isDisabled() && this.pressed
) {
5962 item
= this.getTargetItem( e
);
5963 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
5964 this.pressItem( item
);
5965 this.selecting
= item
;
5971 * Handle mouse over events.
5974 * @param {jQuery.Event} e Mouse over event
5976 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
5978 if ( this.blockMouseOverEvents
) {
5981 if ( !this.isDisabled() ) {
5982 item
= this.getTargetItem( e
);
5983 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
5989 * Handle mouse leave events.
5992 * @param {jQuery.Event} e Mouse over event
5994 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
5995 if ( !this.isDisabled() ) {
5996 this.highlightItem( null );
6002 * Handle key down events.
6005 * @param {KeyboardEvent} e Key down event
6007 OO
.ui
.SelectWidget
.prototype.onKeyDown = function ( e
) {
6010 currentItem
= this.getHighlightedItem() || this.getSelectedItem();
6012 if ( !this.isDisabled() && this.isVisible() ) {
6013 switch ( e
.keyCode
) {
6014 case OO
.ui
.Keys
.ENTER
:
6015 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
6016 // Was only highlighted, now let's select it. No-op if already selected.
6017 this.chooseItem( currentItem
);
6022 case OO
.ui
.Keys
.LEFT
:
6023 this.clearKeyPressBuffer();
6024 nextItem
= this.getRelativeSelectableItem( currentItem
, -1 );
6027 case OO
.ui
.Keys
.DOWN
:
6028 case OO
.ui
.Keys
.RIGHT
:
6029 this.clearKeyPressBuffer();
6030 nextItem
= this.getRelativeSelectableItem( currentItem
, 1 );
6033 case OO
.ui
.Keys
.ESCAPE
:
6034 case OO
.ui
.Keys
.TAB
:
6035 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
6036 currentItem
.setHighlighted( false );
6038 this.unbindKeyDownListener();
6039 this.unbindKeyPressListener();
6040 // Don't prevent tabbing away / defocusing
6046 if ( nextItem
.constructor.static.highlightable
) {
6047 this.highlightItem( nextItem
);
6049 this.chooseItem( nextItem
);
6051 this.scrollItemIntoView( nextItem
);
6056 e
.stopPropagation();
6062 * Bind key down listener.
6066 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
6067 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler
, true );
6071 * Unbind key down listener.
6075 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
6076 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler
, true );
6080 * Scroll item into view, preventing spurious mouse highlight actions from happening.
6082 * @param {OO.ui.OptionWidget} item Item to scroll into view
6084 OO
.ui
.SelectWidget
.prototype.scrollItemIntoView = function ( item
) {
6086 // Chromium's Blink engine will generate spurious 'mouseover' events during programmatic scrolling
6087 // and around 100-150 ms after it is finished.
6088 this.blockMouseOverEvents
++;
6089 item
.scrollElementIntoView().done( function () {
6090 setTimeout( function () {
6091 widget
.blockMouseOverEvents
--;
6097 * Clear the key-press buffer
6101 OO
.ui
.SelectWidget
.prototype.clearKeyPressBuffer = function () {
6102 if ( this.keyPressBufferTimer
) {
6103 clearTimeout( this.keyPressBufferTimer
);
6104 this.keyPressBufferTimer
= null;
6106 this.keyPressBuffer
= '';
6110 * Handle key press events.
6113 * @param {KeyboardEvent} e Key press event
6115 OO
.ui
.SelectWidget
.prototype.onKeyPress = function ( e
) {
6116 var c
, filter
, item
;
6118 if ( !e
.charCode
) {
6119 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.keyPressBuffer
!== '' ) {
6120 this.keyPressBuffer
= this.keyPressBuffer
.substr( 0, this.keyPressBuffer
.length
- 1 );
6125 if ( String
.fromCodePoint
) {
6126 c
= String
.fromCodePoint( e
.charCode
);
6128 c
= String
.fromCharCode( e
.charCode
);
6131 if ( this.keyPressBufferTimer
) {
6132 clearTimeout( this.keyPressBufferTimer
);
6134 this.keyPressBufferTimer
= setTimeout( this.clearKeyPressBuffer
.bind( this ), 1500 );
6136 item
= this.getHighlightedItem() || this.getSelectedItem();
6138 if ( this.keyPressBuffer
=== c
) {
6139 // Common (if weird) special case: typing "xxxx" will cycle through all
6140 // the items beginning with "x".
6142 item
= this.getRelativeSelectableItem( item
, 1 );
6145 this.keyPressBuffer
+= c
;
6148 filter
= this.getItemMatcher( this.keyPressBuffer
, false );
6149 if ( !item
|| !filter( item
) ) {
6150 item
= this.getRelativeSelectableItem( item
, 1, filter
);
6153 if ( this.isVisible() && item
.constructor.static.highlightable
) {
6154 this.highlightItem( item
);
6156 this.chooseItem( item
);
6158 this.scrollItemIntoView( item
);
6162 e
.stopPropagation();
6166 * Get a matcher for the specific string
6169 * @param {string} s String to match against items
6170 * @param {boolean} [exact=false] Only accept exact matches
6171 * @return {Function} function ( OO.ui.OptionWidget ) => boolean
6173 OO
.ui
.SelectWidget
.prototype.getItemMatcher = function ( s
, exact
) {
6176 if ( s
.normalize
) {
6179 s
= exact
? s
.trim() : s
.replace( /^\s+/, '' );
6180 re
= '^\\s*' + s
.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
6184 re
= new RegExp( re
, 'i' );
6185 return function ( item
) {
6186 var matchText
= item
.getMatchText();
6187 if ( matchText
.normalize
) {
6188 matchText
= matchText
.normalize();
6190 return re
.test( matchText
);
6195 * Bind key press listener.
6199 OO
.ui
.SelectWidget
.prototype.bindKeyPressListener = function () {
6200 this.getElementWindow().addEventListener( 'keypress', this.onKeyPressHandler
, true );
6204 * Unbind key down listener.
6206 * If you override this, be sure to call this.clearKeyPressBuffer() from your
6211 OO
.ui
.SelectWidget
.prototype.unbindKeyPressListener = function () {
6212 this.getElementWindow().removeEventListener( 'keypress', this.onKeyPressHandler
, true );
6213 this.clearKeyPressBuffer();
6217 * Visibility change handler
6220 * @param {boolean} visible
6222 OO
.ui
.SelectWidget
.prototype.onToggle = function ( visible
) {
6224 this.clearKeyPressBuffer();
6229 * Get the closest item to a jQuery.Event.
6232 * @param {jQuery.Event} e
6233 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
6235 OO
.ui
.SelectWidget
.prototype.getTargetItem = function ( e
) {
6236 return $( e
.target
).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
6240 * Get selected item.
6242 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
6244 OO
.ui
.SelectWidget
.prototype.getSelectedItem = function () {
6247 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6248 if ( this.items
[ i
].isSelected() ) {
6249 return this.items
[ i
];
6256 * Get highlighted item.
6258 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
6260 OO
.ui
.SelectWidget
.prototype.getHighlightedItem = function () {
6263 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6264 if ( this.items
[ i
].isHighlighted() ) {
6265 return this.items
[ i
];
6272 * Toggle pressed state.
6274 * Press is a state that occurs when a user mouses down on an item, but
6275 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
6276 * until the user releases the mouse.
6278 * @param {boolean} pressed An option is being pressed
6280 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
6281 if ( pressed
=== undefined ) {
6282 pressed
= !this.pressed
;
6284 if ( pressed
!== this.pressed
) {
6286 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
6287 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
6288 this.pressed
= pressed
;
6293 * Highlight an option. If the `item` param is omitted, no options will be highlighted
6294 * and any existing highlight will be removed. The highlight is mutually exclusive.
6296 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
6300 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
6301 var i
, len
, highlighted
,
6304 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6305 highlighted
= this.items
[ i
] === item
;
6306 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
6307 this.items
[ i
].setHighlighted( highlighted
);
6312 this.emit( 'highlight', item
);
6319 * Fetch an item by its label.
6321 * @param {string} label Label of the item to select.
6322 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
6323 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
6325 OO
.ui
.SelectWidget
.prototype.getItemFromLabel = function ( label
, prefix
) {
6327 len
= this.items
.length
,
6328 filter
= this.getItemMatcher( label
, true );
6330 for ( i
= 0; i
< len
; i
++ ) {
6331 item
= this.items
[ i
];
6332 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
6339 filter
= this.getItemMatcher( label
, false );
6340 for ( i
= 0; i
< len
; i
++ ) {
6341 item
= this.items
[ i
];
6342 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
6358 * Programmatically select an option by its label. If the item does not exist,
6359 * all options will be deselected.
6361 * @param {string} [label] Label of the item to select.
6362 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
6366 OO
.ui
.SelectWidget
.prototype.selectItemByLabel = function ( label
, prefix
) {
6367 var itemFromLabel
= this.getItemFromLabel( label
, !!prefix
);
6368 if ( label
=== undefined || !itemFromLabel
) {
6369 return this.selectItem();
6371 return this.selectItem( itemFromLabel
);
6375 * Programmatically select an option by its data. If the `data` parameter is omitted,
6376 * or if the item does not exist, all options will be deselected.
6378 * @param {Object|string} [data] Value of the item to select, omit to deselect all
6382 OO
.ui
.SelectWidget
.prototype.selectItemByData = function ( data
) {
6383 var itemFromData
= this.getItemFromData( data
);
6384 if ( data
=== undefined || !itemFromData
) {
6385 return this.selectItem();
6387 return this.selectItem( itemFromData
);
6391 * Programmatically select an option by its reference. If the `item` parameter is omitted,
6392 * all options will be deselected.
6394 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
6398 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
6399 var i
, len
, selected
,
6402 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6403 selected
= this.items
[ i
] === item
;
6404 if ( this.items
[ i
].isSelected() !== selected
) {
6405 this.items
[ i
].setSelected( selected
);
6410 this.emit( 'select', item
);
6419 * Press is a state that occurs when a user mouses down on an item, but has not
6420 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
6421 * releases the mouse.
6423 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
6427 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
6428 var i
, len
, pressed
,
6431 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6432 pressed
= this.items
[ i
] === item
;
6433 if ( this.items
[ i
].isPressed() !== pressed
) {
6434 this.items
[ i
].setPressed( pressed
);
6439 this.emit( 'press', item
);
6448 * Note that ‘choose’ should never be modified programmatically. A user can choose
6449 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
6450 * use the #selectItem method.
6452 * This method is identical to #selectItem, but may vary in subclasses that take additional action
6453 * when users choose an item with the keyboard or mouse.
6455 * @param {OO.ui.OptionWidget} item Item to choose
6459 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
6461 this.selectItem( item
);
6462 this.emit( 'choose', item
);
6469 * Get an option by its position relative to the specified item (or to the start of the option array,
6470 * if item is `null`). The direction in which to search through the option array is specified with a
6471 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
6472 * `null` if there are no options in the array.
6474 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
6475 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
6476 * @param {Function} [filter] Only consider items for which this function returns
6477 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
6478 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
6480 OO
.ui
.SelectWidget
.prototype.getRelativeSelectableItem = function ( item
, direction
, filter
) {
6481 var currentIndex
, nextIndex
, i
,
6482 increase
= direction
> 0 ? 1 : -1,
6483 len
= this.items
.length
;
6485 if ( item
instanceof OO
.ui
.OptionWidget
) {
6486 currentIndex
= this.items
.indexOf( item
);
6487 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
6489 // If no item is selected and moving forward, start at the beginning.
6490 // If moving backward, start at the end.
6491 nextIndex
= direction
> 0 ? 0 : len
- 1;
6494 for ( i
= 0; i
< len
; i
++ ) {
6495 item
= this.items
[ nextIndex
];
6497 item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() &&
6498 ( !filter
|| filter( item
) )
6502 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
6508 * Get the next selectable item or `null` if there are no selectable items.
6509 * Disabled options and menu-section markers and breaks are not selectable.
6511 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
6513 OO
.ui
.SelectWidget
.prototype.getFirstSelectableItem = function () {
6514 return this.getRelativeSelectableItem( null, 1 );
6518 * Add an array of options to the select. Optionally, an index number can be used to
6519 * specify an insertion point.
6521 * @param {OO.ui.OptionWidget[]} items Items to add
6522 * @param {number} [index] Index to insert items after
6526 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
6528 OO
.ui
.mixin
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
6530 // Always provide an index, even if it was omitted
6531 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
6537 * Remove the specified array of options from the select. Options will be detached
6538 * from the DOM, not removed, so they can be reused later. To remove all options from
6539 * the select, you may wish to use the #clearItems method instead.
6541 * @param {OO.ui.OptionWidget[]} items Items to remove
6545 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
6548 // Deselect items being removed
6549 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
6551 if ( item
.isSelected() ) {
6552 this.selectItem( null );
6557 OO
.ui
.mixin
.GroupWidget
.prototype.removeItems
.call( this, items
);
6559 this.emit( 'remove', items
);
6565 * Clear all options from the select. Options will be detached from the DOM, not removed,
6566 * so that they can be reused later. To remove a subset of options from the select, use
6567 * the #removeItems method.
6572 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
6573 var items
= this.items
.slice();
6576 OO
.ui
.mixin
.GroupWidget
.prototype.clearItems
.call( this );
6579 this.selectItem( null );
6581 this.emit( 'remove', items
);
6587 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
6588 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
6589 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
6590 * options. For more information about options and selects, please see the
6591 * [OOjs UI documentation on MediaWiki][1].
6594 * // Decorated options in a select widget
6595 * var select = new OO.ui.SelectWidget( {
6597 * new OO.ui.DecoratedOptionWidget( {
6599 * label: 'Option with icon',
6602 * new OO.ui.DecoratedOptionWidget( {
6604 * label: 'Option with indicator',
6609 * $( 'body' ).append( select.$element );
6611 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
6614 * @extends OO.ui.OptionWidget
6615 * @mixins OO.ui.mixin.IconElement
6616 * @mixins OO.ui.mixin.IndicatorElement
6619 * @param {Object} [config] Configuration options
6621 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
6622 // Parent constructor
6623 OO
.ui
.DecoratedOptionWidget
.parent
.call( this, config
);
6625 // Mixin constructors
6626 OO
.ui
.mixin
.IconElement
.call( this, config
);
6627 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
6631 .addClass( 'oo-ui-decoratedOptionWidget' )
6632 .prepend( this.$icon
)
6633 .append( this.$indicator
);
6638 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
6639 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IconElement
);
6640 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IndicatorElement
);
6643 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
6644 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
6645 * the [OOjs UI documentation on MediaWiki] [1] for more information.
6647 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
6650 * @extends OO.ui.DecoratedOptionWidget
6653 * @param {Object} [config] Configuration options
6655 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
6656 // Configuration initialization
6657 config
= $.extend( { icon
: 'check' }, config
);
6659 // Parent constructor
6660 OO
.ui
.MenuOptionWidget
.parent
.call( this, config
);
6664 .attr( 'role', 'menuitem' )
6665 .addClass( 'oo-ui-menuOptionWidget' );
6670 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
6672 /* Static Properties */
6678 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
6681 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
6682 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
6685 * var myDropdown = new OO.ui.DropdownWidget( {
6688 * new OO.ui.MenuSectionOptionWidget( {
6691 * new OO.ui.MenuOptionWidget( {
6693 * label: 'Welsh Corgi'
6695 * new OO.ui.MenuOptionWidget( {
6697 * label: 'Standard Poodle'
6699 * new OO.ui.MenuSectionOptionWidget( {
6702 * new OO.ui.MenuOptionWidget( {
6709 * $( 'body' ).append( myDropdown.$element );
6712 * @extends OO.ui.DecoratedOptionWidget
6715 * @param {Object} [config] Configuration options
6717 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
6718 // Parent constructor
6719 OO
.ui
.MenuSectionOptionWidget
.parent
.call( this, config
);
6722 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' )
6723 .attr( 'role', '' );
6728 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
6730 /* Static Properties */
6736 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
6742 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
6745 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
6746 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
6747 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
6748 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
6749 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
6750 * and customized to be opened, closed, and displayed as needed.
6752 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
6753 * mouse outside the menu.
6755 * Menus also have support for keyboard interaction:
6757 * - Enter/Return key: choose and select a menu option
6758 * - Up-arrow key: highlight the previous menu option
6759 * - Down-arrow key: highlight the next menu option
6760 * - Esc key: hide the menu
6762 * Unlike most widgets, MenuSelectWidget is initially hidden and must be shown by calling #toggle.
6764 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
6765 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
6768 * @extends OO.ui.SelectWidget
6769 * @mixins OO.ui.mixin.ClippableElement
6772 * @param {Object} [config] Configuration options
6773 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
6774 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
6775 * and {@link OO.ui.mixin.LookupElement LookupElement}
6776 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
6777 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiselectWidget CapsuleMultiselectWidget}
6778 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
6779 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
6780 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
6781 * that button, unless the button (or its parent widget) is passed in here.
6782 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
6783 * @cfg {boolean} [hideOnChoose=true] Hide the menu when the user chooses an option.
6784 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
6786 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
6787 // Configuration initialization
6788 config
= config
|| {};
6790 // Parent constructor
6791 OO
.ui
.MenuSelectWidget
.parent
.call( this, config
);
6793 // Mixin constructors
6794 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
6797 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
6798 this.hideOnChoose
= config
.hideOnChoose
=== undefined || !!config
.hideOnChoose
;
6799 this.filterFromInput
= !!config
.filterFromInput
;
6800 this.$input
= config
.$input
? config
.$input
: config
.input
? config
.input
.$input
: null;
6801 this.$widget
= config
.widget
? config
.widget
.$element
: null;
6802 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
6803 this.onInputEditHandler
= OO
.ui
.debounce( this.updateItemVisibility
.bind( this ), 100 );
6807 .addClass( 'oo-ui-menuSelectWidget' )
6808 .attr( 'role', 'menu' );
6810 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
6811 // that reference properties not initialized at that time of parent class construction
6812 // TODO: Find a better way to handle post-constructor setup
6813 this.visible
= false;
6814 this.$element
.addClass( 'oo-ui-element-hidden' );
6819 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
6820 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.ClippableElement
);
6825 * Handles document mouse down events.
6828 * @param {MouseEvent} e Mouse down event
6830 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
6832 !OO
.ui
.contains( this.$element
[ 0 ], e
.target
, true ) &&
6833 ( !this.$widget
|| !OO
.ui
.contains( this.$widget
[ 0 ], e
.target
, true ) )
6835 this.toggle( false );
6842 OO
.ui
.MenuSelectWidget
.prototype.onKeyDown = function ( e
) {
6843 var currentItem
= this.getHighlightedItem() || this.getSelectedItem();
6845 if ( !this.isDisabled() && this.isVisible() ) {
6846 switch ( e
.keyCode
) {
6847 case OO
.ui
.Keys
.LEFT
:
6848 case OO
.ui
.Keys
.RIGHT
:
6849 // Do nothing if a text field is associated, arrow keys will be handled natively
6850 if ( !this.$input
) {
6851 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
6854 case OO
.ui
.Keys
.ESCAPE
:
6855 case OO
.ui
.Keys
.TAB
:
6856 if ( currentItem
) {
6857 currentItem
.setHighlighted( false );
6859 this.toggle( false );
6860 // Don't prevent tabbing away, prevent defocusing
6861 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
6863 e
.stopPropagation();
6867 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
6874 * Update menu item visibility after input changes.
6878 OO
.ui
.MenuSelectWidget
.prototype.updateItemVisibility = function () {
6879 var i
, item
, visible
, section
, sectionEmpty
,
6881 len
= this.items
.length
,
6882 showAll
= !this.isVisible(),
6883 filter
= showAll
? null : this.getItemMatcher( this.$input
.val() );
6885 // Hide non-matching options, and also hide section headers if all options
6886 // in their section are hidden.
6887 for ( i
= 0; i
< len
; i
++ ) {
6888 item
= this.items
[ i
];
6889 if ( item
instanceof OO
.ui
.MenuSectionOptionWidget
) {
6891 // If the previous section was empty, hide its header
6892 section
.toggle( showAll
|| !sectionEmpty
);
6895 sectionEmpty
= true;
6896 } else if ( item
instanceof OO
.ui
.OptionWidget
) {
6897 visible
= showAll
|| filter( item
);
6898 anyVisible
= anyVisible
|| visible
;
6899 sectionEmpty
= sectionEmpty
&& !visible
;
6900 item
.toggle( visible
);
6903 // Process the final section
6905 section
.toggle( showAll
|| !sectionEmpty
);
6908 this.$element
.toggleClass( 'oo-ui-menuSelectWidget-invisible', !anyVisible
);
6910 // Reevaluate clipping
6917 OO
.ui
.MenuSelectWidget
.prototype.bindKeyDownListener = function () {
6918 if ( this.$input
) {
6919 this.$input
.on( 'keydown', this.onKeyDownHandler
);
6921 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyDownListener
.call( this );
6928 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyDownListener = function () {
6929 if ( this.$input
) {
6930 this.$input
.off( 'keydown', this.onKeyDownHandler
);
6932 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyDownListener
.call( this );
6939 OO
.ui
.MenuSelectWidget
.prototype.bindKeyPressListener = function () {
6940 if ( this.$input
) {
6941 if ( this.filterFromInput
) {
6942 this.$input
.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
6945 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyPressListener
.call( this );
6952 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyPressListener = function () {
6953 if ( this.$input
) {
6954 if ( this.filterFromInput
) {
6955 this.$input
.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
6956 this.updateItemVisibility();
6959 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyPressListener
.call( this );
6966 * When a user chooses an item, the menu is closed, unless the hideOnChoose config option is set to false.
6968 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
6969 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
6971 * @param {OO.ui.OptionWidget} item Item to choose
6974 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
6975 OO
.ui
.MenuSelectWidget
.parent
.prototype.chooseItem
.call( this, item
);
6976 if ( this.hideOnChoose
) {
6977 this.toggle( false );
6985 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
6987 OO
.ui
.MenuSelectWidget
.parent
.prototype.addItems
.call( this, items
, index
);
6989 // Reevaluate clipping
6998 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
7000 OO
.ui
.MenuSelectWidget
.parent
.prototype.removeItems
.call( this, items
);
7002 // Reevaluate clipping
7011 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
7013 OO
.ui
.MenuSelectWidget
.parent
.prototype.clearItems
.call( this );
7015 // Reevaluate clipping
7022 * Toggle visibility of the menu. The menu is initially hidden and must be shown by calling
7023 * `.toggle( true )` after its #$element is attached to the DOM.
7025 * Do not show the menu while it is not attached to the DOM. The calculations required to display
7026 * it in the right place and with the right dimensions only work correctly while it is attached.
7027 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
7028 * strictly enforced, so currently it only generates a warning in the browser console.
7032 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
7035 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
7036 change
= visible
!== this.isVisible();
7038 if ( visible
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
7039 OO
.ui
.warnDeprecation( 'MenuSelectWidget#toggle: Before calling this method, the menu must be attached to the DOM.' );
7040 this.warnedUnattached
= true;
7044 OO
.ui
.MenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
7048 this.bindKeyDownListener();
7049 this.bindKeyPressListener();
7051 this.toggleClipping( true );
7053 if ( this.getSelectedItem() ) {
7054 this.getSelectedItem().scrollElementIntoView( { duration
: 0 } );
7058 if ( this.autoHide
) {
7059 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
7062 this.unbindKeyDownListener();
7063 this.unbindKeyPressListener();
7064 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
7065 this.toggleClipping( false );
7073 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
7074 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
7075 * users can interact with it.
7077 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7078 * OO.ui.DropdownInputWidget instead.
7081 * // Example: A DropdownWidget with a menu that contains three options
7082 * var dropDown = new OO.ui.DropdownWidget( {
7083 * label: 'Dropdown menu: Select a menu option',
7086 * new OO.ui.MenuOptionWidget( {
7090 * new OO.ui.MenuOptionWidget( {
7094 * new OO.ui.MenuOptionWidget( {
7102 * $( 'body' ).append( dropDown.$element );
7104 * dropDown.getMenu().selectItemByData( 'b' );
7106 * dropDown.getMenu().getSelectedItem().getData(); // returns 'b'
7108 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
7110 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
7113 * @extends OO.ui.Widget
7114 * @mixins OO.ui.mixin.IconElement
7115 * @mixins OO.ui.mixin.IndicatorElement
7116 * @mixins OO.ui.mixin.LabelElement
7117 * @mixins OO.ui.mixin.TitledElement
7118 * @mixins OO.ui.mixin.TabIndexedElement
7121 * @param {Object} [config] Configuration options
7122 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
7123 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
7124 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
7125 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
7127 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
7128 // Configuration initialization
7129 config
= $.extend( { indicator
: 'down' }, config
);
7131 // Parent constructor
7132 OO
.ui
.DropdownWidget
.parent
.call( this, config
);
7134 // Properties (must be set before TabIndexedElement constructor call)
7135 this.$handle
= this.$( '<span>' );
7136 this.$overlay
= config
.$overlay
|| this.$element
;
7138 // Mixin constructors
7139 OO
.ui
.mixin
.IconElement
.call( this, config
);
7140 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
7141 OO
.ui
.mixin
.LabelElement
.call( this, config
);
7142 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
7143 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
7146 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend( {
7148 $container
: this.$element
7153 click
: this.onClick
.bind( this ),
7154 keydown
: this.onKeyDown
.bind( this ),
7155 // Hack? Handle type-to-search when menu is not expanded and not handling its own events
7156 keypress
: this.menu
.onKeyPressHandler
,
7157 blur
: this.menu
.clearKeyPressBuffer
.bind( this.menu
)
7159 this.menu
.connect( this, {
7160 select
: 'onMenuSelect',
7161 toggle
: 'onMenuToggle'
7166 .addClass( 'oo-ui-dropdownWidget-handle' )
7167 .append( this.$icon
, this.$label
, this.$indicator
);
7169 .addClass( 'oo-ui-dropdownWidget' )
7170 .append( this.$handle
);
7171 this.$overlay
.append( this.menu
.$element
);
7176 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
7177 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IconElement
);
7178 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IndicatorElement
);
7179 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.LabelElement
);
7180 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TitledElement
);
7181 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TabIndexedElement
);
7188 * @return {OO.ui.MenuSelectWidget} Menu of widget
7190 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
7195 * Handles menu select events.
7198 * @param {OO.ui.MenuOptionWidget} item Selected menu item
7200 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
7204 this.setLabel( null );
7208 selectedLabel
= item
.getLabel();
7210 // If the label is a DOM element, clone it, because setLabel will append() it
7211 if ( selectedLabel
instanceof jQuery
) {
7212 selectedLabel
= selectedLabel
.clone();
7215 this.setLabel( selectedLabel
);
7219 * Handle menu toggle events.
7222 * @param {boolean} isVisible Menu toggle event
7224 OO
.ui
.DropdownWidget
.prototype.onMenuToggle = function ( isVisible
) {
7225 this.$element
.toggleClass( 'oo-ui-dropdownWidget-open', isVisible
);
7229 * Handle mouse click events.
7232 * @param {jQuery.Event} e Mouse click event
7234 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
7235 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
7242 * Handle key down events.
7245 * @param {jQuery.Event} e Key down event
7247 OO
.ui
.DropdownWidget
.prototype.onKeyDown = function ( e
) {
7249 !this.isDisabled() &&
7251 e
.which
=== OO
.ui
.Keys
.ENTER
||
7253 !this.menu
.isVisible() &&
7255 e
.which
=== OO
.ui
.Keys
.SPACE
||
7256 e
.which
=== OO
.ui
.Keys
.UP
||
7257 e
.which
=== OO
.ui
.Keys
.DOWN
7268 * RadioOptionWidget is an option widget that looks like a radio button.
7269 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
7270 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
7272 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
7275 * @extends OO.ui.OptionWidget
7278 * @param {Object} [config] Configuration options
7280 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
7281 // Configuration initialization
7282 config
= config
|| {};
7284 // Properties (must be done before parent constructor which calls #setDisabled)
7285 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
7287 // Parent constructor
7288 OO
.ui
.RadioOptionWidget
.parent
.call( this, config
);
7291 // Remove implicit role, we're handling it ourselves
7292 this.radio
.$input
.attr( 'role', 'presentation' );
7294 .addClass( 'oo-ui-radioOptionWidget' )
7295 .attr( 'role', 'radio' )
7296 .attr( 'aria-checked', 'false' )
7297 .removeAttr( 'aria-selected' )
7298 .prepend( this.radio
.$element
);
7303 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
7305 /* Static Properties */
7311 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
7317 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
7323 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
7329 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
7336 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
7337 OO
.ui
.RadioOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
7339 this.radio
.setSelected( state
);
7341 .attr( 'aria-checked', state
.toString() )
7342 .removeAttr( 'aria-selected' );
7350 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
7351 OO
.ui
.RadioOptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
7353 this.radio
.setDisabled( this.isDisabled() );
7359 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
7360 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
7361 * an interface for adding, removing and selecting options.
7362 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
7364 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7365 * OO.ui.RadioSelectInputWidget instead.
7368 * // A RadioSelectWidget with RadioOptions.
7369 * var option1 = new OO.ui.RadioOptionWidget( {
7371 * label: 'Selected radio option'
7374 * var option2 = new OO.ui.RadioOptionWidget( {
7376 * label: 'Unselected radio option'
7379 * var radioSelect=new OO.ui.RadioSelectWidget( {
7380 * items: [ option1, option2 ]
7383 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
7384 * radioSelect.selectItem( option1 );
7386 * $( 'body' ).append( radioSelect.$element );
7388 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
7392 * @extends OO.ui.SelectWidget
7393 * @mixins OO.ui.mixin.TabIndexedElement
7396 * @param {Object} [config] Configuration options
7398 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
7399 // Parent constructor
7400 OO
.ui
.RadioSelectWidget
.parent
.call( this, config
);
7402 // Mixin constructors
7403 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
7407 focus
: this.bindKeyDownListener
.bind( this ),
7408 blur
: this.unbindKeyDownListener
.bind( this )
7413 .addClass( 'oo-ui-radioSelectWidget' )
7414 .attr( 'role', 'radiogroup' );
7419 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
7420 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
7423 * MultioptionWidgets are special elements that can be selected and configured with data. The
7424 * data is often unique for each option, but it does not have to be. MultioptionWidgets are used
7425 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
7426 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
7428 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Multioptions
7431 * @extends OO.ui.Widget
7432 * @mixins OO.ui.mixin.ItemWidget
7433 * @mixins OO.ui.mixin.LabelElement
7436 * @param {Object} [config] Configuration options
7437 * @cfg {boolean} [selected=false] Whether the option is initially selected
7439 OO
.ui
.MultioptionWidget
= function OoUiMultioptionWidget( config
) {
7440 // Configuration initialization
7441 config
= config
|| {};
7443 // Parent constructor
7444 OO
.ui
.MultioptionWidget
.parent
.call( this, config
);
7446 // Mixin constructors
7447 OO
.ui
.mixin
.ItemWidget
.call( this );
7448 OO
.ui
.mixin
.LabelElement
.call( this, config
);
7451 this.selected
= null;
7455 .addClass( 'oo-ui-multioptionWidget' )
7456 .append( this.$label
);
7457 this.setSelected( config
.selected
);
7462 OO
.inheritClass( OO
.ui
.MultioptionWidget
, OO
.ui
.Widget
);
7463 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.ItemWidget
);
7464 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.LabelElement
);
7471 * A change event is emitted when the selected state of the option changes.
7473 * @param {boolean} selected Whether the option is now selected
7479 * Check if the option is selected.
7481 * @return {boolean} Item is selected
7483 OO
.ui
.MultioptionWidget
.prototype.isSelected = function () {
7484 return this.selected
;
7488 * Set the option’s selected state. In general, all modifications to the selection
7489 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
7490 * method instead of this method.
7492 * @param {boolean} [state=false] Select option
7495 OO
.ui
.MultioptionWidget
.prototype.setSelected = function ( state
) {
7497 if ( this.selected
!== state
) {
7498 this.selected
= state
;
7499 this.emit( 'change', state
);
7500 this.$element
.toggleClass( 'oo-ui-multioptionWidget-selected', state
);
7506 * MultiselectWidget allows selecting multiple options from a list.
7508 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
7510 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
7514 * @extends OO.ui.Widget
7515 * @mixins OO.ui.mixin.GroupWidget
7518 * @param {Object} [config] Configuration options
7519 * @cfg {OO.ui.MultioptionWidget[]} [items] An array of options to add to the multiselect.
7521 OO
.ui
.MultiselectWidget
= function OoUiMultiselectWidget( config
) {
7522 // Parent constructor
7523 OO
.ui
.MultiselectWidget
.parent
.call( this, config
);
7525 // Configuration initialization
7526 config
= config
|| {};
7528 // Mixin constructors
7529 OO
.ui
.mixin
.GroupWidget
.call( this, config
);
7532 this.aggregate( { change
: 'select' } );
7533 // This is mostly for compatibility with CapsuleMultiselectWidget... normally, 'change' is emitted
7534 // by GroupElement only when items are added/removed
7535 this.connect( this, { select
: [ 'emit', 'change' ] } );
7538 if ( config
.items
) {
7539 this.addItems( config
.items
);
7541 this.$group
.addClass( 'oo-ui-multiselectWidget-group' );
7542 this.$element
.addClass( 'oo-ui-multiselectWidget' )
7543 .append( this.$group
);
7548 OO
.inheritClass( OO
.ui
.MultiselectWidget
, OO
.ui
.Widget
);
7549 OO
.mixinClass( OO
.ui
.MultiselectWidget
, OO
.ui
.mixin
.GroupWidget
);
7556 * A change event is emitted when the set of items changes, or an item is selected or deselected.
7562 * A select event is emitted when an item is selected or deselected.
7568 * Get options that are selected.
7570 * @return {OO.ui.MultioptionWidget[]} Selected options
7572 OO
.ui
.MultiselectWidget
.prototype.getSelectedItems = function () {
7573 return this.items
.filter( function ( item
) {
7574 return item
.isSelected();
7579 * Get the data of options that are selected.
7581 * @return {Object[]|string[]} Values of selected options
7583 OO
.ui
.MultiselectWidget
.prototype.getSelectedItemsData = function () {
7584 return this.getSelectedItems().map( function ( item
) {
7590 * Select options by reference. Options not mentioned in the `items` array will be deselected.
7592 * @param {OO.ui.MultioptionWidget[]} items Items to select
7595 OO
.ui
.MultiselectWidget
.prototype.selectItems = function ( items
) {
7596 this.items
.forEach( function ( item
) {
7597 var selected
= items
.indexOf( item
) !== -1;
7598 item
.setSelected( selected
);
7604 * Select items by their data. Options not mentioned in the `datas` array will be deselected.
7606 * @param {Object[]|string[]} datas Values of items to select
7609 OO
.ui
.MultiselectWidget
.prototype.selectItemsByData = function ( datas
) {
7612 items
= datas
.map( function ( data
) {
7613 return widget
.getItemFromData( data
);
7615 this.selectItems( items
);
7620 * CheckboxMultioptionWidget is an option widget that looks like a checkbox.
7621 * The class is used with OO.ui.CheckboxMultiselectWidget to create a selection of checkbox options.
7622 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
7624 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
7627 * @extends OO.ui.MultioptionWidget
7630 * @param {Object} [config] Configuration options
7632 OO
.ui
.CheckboxMultioptionWidget
= function OoUiCheckboxMultioptionWidget( config
) {
7633 // Configuration initialization
7634 config
= config
|| {};
7636 // Properties (must be done before parent constructor which calls #setDisabled)
7637 this.checkbox
= new OO
.ui
.CheckboxInputWidget();
7639 // Parent constructor
7640 OO
.ui
.CheckboxMultioptionWidget
.parent
.call( this, config
);
7643 this.checkbox
.on( 'change', this.onCheckboxChange
.bind( this ) );
7644 this.$element
.on( 'keydown', this.onKeyDown
.bind( this ) );
7648 .addClass( 'oo-ui-checkboxMultioptionWidget' )
7649 .prepend( this.checkbox
.$element
);
7654 OO
.inheritClass( OO
.ui
.CheckboxMultioptionWidget
, OO
.ui
.MultioptionWidget
);
7656 /* Static Properties */
7662 OO
.ui
.CheckboxMultioptionWidget
.static.tagName
= 'label';
7667 * Handle checkbox selected state change.
7671 OO
.ui
.CheckboxMultioptionWidget
.prototype.onCheckboxChange = function () {
7672 this.setSelected( this.checkbox
.isSelected() );
7678 OO
.ui
.CheckboxMultioptionWidget
.prototype.setSelected = function ( state
) {
7679 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setSelected
.call( this, state
);
7680 this.checkbox
.setSelected( state
);
7687 OO
.ui
.CheckboxMultioptionWidget
.prototype.setDisabled = function ( disabled
) {
7688 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
7689 this.checkbox
.setDisabled( this.isDisabled() );
7696 OO
.ui
.CheckboxMultioptionWidget
.prototype.focus = function () {
7697 this.checkbox
.focus();
7701 * Handle key down events.
7704 * @param {jQuery.Event} e
7706 OO
.ui
.CheckboxMultioptionWidget
.prototype.onKeyDown = function ( e
) {
7708 element
= this.getElementGroup(),
7711 if ( e
.keyCode
=== OO
.ui
.Keys
.LEFT
|| e
.keyCode
=== OO
.ui
.Keys
.UP
) {
7712 nextItem
= element
.getRelativeFocusableItem( this, -1 );
7713 } else if ( e
.keyCode
=== OO
.ui
.Keys
.RIGHT
|| e
.keyCode
=== OO
.ui
.Keys
.DOWN
) {
7714 nextItem
= element
.getRelativeFocusableItem( this, 1 );
7724 * CheckboxMultiselectWidget is a {@link OO.ui.MultiselectWidget multiselect widget} that contains
7725 * checkboxes and is used together with OO.ui.CheckboxMultioptionWidget. The
7726 * CheckboxMultiselectWidget provides an interface for adding, removing and selecting options.
7727 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
7729 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7730 * OO.ui.CheckboxMultiselectInputWidget instead.
7733 * // A CheckboxMultiselectWidget with CheckboxMultioptions.
7734 * var option1 = new OO.ui.CheckboxMultioptionWidget( {
7737 * label: 'Selected checkbox'
7740 * var option2 = new OO.ui.CheckboxMultioptionWidget( {
7742 * label: 'Unselected checkbox'
7745 * var multiselect=new OO.ui.CheckboxMultiselectWidget( {
7746 * items: [ option1, option2 ]
7749 * $( 'body' ).append( multiselect.$element );
7751 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
7754 * @extends OO.ui.MultiselectWidget
7757 * @param {Object} [config] Configuration options
7759 OO
.ui
.CheckboxMultiselectWidget
= function OoUiCheckboxMultiselectWidget( config
) {
7760 // Parent constructor
7761 OO
.ui
.CheckboxMultiselectWidget
.parent
.call( this, config
);
7764 this.$lastClicked
= null;
7767 this.$group
.on( 'click', this.onClick
.bind( this ) );
7771 .addClass( 'oo-ui-checkboxMultiselectWidget' );
7776 OO
.inheritClass( OO
.ui
.CheckboxMultiselectWidget
, OO
.ui
.MultiselectWidget
);
7781 * Get an option by its position relative to the specified item (or to the start of the option array,
7782 * if item is `null`). The direction in which to search through the option array is specified with a
7783 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
7784 * `null` if there are no options in the array.
7786 * @param {OO.ui.CheckboxMultioptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
7787 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
7788 * @return {OO.ui.CheckboxMultioptionWidget|null} Item at position, `null` if there are no items in the select
7790 OO
.ui
.CheckboxMultiselectWidget
.prototype.getRelativeFocusableItem = function ( item
, direction
) {
7791 var currentIndex
, nextIndex
, i
,
7792 increase
= direction
> 0 ? 1 : -1,
7793 len
= this.items
.length
;
7796 currentIndex
= this.items
.indexOf( item
);
7797 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
7799 // If no item is selected and moving forward, start at the beginning.
7800 // If moving backward, start at the end.
7801 nextIndex
= direction
> 0 ? 0 : len
- 1;
7804 for ( i
= 0; i
< len
; i
++ ) {
7805 item
= this.items
[ nextIndex
];
7806 if ( item
&& !item
.isDisabled() ) {
7809 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
7815 * Handle click events on checkboxes.
7817 * @param {jQuery.Event} e
7819 OO
.ui
.CheckboxMultiselectWidget
.prototype.onClick = function ( e
) {
7820 var $options
, lastClickedIndex
, nowClickedIndex
, i
, direction
, wasSelected
, items
,
7821 $lastClicked
= this.$lastClicked
,
7822 $nowClicked
= $( e
.target
).closest( '.oo-ui-checkboxMultioptionWidget' )
7823 .not( '.oo-ui-widget-disabled' );
7825 // Allow selecting multiple options at once by Shift-clicking them
7826 if ( $lastClicked
&& $nowClicked
.length
&& e
.shiftKey
) {
7827 $options
= this.$group
.find( '.oo-ui-checkboxMultioptionWidget' );
7828 lastClickedIndex
= $options
.index( $lastClicked
);
7829 nowClickedIndex
= $options
.index( $nowClicked
);
7830 // If it's the same item, either the user is being silly, or it's a fake event generated by the
7831 // browser. In either case we don't need custom handling.
7832 if ( nowClickedIndex
!== lastClickedIndex
) {
7834 wasSelected
= items
[ nowClickedIndex
].isSelected();
7835 direction
= nowClickedIndex
> lastClickedIndex
? 1 : -1;
7837 // This depends on the DOM order of the items and the order of the .items array being the same.
7838 for ( i
= lastClickedIndex
; i
!== nowClickedIndex
; i
+= direction
) {
7839 if ( !items
[ i
].isDisabled() ) {
7840 items
[ i
].setSelected( !wasSelected
);
7843 // For the now-clicked element, use immediate timeout to allow the browser to do its own
7844 // handling first, then set our value. The order in which events happen is different for
7845 // clicks on the <input> and on the <label> and there are additional fake clicks fired for
7846 // non-click actions that change the checkboxes.
7848 setTimeout( function () {
7849 if ( !items
[ nowClickedIndex
].isDisabled() ) {
7850 items
[ nowClickedIndex
].setSelected( !wasSelected
);
7856 if ( $nowClicked
.length
) {
7857 this.$lastClicked
= $nowClicked
;
7862 * FloatingMenuSelectWidget is a menu that will stick under a specified
7863 * container, even when it is inserted elsewhere in the document (for example,
7864 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
7865 * menu from being clipped too aggresively.
7867 * The menu's position is automatically calculated and maintained when the menu
7868 * is toggled or the window is resized.
7870 * See OO.ui.ComboBoxInputWidget for an example of a widget that uses this class.
7873 * @extends OO.ui.MenuSelectWidget
7874 * @mixins OO.ui.mixin.FloatableElement
7877 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
7878 * Deprecated, omit this parameter and specify `$container` instead.
7879 * @param {Object} [config] Configuration options
7880 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
7882 OO
.ui
.FloatingMenuSelectWidget
= function OoUiFloatingMenuSelectWidget( inputWidget
, config
) {
7883 // Allow 'inputWidget' parameter and config for backwards compatibility
7884 if ( OO
.isPlainObject( inputWidget
) && config
=== undefined ) {
7885 config
= inputWidget
;
7886 inputWidget
= config
.inputWidget
;
7889 // Configuration initialization
7890 config
= config
|| {};
7892 // Parent constructor
7893 OO
.ui
.FloatingMenuSelectWidget
.parent
.call( this, config
);
7895 // Properties (must be set before mixin constructors)
7896 this.inputWidget
= inputWidget
; // For backwards compatibility
7897 this.$container
= config
.$container
|| this.inputWidget
.$element
;
7899 // Mixins constructors
7900 OO
.ui
.mixin
.FloatableElement
.call( this, $.extend( {}, config
, { $floatableContainer
: this.$container
} ) );
7903 this.$element
.addClass( 'oo-ui-floatingMenuSelectWidget' );
7904 // For backwards compatibility
7905 this.$element
.addClass( 'oo-ui-textInputMenuSelectWidget' );
7910 OO
.inheritClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.MenuSelectWidget
);
7911 OO
.mixinClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.mixin
.FloatableElement
);
7918 OO
.ui
.FloatingMenuSelectWidget
.prototype.toggle = function ( visible
) {
7920 visible
= visible
=== undefined ? !this.isVisible() : !!visible
;
7921 change
= visible
!== this.isVisible();
7923 if ( change
&& visible
) {
7924 // Make sure the width is set before the parent method runs.
7925 this.setIdealSize( this.$container
.width() );
7929 // This will call this.clip(), which is nonsensical since we're not positioned yet...
7930 OO
.ui
.FloatingMenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
7933 this.togglePositioning( this.isVisible() );
7940 * Progress bars visually display the status of an operation, such as a download,
7941 * and can be either determinate or indeterminate:
7943 * - **determinate** process bars show the percent of an operation that is complete.
7945 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
7946 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
7947 * not use percentages.
7949 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
7952 * // Examples of determinate and indeterminate progress bars.
7953 * var progressBar1 = new OO.ui.ProgressBarWidget( {
7956 * var progressBar2 = new OO.ui.ProgressBarWidget();
7958 * // Create a FieldsetLayout to layout progress bars
7959 * var fieldset = new OO.ui.FieldsetLayout;
7960 * fieldset.addItems( [
7961 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
7962 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
7964 * $( 'body' ).append( fieldset.$element );
7967 * @extends OO.ui.Widget
7970 * @param {Object} [config] Configuration options
7971 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
7972 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
7973 * By default, the progress bar is indeterminate.
7975 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
7976 // Configuration initialization
7977 config
= config
|| {};
7979 // Parent constructor
7980 OO
.ui
.ProgressBarWidget
.parent
.call( this, config
);
7983 this.$bar
= $( '<div>' );
7984 this.progress
= null;
7987 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
7988 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
7991 role
: 'progressbar',
7993 'aria-valuemax': 100
7995 .addClass( 'oo-ui-progressBarWidget' )
7996 .append( this.$bar
);
8001 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
8003 /* Static Properties */
8009 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
8014 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
8016 * @return {number|boolean} Progress percent
8018 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
8019 return this.progress
;
8023 * Set the percent of the process completed or `false` for an indeterminate process.
8025 * @param {number|boolean} progress Progress percent or `false` for indeterminate
8027 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
8028 this.progress
= progress
;
8030 if ( progress
!== false ) {
8031 this.$bar
.css( 'width', this.progress
+ '%' );
8032 this.$element
.attr( 'aria-valuenow', this.progress
);
8034 this.$bar
.css( 'width', '' );
8035 this.$element
.removeAttr( 'aria-valuenow' );
8037 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', progress
=== false );
8041 * InputWidget is the base class for all input widgets, which
8042 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
8043 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
8044 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
8046 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8050 * @extends OO.ui.Widget
8051 * @mixins OO.ui.mixin.FlaggedElement
8052 * @mixins OO.ui.mixin.TabIndexedElement
8053 * @mixins OO.ui.mixin.TitledElement
8054 * @mixins OO.ui.mixin.AccessKeyedElement
8057 * @param {Object} [config] Configuration options
8058 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
8059 * @cfg {string} [value=''] The value of the input.
8060 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
8061 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
8062 * before it is accepted.
8064 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
8065 // Configuration initialization
8066 config
= config
|| {};
8068 // Parent constructor
8069 OO
.ui
.InputWidget
.parent
.call( this, config
);
8072 // See #reusePreInfuseDOM about config.$input
8073 this.$input
= config
.$input
|| this.getInputElement( config
);
8075 this.inputFilter
= config
.inputFilter
;
8077 // Mixin constructors
8078 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
8079 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
8080 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
8081 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$input
} ) );
8084 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
8088 .addClass( 'oo-ui-inputWidget-input' )
8089 .attr( 'name', config
.name
)
8090 .prop( 'disabled', this.isDisabled() );
8092 .addClass( 'oo-ui-inputWidget' )
8093 .append( this.$input
);
8094 this.setValue( config
.value
);
8096 this.setDir( config
.dir
);
8102 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
8103 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.FlaggedElement
);
8104 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TabIndexedElement
);
8105 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TitledElement
);
8106 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
8108 /* Static Properties */
8114 OO
.ui
.InputWidget
.static.supportsSimpleLabel
= true;
8116 /* Static Methods */
8121 OO
.ui
.InputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
8122 config
= OO
.ui
.InputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
8123 // Reusing $input lets browsers preserve inputted values across page reloads (T114134)
8124 config
.$input
= $( node
).find( '.oo-ui-inputWidget-input' );
8131 OO
.ui
.InputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8132 var state
= OO
.ui
.InputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8133 if ( config
.$input
&& config
.$input
.length
) {
8134 state
.value
= config
.$input
.val();
8135 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
8136 state
.focus
= config
.$input
.is( ':focus' );
8146 * A change event is emitted when the value of the input changes.
8148 * @param {string} value
8154 * Get input element.
8156 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
8157 * different circumstances. The element must have a `value` property (like form elements).
8160 * @param {Object} config Configuration options
8161 * @return {jQuery} Input element
8163 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
8164 return $( '<input>' );
8168 * Get input element's ID.
8170 * If the element already has an ID then that is returned, otherwise unique ID is
8171 * generated, set on the element, and returned.
8173 * @return {string} The ID of the element
8175 OO
.ui
.InputWidget
.prototype.getInputId = function () {
8176 var id
= this.$input
.attr( 'id' );
8178 if ( id
=== undefined ) {
8179 id
= OO
.ui
.generateElementId();
8180 this.$input
.attr( 'id', id
);
8187 * Handle potentially value-changing events.
8190 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
8192 OO
.ui
.InputWidget
.prototype.onEdit = function () {
8194 if ( !this.isDisabled() ) {
8195 // Allow the stack to clear so the value will be updated
8196 setTimeout( function () {
8197 widget
.setValue( widget
.$input
.val() );
8203 * Get the value of the input.
8205 * @return {string} Input value
8207 OO
.ui
.InputWidget
.prototype.getValue = function () {
8208 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
8209 // it, and we won't know unless they're kind enough to trigger a 'change' event.
8210 var value
= this.$input
.val();
8211 if ( this.value
!== value
) {
8212 this.setValue( value
);
8218 * Set the directionality of the input.
8220 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
8223 OO
.ui
.InputWidget
.prototype.setDir = function ( dir
) {
8224 this.$input
.prop( 'dir', dir
);
8229 * Set the value of the input.
8231 * @param {string} value New value
8235 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
8236 value
= this.cleanUpValue( value
);
8237 // Update the DOM if it has changed. Note that with cleanUpValue, it
8238 // is possible for the DOM value to change without this.value changing.
8239 if ( this.$input
.val() !== value
) {
8240 this.$input
.val( value
);
8242 if ( this.value
!== value
) {
8244 this.emit( 'change', this.value
);
8250 * Clean up incoming value.
8252 * Ensures value is a string, and converts undefined and null to empty string.
8255 * @param {string} value Original value
8256 * @return {string} Cleaned up value
8258 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
8259 if ( value
=== undefined || value
=== null ) {
8261 } else if ( this.inputFilter
) {
8262 return this.inputFilter( String( value
) );
8264 return String( value
);
8269 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
8270 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
8273 OO
.ui
.InputWidget
.prototype.simulateLabelClick = function () {
8274 OO
.ui
.warnDeprecation( 'InputWidget: simulateLabelClick() is deprecated.' );
8275 if ( !this.isDisabled() ) {
8276 if ( this.$input
.is( ':checkbox, :radio' ) ) {
8277 this.$input
.click();
8279 if ( this.$input
.is( ':input' ) ) {
8280 this.$input
[ 0 ].focus();
8288 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
8289 OO
.ui
.InputWidget
.parent
.prototype.setDisabled
.call( this, state
);
8290 if ( this.$input
) {
8291 this.$input
.prop( 'disabled', this.isDisabled() );
8301 OO
.ui
.InputWidget
.prototype.focus = function () {
8302 this.$input
[ 0 ].focus();
8311 OO
.ui
.InputWidget
.prototype.blur = function () {
8312 this.$input
[ 0 ].blur();
8319 OO
.ui
.InputWidget
.prototype.restorePreInfuseState = function ( state
) {
8320 OO
.ui
.InputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
8321 if ( state
.value
!== undefined && state
.value
!== this.getValue() ) {
8322 this.setValue( state
.value
);
8324 if ( state
.focus
) {
8330 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
8331 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
8332 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
8333 * HTML `<button>` (the default) or an HTML `<input>` tags. See the
8334 * [OOjs UI documentation on MediaWiki] [1] for more information.
8337 * // A ButtonInputWidget rendered as an HTML button, the default.
8338 * var button = new OO.ui.ButtonInputWidget( {
8339 * label: 'Input button',
8343 * $( 'body' ).append( button.$element );
8345 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
8348 * @extends OO.ui.InputWidget
8349 * @mixins OO.ui.mixin.ButtonElement
8350 * @mixins OO.ui.mixin.IconElement
8351 * @mixins OO.ui.mixin.IndicatorElement
8352 * @mixins OO.ui.mixin.LabelElement
8353 * @mixins OO.ui.mixin.TitledElement
8356 * @param {Object} [config] Configuration options
8357 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
8358 * @cfg {boolean} [useInputTag=false] Use an `<input>` tag instead of a `<button>` tag, the default.
8359 * Widgets configured to be an `<input>` do not support {@link #icon icons} and {@link #indicator indicators},
8360 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
8361 * be set to `true` when there’s need to support IE 6 in a form with multiple buttons.
8363 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
8364 // Configuration initialization
8365 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
8367 // See InputWidget#reusePreInfuseDOM about config.$input
8368 if ( config
.$input
) {
8369 config
.$input
.empty();
8372 // Properties (must be set before parent constructor, which calls #setValue)
8373 this.useInputTag
= config
.useInputTag
;
8375 // Parent constructor
8376 OO
.ui
.ButtonInputWidget
.parent
.call( this, config
);
8378 // Mixin constructors
8379 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
8380 OO
.ui
.mixin
.IconElement
.call( this, config
);
8381 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
8382 OO
.ui
.mixin
.LabelElement
.call( this, config
);
8383 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
8386 if ( !config
.useInputTag
) {
8387 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
8389 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
8394 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
8395 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.ButtonElement
);
8396 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IconElement
);
8397 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
8398 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.LabelElement
);
8399 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.TitledElement
);
8401 /* Static Properties */
8404 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
8405 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
8410 OO
.ui
.ButtonInputWidget
.static.supportsSimpleLabel
= false;
8416 OO
.ui
.ButtonInputWidget
.static.tagName
= 'span';
8424 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
8426 type
= [ 'button', 'submit', 'reset' ].indexOf( config
.type
) !== -1 ? config
.type
: 'button';
8427 return $( '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + type
+ '">' );
8433 * If #useInputTag is `true`, the label is set as the `value` of the `<input>` tag.
8435 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
8436 * text, or `null` for no label
8439 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
8440 if ( typeof label
=== 'function' ) {
8441 label
= OO
.ui
.resolveMsg( label
);
8444 if ( this.useInputTag
) {
8445 // Discard non-plaintext labels
8446 if ( typeof label
!== 'string' ) {
8450 this.$input
.val( label
);
8453 return OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.call( this, label
);
8457 * Set the value of the input.
8459 * This method is disabled for button inputs configured as {@link #useInputTag <input> tags}, as
8460 * they do not support {@link #value values}.
8462 * @param {string} value New value
8465 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
8466 if ( !this.useInputTag
) {
8467 OO
.ui
.ButtonInputWidget
.parent
.prototype.setValue
.call( this, value
);
8473 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
8474 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
8475 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
8476 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
8478 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
8481 * // An example of selected, unselected, and disabled checkbox inputs
8482 * var checkbox1=new OO.ui.CheckboxInputWidget( {
8486 * var checkbox2=new OO.ui.CheckboxInputWidget( {
8489 * var checkbox3=new OO.ui.CheckboxInputWidget( {
8493 * // Create a fieldset layout with fields for each checkbox.
8494 * var fieldset = new OO.ui.FieldsetLayout( {
8495 * label: 'Checkboxes'
8497 * fieldset.addItems( [
8498 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
8499 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
8500 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
8502 * $( 'body' ).append( fieldset.$element );
8504 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8507 * @extends OO.ui.InputWidget
8510 * @param {Object} [config] Configuration options
8511 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
8513 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
8514 // Configuration initialization
8515 config
= config
|| {};
8517 // Parent constructor
8518 OO
.ui
.CheckboxInputWidget
.parent
.call( this, config
);
8522 .addClass( 'oo-ui-checkboxInputWidget' )
8523 // Required for pretty styling in MediaWiki theme
8524 .append( $( '<span>' ) );
8525 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
8530 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
8532 /* Static Properties */
8538 OO
.ui
.CheckboxInputWidget
.static.tagName
= 'span';
8540 /* Static Methods */
8545 OO
.ui
.CheckboxInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8546 var state
= OO
.ui
.CheckboxInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8547 state
.checked
= config
.$input
.prop( 'checked' );
8557 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
8558 return $( '<input>' ).attr( 'type', 'checkbox' );
8564 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
8566 if ( !this.isDisabled() ) {
8567 // Allow the stack to clear so the value will be updated
8568 setTimeout( function () {
8569 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
8575 * Set selection state of this checkbox.
8577 * @param {boolean} state `true` for selected
8580 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
8582 if ( this.selected
!== state
) {
8583 this.selected
= state
;
8584 this.$input
.prop( 'checked', this.selected
);
8585 this.emit( 'change', this.selected
);
8591 * Check if this checkbox is selected.
8593 * @return {boolean} Checkbox is selected
8595 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
8596 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
8597 // it, and we won't know unless they're kind enough to trigger a 'change' event.
8598 var selected
= this.$input
.prop( 'checked' );
8599 if ( this.selected
!== selected
) {
8600 this.setSelected( selected
);
8602 return this.selected
;
8608 OO
.ui
.CheckboxInputWidget
.prototype.restorePreInfuseState = function ( state
) {
8609 OO
.ui
.CheckboxInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
8610 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
8611 this.setSelected( state
.checked
);
8616 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
8617 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
8618 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
8619 * more information about input widgets.
8621 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
8622 * are no options. If no `value` configuration option is provided, the first option is selected.
8623 * If you need a state representing no value (no option being selected), use a DropdownWidget.
8625 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
8628 * // Example: A DropdownInputWidget with three options
8629 * var dropdownInput = new OO.ui.DropdownInputWidget( {
8631 * { data: 'a', label: 'First' },
8632 * { data: 'b', label: 'Second'},
8633 * { data: 'c', label: 'Third' }
8636 * $( 'body' ).append( dropdownInput.$element );
8638 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8641 * @extends OO.ui.InputWidget
8642 * @mixins OO.ui.mixin.TitledElement
8645 * @param {Object} [config] Configuration options
8646 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
8647 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
8649 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
8650 // Configuration initialization
8651 config
= config
|| {};
8653 // See InputWidget#reusePreInfuseDOM about config.$input
8654 if ( config
.$input
) {
8655 config
.$input
.addClass( 'oo-ui-element-hidden' );
8658 // Properties (must be done before parent constructor which calls #setDisabled)
8659 this.dropdownWidget
= new OO
.ui
.DropdownWidget( config
.dropdown
);
8661 // Parent constructor
8662 OO
.ui
.DropdownInputWidget
.parent
.call( this, config
);
8664 // Mixin constructors
8665 OO
.ui
.mixin
.TitledElement
.call( this, config
);
8668 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
8671 this.setOptions( config
.options
|| [] );
8673 .addClass( 'oo-ui-dropdownInputWidget' )
8674 .append( this.dropdownWidget
.$element
);
8679 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
8680 OO
.mixinClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.mixin
.TitledElement
);
8688 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
8689 return $( '<input>' ).attr( 'type', 'hidden' );
8693 * Handles menu select events.
8696 * @param {OO.ui.MenuOptionWidget} item Selected menu item
8698 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
8699 this.setValue( item
.getData() );
8705 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
8706 value
= this.cleanUpValue( value
);
8707 this.dropdownWidget
.getMenu().selectItemByData( value
);
8708 OO
.ui
.DropdownInputWidget
.parent
.prototype.setValue
.call( this, value
);
8715 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
8716 this.dropdownWidget
.setDisabled( state
);
8717 OO
.ui
.DropdownInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
8722 * Set the options available for this input.
8724 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
8727 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
8729 value
= this.getValue(),
8732 // Rebuild the dropdown menu
8733 this.dropdownWidget
.getMenu()
8735 .addItems( options
.map( function ( opt
) {
8736 var optValue
= widget
.cleanUpValue( opt
.data
);
8738 if ( opt
.optgroup
=== undefined ) {
8739 return new OO
.ui
.MenuOptionWidget( {
8741 label
: opt
.label
!== undefined ? opt
.label
: optValue
8744 return new OO
.ui
.MenuSectionOptionWidget( {
8750 // Restore the previous value, or reset to something sensible
8751 if ( this.dropdownWidget
.getMenu().getItemFromData( value
) ) {
8752 // Previous value is still available, ensure consistency with the dropdown
8753 this.setValue( value
);
8755 // No longer valid, reset
8756 if ( options
.length
) {
8757 this.setValue( options
[ 0 ].data
);
8767 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
8768 this.dropdownWidget
.getMenu().toggle( true );
8775 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
8776 this.dropdownWidget
.getMenu().toggle( false );
8781 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
8782 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
8783 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
8784 * please see the [OOjs UI documentation on MediaWiki][1].
8786 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
8789 * // An example of selected, unselected, and disabled radio inputs
8790 * var radio1 = new OO.ui.RadioInputWidget( {
8794 * var radio2 = new OO.ui.RadioInputWidget( {
8797 * var radio3 = new OO.ui.RadioInputWidget( {
8801 * // Create a fieldset layout with fields for each radio button.
8802 * var fieldset = new OO.ui.FieldsetLayout( {
8803 * label: 'Radio inputs'
8805 * fieldset.addItems( [
8806 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
8807 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
8808 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
8810 * $( 'body' ).append( fieldset.$element );
8812 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8815 * @extends OO.ui.InputWidget
8818 * @param {Object} [config] Configuration options
8819 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
8821 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
8822 // Configuration initialization
8823 config
= config
|| {};
8825 // Parent constructor
8826 OO
.ui
.RadioInputWidget
.parent
.call( this, config
);
8830 .addClass( 'oo-ui-radioInputWidget' )
8831 // Required for pretty styling in MediaWiki theme
8832 .append( $( '<span>' ) );
8833 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
8838 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
8840 /* Static Properties */
8846 OO
.ui
.RadioInputWidget
.static.tagName
= 'span';
8848 /* Static Methods */
8853 OO
.ui
.RadioInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8854 var state
= OO
.ui
.RadioInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8855 state
.checked
= config
.$input
.prop( 'checked' );
8865 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
8866 return $( '<input>' ).attr( 'type', 'radio' );
8872 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
8873 // RadioInputWidget doesn't track its state.
8877 * Set selection state of this radio button.
8879 * @param {boolean} state `true` for selected
8882 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
8883 // RadioInputWidget doesn't track its state.
8884 this.$input
.prop( 'checked', state
);
8889 * Check if this radio button is selected.
8891 * @return {boolean} Radio is selected
8893 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
8894 return this.$input
.prop( 'checked' );
8900 OO
.ui
.RadioInputWidget
.prototype.restorePreInfuseState = function ( state
) {
8901 OO
.ui
.RadioInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
8902 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
8903 this.setSelected( state
.checked
);
8908 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
8909 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
8910 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
8911 * more information about input widgets.
8913 * This and OO.ui.DropdownInputWidget support the same configuration options.
8916 * // Example: A RadioSelectInputWidget with three options
8917 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
8919 * { data: 'a', label: 'First' },
8920 * { data: 'b', label: 'Second'},
8921 * { data: 'c', label: 'Third' }
8924 * $( 'body' ).append( radioSelectInput.$element );
8926 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8929 * @extends OO.ui.InputWidget
8932 * @param {Object} [config] Configuration options
8933 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
8935 OO
.ui
.RadioSelectInputWidget
= function OoUiRadioSelectInputWidget( config
) {
8936 // Configuration initialization
8937 config
= config
|| {};
8939 // Properties (must be done before parent constructor which calls #setDisabled)
8940 this.radioSelectWidget
= new OO
.ui
.RadioSelectWidget();
8942 // Parent constructor
8943 OO
.ui
.RadioSelectInputWidget
.parent
.call( this, config
);
8946 this.radioSelectWidget
.connect( this, { select
: 'onMenuSelect' } );
8949 this.setOptions( config
.options
|| [] );
8951 .addClass( 'oo-ui-radioSelectInputWidget' )
8952 .append( this.radioSelectWidget
.$element
);
8957 OO
.inheritClass( OO
.ui
.RadioSelectInputWidget
, OO
.ui
.InputWidget
);
8959 /* Static Properties */
8965 OO
.ui
.RadioSelectInputWidget
.static.supportsSimpleLabel
= false;
8967 /* Static Methods */
8972 OO
.ui
.RadioSelectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8973 var state
= OO
.ui
.RadioSelectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8974 state
.value
= $( node
).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
8981 OO
.ui
.RadioSelectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
8982 config
= OO
.ui
.RadioSelectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
8983 // Cannot reuse the `<input type=radio>` set
8984 delete config
.$input
;
8994 OO
.ui
.RadioSelectInputWidget
.prototype.getInputElement = function () {
8995 return $( '<input>' ).attr( 'type', 'hidden' );
8999 * Handles menu select events.
9002 * @param {OO.ui.RadioOptionWidget} item Selected menu item
9004 OO
.ui
.RadioSelectInputWidget
.prototype.onMenuSelect = function ( item
) {
9005 this.setValue( item
.getData() );
9011 OO
.ui
.RadioSelectInputWidget
.prototype.setValue = function ( value
) {
9012 value
= this.cleanUpValue( value
);
9013 this.radioSelectWidget
.selectItemByData( value
);
9014 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setValue
.call( this, value
);
9021 OO
.ui
.RadioSelectInputWidget
.prototype.setDisabled = function ( state
) {
9022 this.radioSelectWidget
.setDisabled( state
);
9023 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
9028 * Set the options available for this input.
9030 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9033 OO
.ui
.RadioSelectInputWidget
.prototype.setOptions = function ( options
) {
9035 value
= this.getValue(),
9038 // Rebuild the radioSelect menu
9039 this.radioSelectWidget
9041 .addItems( options
.map( function ( opt
) {
9042 var optValue
= widget
.cleanUpValue( opt
.data
);
9043 return new OO
.ui
.RadioOptionWidget( {
9045 label
: opt
.label
!== undefined ? opt
.label
: optValue
9049 // Restore the previous value, or reset to something sensible
9050 if ( this.radioSelectWidget
.getItemFromData( value
) ) {
9051 // Previous value is still available, ensure consistency with the radioSelect
9052 this.setValue( value
);
9054 // No longer valid, reset
9055 if ( options
.length
) {
9056 this.setValue( options
[ 0 ].data
);
9064 * CheckboxMultiselectInputWidget is a
9065 * {@link OO.ui.CheckboxMultiselectWidget CheckboxMultiselectWidget} intended to be used within a
9066 * HTML form, such as a OO.ui.FormLayout. The selected values are synchronized with the value of
9067 * HTML `<input type=checkbox>` tags. Please see the [OOjs UI documentation on MediaWiki][1] for
9068 * more information about input widgets.
9071 * // Example: A CheckboxMultiselectInputWidget with three options
9072 * var multiselectInput = new OO.ui.CheckboxMultiselectInputWidget( {
9074 * { data: 'a', label: 'First' },
9075 * { data: 'b', label: 'Second'},
9076 * { data: 'c', label: 'Third' }
9079 * $( 'body' ).append( multiselectInput.$element );
9081 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9084 * @extends OO.ui.InputWidget
9087 * @param {Object} [config] Configuration options
9088 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: …, disabled: … }`
9090 OO
.ui
.CheckboxMultiselectInputWidget
= function OoUiCheckboxMultiselectInputWidget( config
) {
9091 // Configuration initialization
9092 config
= config
|| {};
9094 // Properties (must be done before parent constructor which calls #setDisabled)
9095 this.checkboxMultiselectWidget
= new OO
.ui
.CheckboxMultiselectWidget();
9097 // Parent constructor
9098 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.call( this, config
);
9101 this.inputName
= config
.name
;
9105 .addClass( 'oo-ui-checkboxMultiselectInputWidget' )
9106 .append( this.checkboxMultiselectWidget
.$element
);
9107 // We don't use this.$input, but rather the CheckboxInputWidgets inside each option
9108 this.$input
.detach();
9109 this.setOptions( config
.options
|| [] );
9110 // Have to repeat this from parent, as we need options to be set up for this to make sense
9111 this.setValue( config
.value
);
9116 OO
.inheritClass( OO
.ui
.CheckboxMultiselectInputWidget
, OO
.ui
.InputWidget
);
9118 /* Static Properties */
9124 OO
.ui
.CheckboxMultiselectInputWidget
.static.supportsSimpleLabel
= false;
9126 /* Static Methods */
9131 OO
.ui
.CheckboxMultiselectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9132 var state
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9133 state
.value
= $( node
).find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
9134 .toArray().map( function ( el
) { return el
.value
; } );
9141 OO
.ui
.CheckboxMultiselectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
9142 config
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
9143 // Cannot reuse the `<input type=checkbox>` set
9144 delete config
.$input
;
9154 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getInputElement = function () {
9156 return $( '<div>' );
9162 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getValue = function () {
9163 var value
= this.$element
.find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
9164 .toArray().map( function ( el
) { return el
.value
; } );
9165 if ( this.value
!== value
) {
9166 this.setValue( value
);
9174 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setValue = function ( value
) {
9175 value
= this.cleanUpValue( value
);
9176 this.checkboxMultiselectWidget
.selectItemsByData( value
);
9177 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setValue
.call( this, value
);
9182 * Clean up incoming value.
9184 * @param {string[]} value Original value
9185 * @return {string[]} Cleaned up value
9187 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.cleanUpValue = function ( value
) {
9190 if ( !Array
.isArray( value
) ) {
9193 for ( i
= 0; i
< value
.length
; i
++ ) {
9195 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
.call( this, value
[ i
] );
9196 // Remove options that we don't have here
9197 if ( !this.checkboxMultiselectWidget
.getItemFromData( singleValue
) ) {
9200 cleanValue
.push( singleValue
);
9208 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setDisabled = function ( state
) {
9209 this.checkboxMultiselectWidget
.setDisabled( state
);
9210 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
9215 * Set the options available for this input.
9217 * @param {Object[]} options Array of menu options in the format `{ data: …, label: …, disabled: … }`
9220 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setOptions = function ( options
) {
9223 // Rebuild the checkboxMultiselectWidget menu
9224 this.checkboxMultiselectWidget
9226 .addItems( options
.map( function ( opt
) {
9227 var optValue
, item
, optDisabled
;
9229 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
.call( widget
, opt
.data
);
9230 optDisabled
= opt
.disabled
!== undefined ? opt
.disabled
: false;
9231 item
= new OO
.ui
.CheckboxMultioptionWidget( {
9233 label
: opt
.label
!== undefined ? opt
.label
: optValue
,
9234 disabled
: optDisabled
9236 // Set the 'name' and 'value' for form submission
9237 item
.checkbox
.$input
.attr( 'name', widget
.inputName
);
9238 item
.checkbox
.setValue( optValue
);
9242 // Re-set the value, checking the checkboxes as needed.
9243 // This will also get rid of any stale options that we just removed.
9244 this.setValue( this.getValue() );
9250 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
9251 * size of the field as well as its presentation. In addition, these widgets can be configured
9252 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
9253 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
9254 * which modifies incoming values rather than validating them.
9255 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9257 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9260 * // Example of a text input widget
9261 * var textInput = new OO.ui.TextInputWidget( {
9262 * value: 'Text input'
9264 * $( 'body' ).append( textInput.$element );
9266 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9269 * @extends OO.ui.InputWidget
9270 * @mixins OO.ui.mixin.IconElement
9271 * @mixins OO.ui.mixin.IndicatorElement
9272 * @mixins OO.ui.mixin.PendingElement
9273 * @mixins OO.ui.mixin.LabelElement
9276 * @param {Object} [config] Configuration options
9277 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
9278 * 'email', 'url' or 'number'. Ignored if `multiline` is true.
9280 * Some values of `type` result in additional behaviors:
9282 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
9283 * empties the text field
9284 * @cfg {string} [placeholder] Placeholder text
9285 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
9286 * instruct the browser to focus this widget.
9287 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
9288 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
9289 * @cfg {boolean} [multiline=false] Allow multiple lines of text
9290 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
9291 * specifies minimum number of rows to display.
9292 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
9293 * Use the #maxRows config to specify a maximum number of displayed rows.
9294 * @cfg {number} [maxRows] Maximum number of rows to display when #autosize is set to true.
9295 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
9296 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
9297 * the value or placeholder text: `'before'` or `'after'`
9298 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
9299 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
9300 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
9301 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
9302 * (the value must contain only numbers); when RegExp, a regular expression that must match the
9303 * value for it to be considered valid; when Function, a function receiving the value as parameter
9304 * that must return true, or promise resolving to true, for it to be considered valid.
9306 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
9307 // Configuration initialization
9308 config
= $.extend( {
9310 labelPosition
: 'after'
9313 if ( config
.type
=== 'search' ) {
9314 OO
.ui
.warnDeprecation( 'TextInputWidget: config.type=\'search\' is deprecated. Use the SearchInputWidget instead. See T148471 for details.' );
9315 if ( config
.icon
=== undefined ) {
9316 config
.icon
= 'search';
9318 // indicator: 'clear' is set dynamically later, depending on value
9321 // Parent constructor
9322 OO
.ui
.TextInputWidget
.parent
.call( this, config
);
9324 // Mixin constructors
9325 OO
.ui
.mixin
.IconElement
.call( this, config
);
9326 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
9327 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$input
} ) );
9328 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9331 this.type
= this.getSaneType( config
);
9332 this.readOnly
= false;
9333 this.required
= false;
9334 this.multiline
= !!config
.multiline
;
9335 this.autosize
= !!config
.autosize
;
9336 this.minRows
= config
.rows
!== undefined ? config
.rows
: '';
9337 this.maxRows
= config
.maxRows
|| Math
.max( 2 * ( this.minRows
|| 0 ), 10 );
9338 this.validate
= null;
9339 this.styleHeight
= null;
9340 this.scrollWidth
= null;
9342 // Clone for resizing
9343 if ( this.autosize
) {
9344 this.$clone
= this.$input
9346 .insertAfter( this.$input
)
9347 .attr( 'aria-hidden', 'true' )
9348 .addClass( 'oo-ui-element-hidden' );
9351 this.setValidation( config
.validate
);
9352 this.setLabelPosition( config
.labelPosition
);
9356 keypress
: this.onKeyPress
.bind( this ),
9357 blur
: this.onBlur
.bind( this ),
9358 focus
: this.onFocus
.bind( this )
9360 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
9361 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
9362 this.on( 'labelChange', this.updatePosition
.bind( this ) );
9363 this.connect( this, {
9365 disable
: 'onDisable'
9367 this.on( 'change', OO
.ui
.debounce( this.onDebouncedChange
.bind( this ), 250 ) );
9371 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type
)
9372 .append( this.$icon
, this.$indicator
);
9373 this.setReadOnly( !!config
.readOnly
);
9374 this.setRequired( !!config
.required
);
9375 this.updateSearchIndicator();
9376 if ( config
.placeholder
!== undefined ) {
9377 this.$input
.attr( 'placeholder', config
.placeholder
);
9379 if ( config
.maxLength
!== undefined ) {
9380 this.$input
.attr( 'maxlength', config
.maxLength
);
9382 if ( config
.autofocus
) {
9383 this.$input
.attr( 'autofocus', 'autofocus' );
9385 if ( config
.autocomplete
=== false ) {
9386 this.$input
.attr( 'autocomplete', 'off' );
9387 // Turning off autocompletion also disables "form caching" when the user navigates to a
9388 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
9390 beforeunload: function () {
9391 this.$input
.removeAttr( 'autocomplete' );
9393 pageshow: function () {
9394 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
9395 // whole page... it shouldn't hurt, though.
9396 this.$input
.attr( 'autocomplete', 'off' );
9400 if ( this.multiline
&& config
.rows
) {
9401 this.$input
.attr( 'rows', config
.rows
);
9403 if ( this.label
|| config
.autosize
) {
9404 this.isWaitingToBeAttached
= true;
9405 this.installParentChangeDetector();
9411 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
9412 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IconElement
);
9413 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
9414 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.PendingElement
);
9415 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.LabelElement
);
9417 /* Static Properties */
9419 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
9424 /* Static Methods */
9429 OO
.ui
.TextInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9430 var state
= OO
.ui
.TextInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9431 if ( config
.multiline
) {
9432 state
.scrollTop
= config
.$input
.scrollTop();
9440 * An `enter` event is emitted when the user presses 'enter' inside the text box.
9442 * Not emitted if the input is multiline.
9448 * A `resize` event is emitted when autosize is set and the widget resizes
9456 * Handle icon mouse down events.
9459 * @param {jQuery.Event} e Mouse down event
9461 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
9462 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
9463 this.$input
[ 0 ].focus();
9469 * Handle indicator mouse down events.
9472 * @param {jQuery.Event} e Mouse down event
9474 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
9475 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
9476 if ( this.type
=== 'search' ) {
9477 // Clear the text field
9478 this.setValue( '' );
9480 this.$input
[ 0 ].focus();
9486 * Handle key press events.
9489 * @param {jQuery.Event} e Key press event
9490 * @fires enter If enter key is pressed and input is not multiline
9492 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
9493 if ( e
.which
=== OO
.ui
.Keys
.ENTER
&& !this.multiline
) {
9494 this.emit( 'enter', e
);
9499 * Handle blur events.
9502 * @param {jQuery.Event} e Blur event
9504 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
9505 this.setValidityFlag();
9509 * Handle focus events.
9512 * @param {jQuery.Event} e Focus event
9514 OO
.ui
.TextInputWidget
.prototype.onFocus = function () {
9515 if ( this.isWaitingToBeAttached
) {
9516 // If we've received focus, then we must be attached to the document, and if
9517 // isWaitingToBeAttached is still true, that means the handler never fired. Fire it now.
9518 this.onElementAttach();
9520 this.setValidityFlag( true );
9524 * Handle element attach events.
9527 * @param {jQuery.Event} e Element attach event
9529 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
9530 this.isWaitingToBeAttached
= false;
9531 // Any previously calculated size is now probably invalid if we reattached elsewhere
9532 this.valCache
= null;
9534 this.positionLabel();
9538 * Handle change events.
9540 * @param {string} value
9543 OO
.ui
.TextInputWidget
.prototype.onChange = function () {
9544 this.updateSearchIndicator();
9549 * Handle debounced change events.
9551 * @param {string} value
9554 OO
.ui
.TextInputWidget
.prototype.onDebouncedChange = function () {
9555 this.setValidityFlag();
9559 * Handle disable events.
9561 * @param {boolean} disabled Element is disabled
9564 OO
.ui
.TextInputWidget
.prototype.onDisable = function () {
9565 this.updateSearchIndicator();
9569 * Check if the input is {@link #readOnly read-only}.
9573 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
9574 return this.readOnly
;
9578 * Set the {@link #readOnly read-only} state of the input.
9580 * @param {boolean} state Make input read-only
9583 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
9584 this.readOnly
= !!state
;
9585 this.$input
.prop( 'readOnly', this.readOnly
);
9586 this.updateSearchIndicator();
9591 * Check if the input is {@link #required required}.
9595 OO
.ui
.TextInputWidget
.prototype.isRequired = function () {
9596 return this.required
;
9600 * Set the {@link #required required} state of the input.
9602 * @param {boolean} state Make input required
9605 OO
.ui
.TextInputWidget
.prototype.setRequired = function ( state
) {
9606 this.required
= !!state
;
9607 if ( this.required
) {
9609 .attr( 'required', 'required' )
9610 .attr( 'aria-required', 'true' );
9611 if ( this.getIndicator() === null ) {
9612 this.setIndicator( 'required' );
9616 .removeAttr( 'required' )
9617 .removeAttr( 'aria-required' );
9618 if ( this.getIndicator() === 'required' ) {
9619 this.setIndicator( null );
9622 this.updateSearchIndicator();
9627 * Support function for making #onElementAttach work across browsers.
9629 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
9630 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
9632 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
9633 * first time that the element gets attached to the documented.
9635 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
9636 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
9637 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
9640 if ( MutationObserver
) {
9641 // The new way. If only it wasn't so ugly.
9643 if ( this.isElementAttached() ) {
9644 // Widget is attached already, do nothing. This breaks the functionality of this function when
9645 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
9646 // would require observation of the whole document, which would hurt performance of other,
9647 // more important code.
9651 // Find topmost node in the tree
9652 topmostNode
= this.$element
[ 0 ];
9653 while ( topmostNode
.parentNode
) {
9654 topmostNode
= topmostNode
.parentNode
;
9657 // We have no way to detect the $element being attached somewhere without observing the entire
9658 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
9659 // parent node of $element, and instead detect when $element is removed from it (and thus
9660 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
9661 // doesn't get attached, we end up back here and create the parent.
9663 mutationObserver
= new MutationObserver( function ( mutations
) {
9664 var i
, j
, removedNodes
;
9665 for ( i
= 0; i
< mutations
.length
; i
++ ) {
9666 removedNodes
= mutations
[ i
].removedNodes
;
9667 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
9668 if ( removedNodes
[ j
] === topmostNode
) {
9669 setTimeout( onRemove
, 0 );
9676 onRemove = function () {
9677 // If the node was attached somewhere else, report it
9678 if ( widget
.isElementAttached() ) {
9679 widget
.onElementAttach();
9681 mutationObserver
.disconnect();
9682 widget
.installParentChangeDetector();
9685 // Create a fake parent and observe it
9686 fakeParentNode
= $( '<div>' ).append( topmostNode
)[ 0 ];
9687 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
9689 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
9690 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
9691 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
9696 * Automatically adjust the size of the text input.
9698 * This only affects #multiline inputs that are {@link #autosize autosized}.
9703 OO
.ui
.TextInputWidget
.prototype.adjustSize = function () {
9704 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
,
9705 idealHeight
, newHeight
, scrollWidth
, property
;
9707 if ( this.isWaitingToBeAttached
) {
9708 // #onElementAttach will be called soon, which calls this method
9712 if ( this.multiline
&& this.$input
.val() !== this.valCache
) {
9713 if ( this.autosize
) {
9715 .val( this.$input
.val() )
9716 .attr( 'rows', this.minRows
)
9717 // Set inline height property to 0 to measure scroll height
9718 .css( 'height', 0 );
9720 this.$clone
.removeClass( 'oo-ui-element-hidden' );
9722 this.valCache
= this.$input
.val();
9724 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
9726 // Remove inline height property to measure natural heights
9727 this.$clone
.css( 'height', '' );
9728 innerHeight
= this.$clone
.innerHeight();
9729 outerHeight
= this.$clone
.outerHeight();
9731 // Measure max rows height
9733 .attr( 'rows', this.maxRows
)
9734 .css( 'height', 'auto' )
9736 maxInnerHeight
= this.$clone
.innerHeight();
9738 // Difference between reported innerHeight and scrollHeight with no scrollbars present.
9739 // This is sometimes non-zero on Blink-based browsers, depending on zoom level.
9740 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
9741 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
9743 this.$clone
.addClass( 'oo-ui-element-hidden' );
9745 // Only apply inline height when expansion beyond natural height is needed
9746 // Use the difference between the inner and outer height as a buffer
9747 newHeight
= idealHeight
> innerHeight
? idealHeight
+ ( outerHeight
- innerHeight
) : '';
9748 if ( newHeight
!== this.styleHeight
) {
9749 this.$input
.css( 'height', newHeight
);
9750 this.styleHeight
= newHeight
;
9751 this.emit( 'resize' );
9754 scrollWidth
= this.$input
[ 0 ].offsetWidth
- this.$input
[ 0 ].clientWidth
;
9755 if ( scrollWidth
!== this.scrollWidth
) {
9756 property
= this.$element
.css( 'direction' ) === 'rtl' ? 'left' : 'right';
9758 this.$label
.css( { right
: '', left
: '' } );
9759 this.$indicator
.css( { right
: '', left
: '' } );
9761 if ( scrollWidth
) {
9762 this.$indicator
.css( property
, scrollWidth
);
9763 if ( this.labelPosition
=== 'after' ) {
9764 this.$label
.css( property
, scrollWidth
);
9768 this.scrollWidth
= scrollWidth
;
9769 this.positionLabel();
9779 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
9780 if ( config
.multiline
) {
9781 return $( '<textarea>' );
9782 } else if ( this.getSaneType( config
) === 'number' ) {
9783 return $( '<input>' )
9784 .attr( 'step', 'any' )
9785 .attr( 'type', 'number' );
9787 return $( '<input>' ).attr( 'type', this.getSaneType( config
) );
9792 * Get sanitized value for 'type' for given config.
9794 * @param {Object} config Configuration options
9795 * @return {string|null}
9798 OO
.ui
.TextInputWidget
.prototype.getSaneType = function ( config
) {
9799 var allowedTypes
= [
9807 return allowedTypes
.indexOf( config
.type
) !== -1 ? config
.type
: 'text';
9811 * Check if the input supports multiple lines.
9815 OO
.ui
.TextInputWidget
.prototype.isMultiline = function () {
9816 return !!this.multiline
;
9820 * Check if the input automatically adjusts its size.
9824 OO
.ui
.TextInputWidget
.prototype.isAutosizing = function () {
9825 return !!this.autosize
;
9829 * Focus the input and select a specified range within the text.
9831 * @param {number} from Select from offset
9832 * @param {number} [to] Select to offset, defaults to from
9835 OO
.ui
.TextInputWidget
.prototype.selectRange = function ( from, to
) {
9836 var isBackwards
, start
, end
,
9837 input
= this.$input
[ 0 ];
9841 isBackwards
= to
< from;
9842 start
= isBackwards
? to
: from;
9843 end
= isBackwards
? from : to
;
9848 input
.setSelectionRange( start
, end
, isBackwards
? 'backward' : 'forward' );
9850 // IE throws an exception if you call setSelectionRange on a unattached DOM node.
9851 // Rather than expensively check if the input is attached every time, just check
9852 // if it was the cause of an error being thrown. If not, rethrow the error.
9853 if ( this.getElementDocument().body
.contains( input
) ) {
9861 * Get an object describing the current selection range in a directional manner
9863 * @return {Object} Object containing 'from' and 'to' offsets
9865 OO
.ui
.TextInputWidget
.prototype.getRange = function () {
9866 var input
= this.$input
[ 0 ],
9867 start
= input
.selectionStart
,
9868 end
= input
.selectionEnd
,
9869 isBackwards
= input
.selectionDirection
=== 'backward';
9872 from: isBackwards
? end
: start
,
9873 to
: isBackwards
? start
: end
9878 * Get the length of the text input value.
9880 * This could differ from the length of #getValue if the
9881 * value gets filtered
9883 * @return {number} Input length
9885 OO
.ui
.TextInputWidget
.prototype.getInputLength = function () {
9886 return this.$input
[ 0 ].value
.length
;
9890 * Focus the input and select the entire text.
9894 OO
.ui
.TextInputWidget
.prototype.select = function () {
9895 return this.selectRange( 0, this.getInputLength() );
9899 * Focus the input and move the cursor to the start.
9903 OO
.ui
.TextInputWidget
.prototype.moveCursorToStart = function () {
9904 return this.selectRange( 0 );
9908 * Focus the input and move the cursor to the end.
9912 OO
.ui
.TextInputWidget
.prototype.moveCursorToEnd = function () {
9913 return this.selectRange( this.getInputLength() );
9917 * Insert new content into the input.
9919 * @param {string} content Content to be inserted
9922 OO
.ui
.TextInputWidget
.prototype.insertContent = function ( content
) {
9924 range
= this.getRange(),
9925 value
= this.getValue();
9927 start
= Math
.min( range
.from, range
.to
);
9928 end
= Math
.max( range
.from, range
.to
);
9930 this.setValue( value
.slice( 0, start
) + content
+ value
.slice( end
) );
9931 this.selectRange( start
+ content
.length
);
9936 * Insert new content either side of a selection.
9938 * @param {string} pre Content to be inserted before the selection
9939 * @param {string} post Content to be inserted after the selection
9942 OO
.ui
.TextInputWidget
.prototype.encapsulateContent = function ( pre
, post
) {
9944 range
= this.getRange(),
9945 offset
= pre
.length
;
9947 start
= Math
.min( range
.from, range
.to
);
9948 end
= Math
.max( range
.from, range
.to
);
9950 this.selectRange( start
).insertContent( pre
);
9951 this.selectRange( offset
+ end
).insertContent( post
);
9953 this.selectRange( offset
+ start
, offset
+ end
);
9958 * Set the validation pattern.
9960 * The validation pattern is either a regular expression, a function, or the symbolic name of a
9961 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
9962 * value must contain only numbers).
9964 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
9965 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
9967 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
9968 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
9969 this.validate
= validate
;
9971 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
9976 * Sets the 'invalid' flag appropriately.
9978 * @param {boolean} [isValid] Optionally override validation result
9980 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
9982 setFlag = function ( valid
) {
9984 widget
.$input
.attr( 'aria-invalid', 'true' );
9986 widget
.$input
.removeAttr( 'aria-invalid' );
9988 widget
.setFlags( { invalid
: !valid
} );
9991 if ( isValid
!== undefined ) {
9994 this.getValidity().then( function () {
10003 * Get the validity of current value.
10005 * This method returns a promise that resolves if the value is valid and rejects if
10006 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
10008 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
10010 OO
.ui
.TextInputWidget
.prototype.getValidity = function () {
10013 function rejectOrResolve( valid
) {
10015 return $.Deferred().resolve().promise();
10017 return $.Deferred().reject().promise();
10021 // Check browser validity and reject if it is invalid
10023 this.$input
[ 0 ].checkValidity
!== undefined &&
10024 this.$input
[ 0 ].checkValidity() === false
10026 return rejectOrResolve( false );
10029 // Run our checks if the browser thinks the field is valid
10030 if ( this.validate
instanceof Function
) {
10031 result
= this.validate( this.getValue() );
10032 if ( result
&& $.isFunction( result
.promise
) ) {
10033 return result
.promise().then( function ( valid
) {
10034 return rejectOrResolve( valid
);
10037 return rejectOrResolve( result
);
10040 return rejectOrResolve( this.getValue().match( this.validate
) );
10045 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
10047 * @param {string} labelPosition Label position, 'before' or 'after'
10050 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
10051 this.labelPosition
= labelPosition
;
10052 if ( this.label
) {
10053 // If there is no label and we only change the position, #updatePosition is a no-op,
10054 // but it takes really a lot of work to do nothing.
10055 this.updatePosition();
10061 * Update the position of the inline label.
10063 * This method is called by #setLabelPosition, and can also be called on its own if
10064 * something causes the label to be mispositioned.
10068 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
10069 var after
= this.labelPosition
=== 'after';
10072 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
10073 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
10075 this.valCache
= null;
10076 this.scrollWidth
= null;
10078 this.positionLabel();
10084 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
10085 * already empty or when it's not editable.
10087 OO
.ui
.TextInputWidget
.prototype.updateSearchIndicator = function () {
10088 if ( this.type
=== 'search' ) {
10089 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
10090 this.setIndicator( null );
10092 this.setIndicator( 'clear' );
10098 * Position the label by setting the correct padding on the input.
10103 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
10104 var after
, rtl
, property
;
10106 if ( this.isWaitingToBeAttached
) {
10107 // #onElementAttach will be called soon, which calls this method
10111 // Clear old values
10113 // Clear old values if present
10115 'padding-right': '',
10119 if ( this.label
) {
10120 this.$element
.append( this.$label
);
10122 this.$label
.detach();
10126 after
= this.labelPosition
=== 'after';
10127 rtl
= this.$element
.css( 'direction' ) === 'rtl';
10128 property
= after
=== rtl
? 'padding-left' : 'padding-right';
10130 this.$input
.css( property
, this.$label
.outerWidth( true ) + ( after
? this.scrollWidth
: 0 ) );
10138 OO
.ui
.TextInputWidget
.prototype.restorePreInfuseState = function ( state
) {
10139 OO
.ui
.TextInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
10140 if ( state
.scrollTop
!== undefined ) {
10141 this.$input
.scrollTop( state
.scrollTop
);
10147 * @extends OO.ui.TextInputWidget
10150 * @param {Object} [config] Configuration options
10152 OO
.ui
.SearchInputWidget
= function OoUiSearchInputWidget( config
) {
10153 config
= $.extend( {
10157 // Set type to text so that TextInputWidget doesn't
10158 // get stuck in an infinite loop.
10159 config
.type
= 'text';
10161 // Parent constructor
10162 OO
.ui
.SearchInputWidget
.parent
.call( this, config
);
10165 this.$element
.addClass( 'oo-ui-textInputWidget-type-search' );
10166 this.updateSearchIndicator();
10167 this.connect( this, {
10168 disable
: 'onDisable'
10174 OO
.inheritClass( OO
.ui
.SearchInputWidget
, OO
.ui
.TextInputWidget
);
10182 OO
.ui
.SearchInputWidget
.prototype.getInputElement = function () {
10183 return $( '<input>' ).attr( 'type', 'search' );
10189 OO
.ui
.SearchInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
10190 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
10191 // Clear the text field
10192 this.setValue( '' );
10193 this.$input
[ 0 ].focus();
10199 * Update the 'clear' indicator displayed on type: 'search' text
10200 * fields, hiding it when the field is already empty or when it's not
10203 OO
.ui
.SearchInputWidget
.prototype.updateSearchIndicator = function () {
10204 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
10205 this.setIndicator( null );
10207 this.setIndicator( 'clear' );
10214 OO
.ui
.SearchInputWidget
.prototype.onChange = function () {
10215 OO
.ui
.SearchInputWidget
.parent
.prototype.onChange
.call( this );
10216 this.updateSearchIndicator();
10220 * Handle disable events.
10222 * @param {boolean} disabled Element is disabled
10225 OO
.ui
.SearchInputWidget
.prototype.onDisable = function () {
10226 this.updateSearchIndicator();
10232 OO
.ui
.SearchInputWidget
.prototype.setReadOnly = function ( state
) {
10233 OO
.ui
.SearchInputWidget
.parent
.prototype.setReadOnly
.call( this, state
);
10234 this.updateSearchIndicator();
10239 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
10240 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
10241 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
10243 * - by typing a value in the text input field. If the value exactly matches the value of a menu
10244 * option, that option will appear to be selected.
10245 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
10248 * After the user chooses an option, its `data` will be used as a new value for the widget.
10249 * A `label` also can be specified for each option: if given, it will be shown instead of the
10250 * `data` in the dropdown menu.
10252 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
10254 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
10257 * // Example: A ComboBoxInputWidget.
10258 * var comboBox = new OO.ui.ComboBoxInputWidget( {
10259 * value: 'Option 1',
10261 * { data: 'Option 1' },
10262 * { data: 'Option 2' },
10263 * { data: 'Option 3' }
10266 * $( 'body' ).append( comboBox.$element );
10269 * // Example: A ComboBoxInputWidget with additional option labels.
10270 * var comboBox = new OO.ui.ComboBoxInputWidget( {
10271 * value: 'Option 1',
10274 * data: 'Option 1',
10275 * label: 'Option One'
10278 * data: 'Option 2',
10279 * label: 'Option Two'
10282 * data: 'Option 3',
10283 * label: 'Option Three'
10287 * $( 'body' ).append( comboBox.$element );
10289 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
10292 * @extends OO.ui.TextInputWidget
10295 * @param {Object} [config] Configuration options
10296 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
10297 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
10298 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
10299 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
10300 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
10302 OO
.ui
.ComboBoxInputWidget
= function OoUiComboBoxInputWidget( config
) {
10303 // Configuration initialization
10304 config
= $.extend( {
10305 autocomplete
: false
10308 // ComboBoxInputWidget shouldn't support multiline
10309 config
.multiline
= false;
10311 // Parent constructor
10312 OO
.ui
.ComboBoxInputWidget
.parent
.call( this, config
);
10315 this.$overlay
= config
.$overlay
|| this.$element
;
10316 this.dropdownButton
= new OO
.ui
.ButtonWidget( {
10317 classes
: [ 'oo-ui-comboBoxInputWidget-dropdownButton' ],
10319 disabled
: this.disabled
10321 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend(
10325 $container
: this.$element
,
10326 disabled
: this.isDisabled()
10332 this.connect( this, {
10333 change
: 'onInputChange',
10334 enter
: 'onInputEnter'
10336 this.dropdownButton
.connect( this, {
10337 click
: 'onDropdownButtonClick'
10339 this.menu
.connect( this, {
10340 choose
: 'onMenuChoose',
10341 add
: 'onMenuItemsChange',
10342 remove
: 'onMenuItemsChange'
10346 this.$input
.attr( {
10348 'aria-autocomplete': 'list'
10350 // Do not override options set via config.menu.items
10351 if ( config
.options
!== undefined ) {
10352 this.setOptions( config
.options
);
10354 this.$field
= $( '<div>' )
10355 .addClass( 'oo-ui-comboBoxInputWidget-field' )
10356 .append( this.$input
, this.dropdownButton
.$element
);
10358 .addClass( 'oo-ui-comboBoxInputWidget' )
10359 .append( this.$field
);
10360 this.$overlay
.append( this.menu
.$element
);
10361 this.onMenuItemsChange();
10366 OO
.inheritClass( OO
.ui
.ComboBoxInputWidget
, OO
.ui
.TextInputWidget
);
10371 * Get the combobox's menu.
10373 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
10375 OO
.ui
.ComboBoxInputWidget
.prototype.getMenu = function () {
10380 * Get the combobox's text input widget.
10382 * @return {OO.ui.TextInputWidget} Text input widget
10384 OO
.ui
.ComboBoxInputWidget
.prototype.getInput = function () {
10389 * Handle input change events.
10392 * @param {string} value New value
10394 OO
.ui
.ComboBoxInputWidget
.prototype.onInputChange = function ( value
) {
10395 var match
= this.menu
.getItemFromData( value
);
10397 this.menu
.selectItem( match
);
10398 if ( this.menu
.getHighlightedItem() ) {
10399 this.menu
.highlightItem( match
);
10402 if ( !this.isDisabled() ) {
10403 this.menu
.toggle( true );
10408 * Handle input enter events.
10412 OO
.ui
.ComboBoxInputWidget
.prototype.onInputEnter = function () {
10413 if ( !this.isDisabled() ) {
10414 this.menu
.toggle( false );
10419 * Handle button click events.
10423 OO
.ui
.ComboBoxInputWidget
.prototype.onDropdownButtonClick = function () {
10424 this.menu
.toggle();
10425 this.$input
[ 0 ].focus();
10429 * Handle menu choose events.
10432 * @param {OO.ui.OptionWidget} item Chosen item
10434 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuChoose = function ( item
) {
10435 this.setValue( item
.getData() );
10439 * Handle menu item change events.
10443 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuItemsChange = function () {
10444 var match
= this.menu
.getItemFromData( this.getValue() );
10445 this.menu
.selectItem( match
);
10446 if ( this.menu
.getHighlightedItem() ) {
10447 this.menu
.highlightItem( match
);
10449 this.$element
.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu
.isEmpty() );
10455 OO
.ui
.ComboBoxInputWidget
.prototype.setDisabled = function ( disabled
) {
10457 OO
.ui
.ComboBoxInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
10459 if ( this.dropdownButton
) {
10460 this.dropdownButton
.setDisabled( this.isDisabled() );
10463 this.menu
.setDisabled( this.isDisabled() );
10470 * Set the options available for this input.
10472 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10475 OO
.ui
.ComboBoxInputWidget
.prototype.setOptions = function ( options
) {
10478 .addItems( options
.map( function ( opt
) {
10479 return new OO
.ui
.MenuOptionWidget( {
10481 label
: opt
.label
!== undefined ? opt
.label
: opt
.data
10489 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
10490 * which is a widget that is specified by reference before any optional configuration settings.
10492 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
10494 * - **left**: The label is placed before the field-widget and aligned with the left margin.
10495 * A left-alignment is used for forms with many fields.
10496 * - **right**: The label is placed before the field-widget and aligned to the right margin.
10497 * A right-alignment is used for long but familiar forms which users tab through,
10498 * verifying the current field with a quick glance at the label.
10499 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
10500 * that users fill out from top to bottom.
10501 * - **inline**: The label is placed after the field-widget and aligned to the left.
10502 * An inline-alignment is best used with checkboxes or radio buttons.
10504 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
10505 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
10507 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
10510 * @extends OO.ui.Layout
10511 * @mixins OO.ui.mixin.LabelElement
10512 * @mixins OO.ui.mixin.TitledElement
10515 * @param {OO.ui.Widget} fieldWidget Field widget
10516 * @param {Object} [config] Configuration options
10517 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
10518 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
10519 * The array may contain strings or OO.ui.HtmlSnippet instances.
10520 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
10521 * The array may contain strings or OO.ui.HtmlSnippet instances.
10522 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
10523 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
10524 * For important messages, you are advised to use `notices`, as they are always shown.
10525 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
10527 * @throws {Error} An error is thrown if no widget is specified
10529 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
10530 // Allow passing positional parameters inside the config object
10531 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
10532 config
= fieldWidget
;
10533 fieldWidget
= config
.fieldWidget
;
10536 // Make sure we have required constructor arguments
10537 if ( fieldWidget
=== undefined ) {
10538 throw new Error( 'Widget not found' );
10541 // Configuration initialization
10542 config
= $.extend( { align
: 'left' }, config
);
10544 // Parent constructor
10545 OO
.ui
.FieldLayout
.parent
.call( this, config
);
10547 // Mixin constructors
10548 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, {
10549 $label
: $( '<label>' )
10551 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
10554 this.fieldWidget
= fieldWidget
;
10557 this.$field
= this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
10558 this.$messages
= $( '<ul>' );
10559 this.$header
= $( '<span>' );
10560 this.$body
= $( '<div>' );
10562 if ( config
.help
) {
10563 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
10564 $overlay
: config
.$overlay
,
10568 classes
: [ 'oo-ui-fieldLayout-help' ],
10572 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
10573 this.popupButtonWidget
.getPopup().$body
.html( config
.help
.toString() );
10575 this.popupButtonWidget
.getPopup().$body
.text( config
.help
);
10577 this.$help
= this.popupButtonWidget
.$element
;
10579 this.$help
= $( [] );
10583 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
10586 if ( fieldWidget
.constructor.static.supportsSimpleLabel
) {
10587 if ( this.fieldWidget
.getInputId() ) {
10588 this.$label
.attr( 'for', this.fieldWidget
.getInputId() );
10590 this.$label
.on( 'click', function () {
10591 this.fieldWidget
.focus();
10597 .addClass( 'oo-ui-fieldLayout' )
10598 .toggleClass( 'oo-ui-fieldLayout-disabled', this.fieldWidget
.isDisabled() )
10599 .append( this.$body
);
10600 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
10601 this.$header
.addClass( 'oo-ui-fieldLayout-header' );
10602 this.$messages
.addClass( 'oo-ui-fieldLayout-messages' );
10604 .addClass( 'oo-ui-fieldLayout-field' )
10605 .append( this.fieldWidget
.$element
);
10607 this.setErrors( config
.errors
|| [] );
10608 this.setNotices( config
.notices
|| [] );
10609 this.setAlignment( config
.align
);
10614 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
10615 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.LabelElement
);
10616 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.TitledElement
);
10621 * Handle field disable events.
10624 * @param {boolean} value Field is disabled
10626 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
10627 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
10631 * Get the widget contained by the field.
10633 * @return {OO.ui.Widget} Field widget
10635 OO
.ui
.FieldLayout
.prototype.getField = function () {
10636 return this.fieldWidget
;
10640 * Return `true` if the given field widget can be used with `'inline'` alignment (see
10641 * #setAlignment). Return `false` if it can't or if this can't be determined.
10643 * @return {boolean}
10645 OO
.ui
.FieldLayout
.prototype.isFieldInline = function () {
10646 // This is very simplistic, but should be good enough.
10647 return this.getField().$element
.prop( 'tagName' ).toLowerCase() === 'span';
10652 * @param {string} kind 'error' or 'notice'
10653 * @param {string|OO.ui.HtmlSnippet} text
10656 OO
.ui
.FieldLayout
.prototype.makeMessage = function ( kind
, text
) {
10657 var $listItem
, $icon
, message
;
10658 $listItem
= $( '<li>' );
10659 if ( kind
=== 'error' ) {
10660 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'warning' ] } ).$element
;
10661 } else if ( kind
=== 'notice' ) {
10662 $icon
= new OO
.ui
.IconWidget( { icon
: 'info' } ).$element
;
10666 message
= new OO
.ui
.LabelWidget( { label
: text
} );
10668 .append( $icon
, message
.$element
)
10669 .addClass( 'oo-ui-fieldLayout-messages-' + kind
);
10674 * Set the field alignment mode.
10677 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
10680 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
10681 if ( value
!== this.align
) {
10682 // Default to 'left'
10683 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
10687 if ( value
=== 'inline' && !this.isFieldInline() ) {
10690 // Reorder elements
10691 if ( value
=== 'top' ) {
10692 this.$header
.append( this.$label
, this.$help
);
10693 this.$body
.append( this.$header
, this.$field
);
10694 } else if ( value
=== 'inline' ) {
10695 this.$header
.append( this.$label
, this.$help
);
10696 this.$body
.append( this.$field
, this.$header
);
10698 this.$header
.append( this.$label
);
10699 this.$body
.append( this.$header
, this.$help
, this.$field
);
10701 // Set classes. The following classes can be used here:
10702 // * oo-ui-fieldLayout-align-left
10703 // * oo-ui-fieldLayout-align-right
10704 // * oo-ui-fieldLayout-align-top
10705 // * oo-ui-fieldLayout-align-inline
10706 if ( this.align
) {
10707 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
10709 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
10710 this.align
= value
;
10717 * Set the list of error messages.
10719 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
10720 * The array may contain strings or OO.ui.HtmlSnippet instances.
10723 OO
.ui
.FieldLayout
.prototype.setErrors = function ( errors
) {
10724 this.errors
= errors
.slice();
10725 this.updateMessages();
10730 * Set the list of notice messages.
10732 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
10733 * The array may contain strings or OO.ui.HtmlSnippet instances.
10736 OO
.ui
.FieldLayout
.prototype.setNotices = function ( notices
) {
10737 this.notices
= notices
.slice();
10738 this.updateMessages();
10743 * Update the rendering of error and notice messages.
10747 OO
.ui
.FieldLayout
.prototype.updateMessages = function () {
10749 this.$messages
.empty();
10751 if ( this.errors
.length
|| this.notices
.length
) {
10752 this.$body
.after( this.$messages
);
10754 this.$messages
.remove();
10758 for ( i
= 0; i
< this.notices
.length
; i
++ ) {
10759 this.$messages
.append( this.makeMessage( 'notice', this.notices
[ i
] ) );
10761 for ( i
= 0; i
< this.errors
.length
; i
++ ) {
10762 this.$messages
.append( this.makeMessage( 'error', this.errors
[ i
] ) );
10767 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
10768 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
10769 * is required and is specified before any optional configuration settings.
10771 * Labels can be aligned in one of four ways:
10773 * - **left**: The label is placed before the field-widget and aligned with the left margin.
10774 * A left-alignment is used for forms with many fields.
10775 * - **right**: The label is placed before the field-widget and aligned to the right margin.
10776 * A right-alignment is used for long but familiar forms which users tab through,
10777 * verifying the current field with a quick glance at the label.
10778 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
10779 * that users fill out from top to bottom.
10780 * - **inline**: The label is placed after the field-widget and aligned to the left.
10781 * An inline-alignment is best used with checkboxes or radio buttons.
10783 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
10784 * text is specified.
10787 * // Example of an ActionFieldLayout
10788 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
10789 * new OO.ui.TextInputWidget( {
10790 * placeholder: 'Field widget'
10792 * new OO.ui.ButtonWidget( {
10796 * label: 'An ActionFieldLayout. This label is aligned top',
10798 * help: 'This is help text'
10802 * $( 'body' ).append( actionFieldLayout.$element );
10805 * @extends OO.ui.FieldLayout
10808 * @param {OO.ui.Widget} fieldWidget Field widget
10809 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
10810 * @param {Object} config
10812 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
10813 // Allow passing positional parameters inside the config object
10814 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
10815 config
= fieldWidget
;
10816 fieldWidget
= config
.fieldWidget
;
10817 buttonWidget
= config
.buttonWidget
;
10820 // Parent constructor
10821 OO
.ui
.ActionFieldLayout
.parent
.call( this, fieldWidget
, config
);
10824 this.buttonWidget
= buttonWidget
;
10825 this.$button
= $( '<span>' );
10826 this.$input
= this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
10830 .addClass( 'oo-ui-actionFieldLayout' );
10832 .addClass( 'oo-ui-actionFieldLayout-button' )
10833 .append( this.buttonWidget
.$element
);
10835 .addClass( 'oo-ui-actionFieldLayout-input' )
10836 .append( this.fieldWidget
.$element
);
10838 .append( this.$input
, this.$button
);
10843 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
10846 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
10847 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
10848 * configured with a label as well. For more information and examples,
10849 * please see the [OOjs UI documentation on MediaWiki][1].
10852 * // Example of a fieldset layout
10853 * var input1 = new OO.ui.TextInputWidget( {
10854 * placeholder: 'A text input field'
10857 * var input2 = new OO.ui.TextInputWidget( {
10858 * placeholder: 'A text input field'
10861 * var fieldset = new OO.ui.FieldsetLayout( {
10862 * label: 'Example of a fieldset layout'
10865 * fieldset.addItems( [
10866 * new OO.ui.FieldLayout( input1, {
10867 * label: 'Field One'
10869 * new OO.ui.FieldLayout( input2, {
10870 * label: 'Field Two'
10873 * $( 'body' ).append( fieldset.$element );
10875 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
10878 * @extends OO.ui.Layout
10879 * @mixins OO.ui.mixin.IconElement
10880 * @mixins OO.ui.mixin.LabelElement
10881 * @mixins OO.ui.mixin.GroupElement
10884 * @param {Object} [config] Configuration options
10885 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
10886 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
10887 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
10888 * For important messages, you are advised to use `notices`, as they are always shown.
10889 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
10891 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
10892 // Configuration initialization
10893 config
= config
|| {};
10895 // Parent constructor
10896 OO
.ui
.FieldsetLayout
.parent
.call( this, config
);
10898 // Mixin constructors
10899 OO
.ui
.mixin
.IconElement
.call( this, config
);
10900 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: $( '<div>' ) } ) );
10901 OO
.ui
.mixin
.GroupElement
.call( this, config
);
10904 this.$header
= $( '<div>' );
10905 if ( config
.help
) {
10906 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
10907 $overlay
: config
.$overlay
,
10911 classes
: [ 'oo-ui-fieldsetLayout-help' ],
10915 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
10916 this.popupButtonWidget
.getPopup().$body
.html( config
.help
.toString() );
10918 this.popupButtonWidget
.getPopup().$body
.text( config
.help
);
10920 this.$help
= this.popupButtonWidget
.$element
;
10922 this.$help
= $( [] );
10927 .addClass( 'oo-ui-fieldsetLayout-header' )
10928 .append( this.$icon
, this.$label
, this.$help
);
10929 this.$group
.addClass( 'oo-ui-fieldsetLayout-group' );
10931 .addClass( 'oo-ui-fieldsetLayout' )
10932 .prepend( this.$header
, this.$group
);
10933 if ( Array
.isArray( config
.items
) ) {
10934 this.addItems( config
.items
);
10940 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
10941 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.IconElement
);
10942 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.LabelElement
);
10943 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.GroupElement
);
10945 /* Static Properties */
10951 OO
.ui
.FieldsetLayout
.static.tagName
= 'fieldset';
10954 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
10955 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
10956 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
10957 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
10959 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
10960 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
10961 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
10962 * some fancier controls. Some controls have both regular and InputWidget variants, for example
10963 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
10964 * often have simplified APIs to match the capabilities of HTML forms.
10965 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
10967 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
10968 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
10971 * // Example of a form layout that wraps a fieldset layout
10972 * var input1 = new OO.ui.TextInputWidget( {
10973 * placeholder: 'Username'
10975 * var input2 = new OO.ui.TextInputWidget( {
10976 * placeholder: 'Password',
10979 * var submit = new OO.ui.ButtonInputWidget( {
10983 * var fieldset = new OO.ui.FieldsetLayout( {
10984 * label: 'A form layout'
10986 * fieldset.addItems( [
10987 * new OO.ui.FieldLayout( input1, {
10988 * label: 'Username',
10991 * new OO.ui.FieldLayout( input2, {
10992 * label: 'Password',
10995 * new OO.ui.FieldLayout( submit )
10997 * var form = new OO.ui.FormLayout( {
10998 * items: [ fieldset ],
10999 * action: '/api/formhandler',
11002 * $( 'body' ).append( form.$element );
11005 * @extends OO.ui.Layout
11006 * @mixins OO.ui.mixin.GroupElement
11009 * @param {Object} [config] Configuration options
11010 * @cfg {string} [method] HTML form `method` attribute
11011 * @cfg {string} [action] HTML form `action` attribute
11012 * @cfg {string} [enctype] HTML form `enctype` attribute
11013 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
11015 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
11018 // Configuration initialization
11019 config
= config
|| {};
11021 // Parent constructor
11022 OO
.ui
.FormLayout
.parent
.call( this, config
);
11024 // Mixin constructors
11025 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
11028 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
11030 // Make sure the action is safe
11031 action
= config
.action
;
11032 if ( action
!== undefined && !OO
.ui
.isSafeUrl( action
) ) {
11033 action
= './' + action
;
11038 .addClass( 'oo-ui-formLayout' )
11040 method
: config
.method
,
11042 enctype
: config
.enctype
11044 if ( Array
.isArray( config
.items
) ) {
11045 this.addItems( config
.items
);
11051 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
11052 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.mixin
.GroupElement
);
11057 * A 'submit' event is emitted when the form is submitted.
11062 /* Static Properties */
11068 OO
.ui
.FormLayout
.static.tagName
= 'form';
11073 * Handle form submit events.
11076 * @param {jQuery.Event} e Submit event
11079 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
11080 if ( this.emit( 'submit' ) ) {
11086 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
11087 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
11090 * // Example of a panel layout
11091 * var panel = new OO.ui.PanelLayout( {
11095 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
11097 * $( 'body' ).append( panel.$element );
11100 * @extends OO.ui.Layout
11103 * @param {Object} [config] Configuration options
11104 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
11105 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
11106 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
11107 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
11109 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
11110 // Configuration initialization
11111 config
= $.extend( {
11118 // Parent constructor
11119 OO
.ui
.PanelLayout
.parent
.call( this, config
);
11122 this.$element
.addClass( 'oo-ui-panelLayout' );
11123 if ( config
.scrollable
) {
11124 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
11126 if ( config
.padded
) {
11127 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
11129 if ( config
.expanded
) {
11130 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
11132 if ( config
.framed
) {
11133 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
11139 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
11144 * Focus the panel layout
11146 * The default implementation just focuses the first focusable element in the panel
11148 OO
.ui
.PanelLayout
.prototype.focus = function () {
11149 OO
.ui
.findFocusable( this.$element
).focus();
11153 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
11154 * items), with small margins between them. Convenient when you need to put a number of block-level
11155 * widgets on a single line next to each other.
11157 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
11160 * // HorizontalLayout with a text input and a label
11161 * var layout = new OO.ui.HorizontalLayout( {
11163 * new OO.ui.LabelWidget( { label: 'Label' } ),
11164 * new OO.ui.TextInputWidget( { value: 'Text' } )
11167 * $( 'body' ).append( layout.$element );
11170 * @extends OO.ui.Layout
11171 * @mixins OO.ui.mixin.GroupElement
11174 * @param {Object} [config] Configuration options
11175 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
11177 OO
.ui
.HorizontalLayout
= function OoUiHorizontalLayout( config
) {
11178 // Configuration initialization
11179 config
= config
|| {};
11181 // Parent constructor
11182 OO
.ui
.HorizontalLayout
.parent
.call( this, config
);
11184 // Mixin constructors
11185 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
11188 this.$element
.addClass( 'oo-ui-horizontalLayout' );
11189 if ( Array
.isArray( config
.items
) ) {
11190 this.addItems( config
.items
);
11196 OO
.inheritClass( OO
.ui
.HorizontalLayout
, OO
.ui
.Layout
);
11197 OO
.mixinClass( OO
.ui
.HorizontalLayout
, OO
.ui
.mixin
.GroupElement
);