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-05-10T00:55:40Z
16 * Namespace for all classes, static methods and static properties.
48 * Constants for MouseEvent.which
52 OO
.ui
.MouseButtons
= {
65 * Generate a unique ID for element
69 OO
.ui
.generateElementId = function () {
71 return 'oojsui-' + OO
.ui
.elementId
;
75 * Check if an element is focusable.
76 * Inspired by :focusable in jQueryUI v1.11.4 - 2015-04-14
78 * @param {jQuery} $element Element to test
79 * @return {boolean} Element is focusable
81 OO
.ui
.isFocusableElement = function ( $element
) {
83 element
= $element
[ 0 ];
85 // Anything disabled is not focusable
86 if ( element
.disabled
) {
90 // Check if the element is visible
92 // This is quicker than calling $element.is( ':visible' )
93 $.expr
.pseudos
.visible( element
) &&
94 // Check that all parents are visible
95 !$element
.parents().addBack().filter( function () {
96 return $.css( this, 'visibility' ) === 'hidden';
102 // Check if the element is ContentEditable, which is the string 'true'
103 if ( element
.contentEditable
=== 'true' ) {
107 // Anything with a non-negative numeric tabIndex is focusable.
108 // Use .prop to avoid browser bugs
109 if ( $element
.prop( 'tabIndex' ) >= 0 ) {
113 // Some element types are naturally focusable
114 // (indexOf is much faster than regex in Chrome and about the
115 // same in FF: https://jsperf.com/regex-vs-indexof-array2)
116 nodeName
= element
.nodeName
.toLowerCase();
117 if ( [ 'input', 'select', 'textarea', 'button', 'object' ].indexOf( nodeName
) !== -1 ) {
121 // Links and areas are focusable if they have an href
122 if ( ( nodeName
=== 'a' || nodeName
=== 'area' ) && $element
.attr( 'href' ) !== undefined ) {
130 * Find a focusable child
132 * @param {jQuery} $container Container to search in
133 * @param {boolean} [backwards] Search backwards
134 * @return {jQuery} Focusable child, or an empty jQuery object if none found
136 OO
.ui
.findFocusable = function ( $container
, backwards
) {
137 var $focusable
= $( [] ),
138 // $focusableCandidates is a superset of things that
139 // could get matched by isFocusableElement
140 $focusableCandidates
= $container
141 .find( 'input, select, textarea, button, object, a, area, [contenteditable], [tabindex]' );
144 $focusableCandidates
= Array
.prototype.reverse
.call( $focusableCandidates
);
147 $focusableCandidates
.each( function () {
148 var $this = $( this );
149 if ( OO
.ui
.isFocusableElement( $this ) ) {
158 * Get the user's language and any fallback languages.
160 * These language codes are used to localize user interface elements in the user's language.
162 * In environments that provide a localization system, this function should be overridden to
163 * return the user's language(s). The default implementation returns English (en) only.
165 * @return {string[]} Language codes, in descending order of priority
167 OO
.ui
.getUserLanguages = function () {
172 * Get a value in an object keyed by language code.
174 * @param {Object.<string,Mixed>} obj Object keyed by language code
175 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
176 * @param {string} [fallback] Fallback code, used if no matching language can be found
177 * @return {Mixed} Local value
179 OO
.ui
.getLocalValue = function ( obj
, lang
, fallback
) {
182 // Requested language
186 // Known user language
187 langs
= OO
.ui
.getUserLanguages();
188 for ( i
= 0, len
= langs
.length
; i
< len
; i
++ ) {
195 if ( obj
[ fallback
] ) {
196 return obj
[ fallback
];
198 // First existing language
199 for ( lang
in obj
) {
207 * Check if a node is contained within another node
209 * Similar to jQuery#contains except a list of containers can be supplied
210 * and a boolean argument allows you to include the container in the match list
212 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
213 * @param {HTMLElement} contained Node to find
214 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
215 * @return {boolean} The node is in the list of target nodes
217 OO
.ui
.contains = function ( containers
, contained
, matchContainers
) {
219 if ( !Array
.isArray( containers
) ) {
220 containers
= [ containers
];
222 for ( i
= containers
.length
- 1; i
>= 0; i
-- ) {
223 if ( ( matchContainers
&& contained
=== containers
[ i
] ) || $.contains( containers
[ i
], contained
) ) {
231 * Return a function, that, as long as it continues to be invoked, will not
232 * be triggered. The function will be called after it stops being called for
233 * N milliseconds. If `immediate` is passed, trigger the function on the
234 * leading edge, instead of the trailing.
236 * Ported from: http://underscorejs.org/underscore.js
238 * @param {Function} func Function to debounce
239 * @param {number} [wait=0] Wait period in milliseconds
240 * @param {boolean} [immediate] Trigger on leading edge
241 * @return {Function} Debounced function
243 OO
.ui
.debounce = function ( func
, wait
, immediate
) {
248 later = function () {
251 func
.apply( context
, args
);
254 if ( immediate
&& !timeout
) {
255 func
.apply( context
, args
);
257 if ( !timeout
|| wait
) {
258 clearTimeout( timeout
);
259 timeout
= setTimeout( later
, wait
);
265 * Puts a console warning with provided message.
267 * @param {string} message Message
269 OO
.ui
.warnDeprecation = function ( message
) {
270 if ( OO
.getProp( window
, 'console', 'warn' ) !== undefined ) {
271 // eslint-disable-next-line no-console
272 console
.warn( message
);
277 * Returns a function, that, when invoked, will only be triggered at most once
278 * during a given window of time. If called again during that window, it will
279 * wait until the window ends and then trigger itself again.
281 * As it's not knowable to the caller whether the function will actually run
282 * when the wrapper is called, return values from the function are entirely
285 * @param {Function} func Function to throttle
286 * @param {number} wait Throttle window length, in milliseconds
287 * @return {Function} Throttled function
289 OO
.ui
.throttle = function ( func
, wait
) {
290 var context
, args
, timeout
,
294 previous
= OO
.ui
.now();
295 func
.apply( context
, args
);
298 // Check how long it's been since the last time the function was
299 // called, and whether it's more or less than the requested throttle
300 // period. If it's less, run the function immediately. If it's more,
301 // set a timeout for the remaining time -- but don't replace an
302 // existing timeout, since that'd indefinitely prolong the wait.
303 var remaining
= wait
- ( OO
.ui
.now() - previous
);
306 if ( remaining
<= 0 ) {
307 // Note: unless wait was ridiculously large, this means we'll
308 // automatically run the first time the function was called in a
309 // given period. (If you provide a wait period larger than the
310 // current Unix timestamp, you *deserve* unexpected behavior.)
311 clearTimeout( timeout
);
313 } else if ( !timeout
) {
314 timeout
= setTimeout( run
, remaining
);
320 * A (possibly faster) way to get the current timestamp as an integer
322 * @return {number} Current timestamp, in milliseconds since the Unix epoch
324 OO
.ui
.now
= Date
.now
|| function () {
325 return new Date().getTime();
329 * Reconstitute a JavaScript object corresponding to a widget created by
330 * the PHP implementation.
332 * This is an alias for `OO.ui.Element.static.infuse()`.
334 * @param {string|HTMLElement|jQuery} idOrNode
335 * A DOM id (if a string) or node for the widget to infuse.
336 * @return {OO.ui.Element}
337 * The `OO.ui.Element` corresponding to this (infusable) document node.
339 OO
.ui
.infuse = function ( idOrNode
) {
340 return OO
.ui
.Element
.static.infuse( idOrNode
);
345 * Message store for the default implementation of OO.ui.msg
347 * Environments that provide a localization system should not use this, but should override
348 * OO.ui.msg altogether.
353 // Tool tip for a button that moves items in a list down one place
354 'ooui-outline-control-move-down': 'Move item down',
355 // Tool tip for a button that moves items in a list up one place
356 'ooui-outline-control-move-up': 'Move item up',
357 // Tool tip for a button that removes items from a list
358 'ooui-outline-control-remove': 'Remove item',
359 // Label for the toolbar group that contains a list of all other available tools
360 'ooui-toolbar-more': 'More',
361 // Label for the fake tool that expands the full list of tools in a toolbar group
362 'ooui-toolgroup-expand': 'More',
363 // Label for the fake tool that collapses the full list of tools in a toolbar group
364 'ooui-toolgroup-collapse': 'Fewer',
365 // Default label for the accept button of a confirmation dialog
366 'ooui-dialog-message-accept': 'OK',
367 // Default label for the reject button of a confirmation dialog
368 'ooui-dialog-message-reject': 'Cancel',
369 // Title for process dialog error description
370 'ooui-dialog-process-error': 'Something went wrong',
371 // Label for process dialog dismiss error button, visible when describing errors
372 'ooui-dialog-process-dismiss': 'Dismiss',
373 // Label for process dialog retry action button, visible when describing only recoverable errors
374 'ooui-dialog-process-retry': 'Try again',
375 // Label for process dialog retry action button, visible when describing only warnings
376 'ooui-dialog-process-continue': 'Continue',
377 // Label for the file selection widget's select file button
378 'ooui-selectfile-button-select': 'Select a file',
379 // Label for the file selection widget if file selection is not supported
380 'ooui-selectfile-not-supported': 'File selection is not supported',
381 // Label for the file selection widget when no file is currently selected
382 'ooui-selectfile-placeholder': 'No file is selected',
383 // Label for the file selection widget's drop target
384 'ooui-selectfile-dragdrop-placeholder': 'Drop file here'
388 * Get a localized message.
390 * After the message key, message parameters may optionally be passed. In the default implementation,
391 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
392 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
393 * they support unnamed, ordered message parameters.
395 * In environments that provide a localization system, this function should be overridden to
396 * return the message translated in the user's language. The default implementation always returns
397 * English messages. An example of doing this with [jQuery.i18n](https://github.com/wikimedia/jquery.i18n)
401 * var i, iLen, button,
402 * messagePath = 'oojs-ui/dist/i18n/',
403 * languages = [ $.i18n().locale, 'ur', 'en' ],
406 * for ( i = 0, iLen = languages.length; i < iLen; i++ ) {
407 * languageMap[ languages[ i ] ] = messagePath + languages[ i ].toLowerCase() + '.json';
410 * $.i18n().load( languageMap ).done( function() {
411 * // Replace the built-in `msg` only once we've loaded the internationalization.
412 * // OOjs UI uses `OO.ui.deferMsg` for all initially-loaded messages. So long as
413 * // you put off creating any widgets until this promise is complete, no English
414 * // will be displayed.
415 * OO.ui.msg = $.i18n;
417 * // A button displaying "OK" in the default locale
418 * button = new OO.ui.ButtonWidget( {
419 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
422 * $( 'body' ).append( button.$element );
424 * // A button displaying "OK" in Urdu
425 * $.i18n().locale = 'ur';
426 * button = new OO.ui.ButtonWidget( {
427 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
430 * $( 'body' ).append( button.$element );
433 * @param {string} key Message key
434 * @param {...Mixed} [params] Message parameters
435 * @return {string} Translated message with parameters substituted
437 OO
.ui
.msg = function ( key
) {
438 var message
= messages
[ key
],
439 params
= Array
.prototype.slice
.call( arguments
, 1 );
440 if ( typeof message
=== 'string' ) {
441 // Perform $1 substitution
442 message
= message
.replace( /\$(\d+)/g, function ( unused
, n
) {
443 var i
= parseInt( n
, 10 );
444 return params
[ i
- 1 ] !== undefined ? params
[ i
- 1 ] : '$' + n
;
447 // Return placeholder if message not found
448 message
= '[' + key
+ ']';
455 * Package a message and arguments for deferred resolution.
457 * Use this when you are statically specifying a message and the message may not yet be present.
459 * @param {string} key Message key
460 * @param {...Mixed} [params] Message parameters
461 * @return {Function} Function that returns the resolved message when executed
463 OO
.ui
.deferMsg = function () {
464 var args
= arguments
;
466 return OO
.ui
.msg
.apply( OO
.ui
, args
);
473 * If the message is a function it will be executed, otherwise it will pass through directly.
475 * @param {Function|string} msg Deferred message, or message text
476 * @return {string} Resolved message
478 OO
.ui
.resolveMsg = function ( msg
) {
479 if ( $.isFunction( msg
) ) {
486 * @param {string} url
489 OO
.ui
.isSafeUrl = function ( url
) {
490 // Keep this function in sync with php/Tag.php
491 var i
, protocolWhitelist
;
493 function stringStartsWith( haystack
, needle
) {
494 return haystack
.substr( 0, needle
.length
) === needle
;
497 protocolWhitelist
= [
498 'bitcoin', 'ftp', 'ftps', 'geo', 'git', 'gopher', 'http', 'https', 'irc', 'ircs',
499 'magnet', 'mailto', 'mms', 'news', 'nntp', 'redis', 'sftp', 'sip', 'sips', 'sms', 'ssh',
500 'svn', 'tel', 'telnet', 'urn', 'worldwind', 'xmpp'
507 for ( i
= 0; i
< protocolWhitelist
.length
; i
++ ) {
508 if ( stringStartsWith( url
, protocolWhitelist
[ i
] + ':' ) ) {
513 // This matches '//' too
514 if ( stringStartsWith( url
, '/' ) || stringStartsWith( url
, './' ) ) {
517 if ( stringStartsWith( url
, '?' ) || stringStartsWith( url
, '#' ) ) {
525 * Check if the user has a 'mobile' device.
527 * For our purposes this means the user is primarily using an
528 * on-screen keyboard, touch input instead of a mouse and may
529 * have a physically small display.
531 * It is left up to implementors to decide how to compute this
532 * so the default implementation always returns false.
534 * @return {boolean} Use is on a mobile device
536 OO
.ui
.isMobile = function () {
545 * Namespace for OOjs UI mixins.
547 * Mixins are named according to the type of object they are intended to
548 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
549 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
550 * is intended to be mixed in to an instance of OO.ui.Widget.
558 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
559 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
560 * connected to them and can't be interacted with.
566 * @param {Object} [config] Configuration options
567 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
568 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
570 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
571 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
572 * @cfg {string} [text] Text to insert
573 * @cfg {Array} [content] An array of content elements to append (after #text).
574 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
575 * Instances of OO.ui.Element will have their $element appended.
576 * @cfg {jQuery} [$content] Content elements to append (after #text).
577 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
578 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
579 * Data can also be specified with the #setData method.
581 OO
.ui
.Element
= function OoUiElement( config
) {
582 // Configuration initialization
583 config
= config
|| {};
587 this.elementId
= null;
589 this.data
= config
.data
;
590 this.$element
= config
.$element
||
591 $( document
.createElement( this.getTagName() ) );
592 this.elementGroup
= null;
595 if ( Array
.isArray( config
.classes
) ) {
596 this.$element
.addClass( config
.classes
.join( ' ' ) );
599 this.setElementId( config
.id
);
602 this.$element
.text( config
.text
);
604 if ( config
.content
) {
605 // The `content` property treats plain strings as text; use an
606 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
607 // appropriate $element appended.
608 this.$element
.append( config
.content
.map( function ( v
) {
609 if ( typeof v
=== 'string' ) {
610 // Escape string so it is properly represented in HTML.
611 return document
.createTextNode( v
);
612 } else if ( v
instanceof OO
.ui
.HtmlSnippet
) {
615 } else if ( v
instanceof OO
.ui
.Element
) {
621 if ( config
.$content
) {
622 // The `$content` property treats plain strings as HTML.
623 this.$element
.append( config
.$content
);
629 OO
.initClass( OO
.ui
.Element
);
631 /* Static Properties */
634 * The name of the HTML tag used by the element.
636 * The static value may be ignored if the #getTagName method is overridden.
642 OO
.ui
.Element
.static.tagName
= 'div';
647 * Reconstitute a JavaScript object corresponding to a widget created
648 * by the PHP implementation.
650 * @param {string|HTMLElement|jQuery} idOrNode
651 * A DOM id (if a string) or node for the widget to infuse.
652 * @return {OO.ui.Element}
653 * The `OO.ui.Element` corresponding to this (infusable) document node.
654 * For `Tag` objects emitted on the HTML side (used occasionally for content)
655 * the value returned is a newly-created Element wrapping around the existing
658 OO
.ui
.Element
.static.infuse = function ( idOrNode
) {
659 var obj
= OO
.ui
.Element
.static.unsafeInfuse( idOrNode
, false );
660 // Verify that the type matches up.
661 // FIXME: uncomment after T89721 is fixed (see T90929)
663 if ( !( obj instanceof this['class'] ) ) {
664 throw new Error( 'Infusion type mismatch!' );
671 * Implementation helper for `infuse`; skips the type check and has an
672 * extra property so that only the top-level invocation touches the DOM.
675 * @param {string|HTMLElement|jQuery} idOrNode
676 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
677 * when the top-level widget of this infusion is inserted into DOM,
678 * replacing the original node; or false for top-level invocation.
679 * @return {OO.ui.Element}
681 OO
.ui
.Element
.static.unsafeInfuse = function ( idOrNode
, domPromise
) {
682 // look for a cached result of a previous infusion.
683 var id
, $elem
, data
, cls
, parts
, parent
, obj
, top
, state
, infusedChildren
;
684 if ( typeof idOrNode
=== 'string' ) {
686 $elem
= $( document
.getElementById( id
) );
688 $elem
= $( idOrNode
);
689 id
= $elem
.attr( 'id' );
691 if ( !$elem
.length
) {
692 throw new Error( 'Widget not found: ' + id
);
694 if ( $elem
[ 0 ].oouiInfused
) {
695 $elem
= $elem
[ 0 ].oouiInfused
;
697 data
= $elem
.data( 'ooui-infused' );
700 if ( data
=== true ) {
701 throw new Error( 'Circular dependency! ' + id
);
704 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
705 state
= data
.constructor.static.gatherPreInfuseState( $elem
, data
);
706 // restore dynamic state after the new element is re-inserted into DOM under infused parent
707 domPromise
.done( data
.restorePreInfuseState
.bind( data
, state
) );
708 infusedChildren
= $elem
.data( 'ooui-infused-children' );
709 if ( infusedChildren
&& infusedChildren
.length
) {
710 infusedChildren
.forEach( function ( data
) {
711 var state
= data
.constructor.static.gatherPreInfuseState( $elem
, data
);
712 domPromise
.done( data
.restorePreInfuseState
.bind( data
, state
) );
718 data
= $elem
.attr( 'data-ooui' );
720 throw new Error( 'No infusion data found: ' + id
);
723 data
= JSON
.parse( data
);
727 if ( !( data
&& data
._
) ) {
728 throw new Error( 'No valid infusion data found: ' + id
);
730 if ( data
._
=== 'Tag' ) {
731 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
732 return new OO
.ui
.Element( { $element
: $elem
} );
734 parts
= data
._
.split( '.' );
735 cls
= OO
.getProp
.apply( OO
, [ window
].concat( parts
) );
736 if ( cls
=== undefined ) {
737 // The PHP output might be old and not including the "OO.ui" prefix
738 // TODO: Remove this back-compat after next major release
739 cls
= OO
.getProp
.apply( OO
, [ OO
.ui
].concat( parts
) );
740 if ( cls
=== undefined ) {
741 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
745 // Verify that we're creating an OO.ui.Element instance
748 while ( parent
!== undefined ) {
749 if ( parent
=== OO
.ui
.Element
) {
754 parent
= parent
.parent
;
757 if ( parent
!== OO
.ui
.Element
) {
758 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
761 if ( domPromise
=== false ) {
763 domPromise
= top
.promise();
765 $elem
.data( 'ooui-infused', true ); // prevent loops
766 data
.id
= id
; // implicit
767 infusedChildren
= [];
768 data
= OO
.copy( data
, null, function deserialize( value
) {
770 if ( OO
.isPlainObject( value
) ) {
772 infused
= OO
.ui
.Element
.static.unsafeInfuse( value
.tag
, domPromise
);
773 infusedChildren
.push( infused
);
774 // Flatten the structure
775 infusedChildren
.push
.apply( infusedChildren
, infused
.$element
.data( 'ooui-infused-children' ) || [] );
776 infused
.$element
.removeData( 'ooui-infused-children' );
779 if ( value
.html
!== undefined ) {
780 return new OO
.ui
.HtmlSnippet( value
.html
);
784 // allow widgets to reuse parts of the DOM
785 data
= cls
.static.reusePreInfuseDOM( $elem
[ 0 ], data
);
786 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
787 state
= cls
.static.gatherPreInfuseState( $elem
[ 0 ], data
);
789 // eslint-disable-next-line new-cap
790 obj
= new cls( data
);
791 // now replace old DOM with this new DOM.
793 // An efficient constructor might be able to reuse the entire DOM tree of the original element,
794 // so only mutate the DOM if we need to.
795 if ( $elem
[ 0 ] !== obj
.$element
[ 0 ] ) {
796 $elem
.replaceWith( obj
.$element
);
797 // This element is now gone from the DOM, but if anyone is holding a reference to it,
798 // let's allow them to OO.ui.infuse() it and do what they expect (T105828).
799 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
800 $elem
[ 0 ].oouiInfused
= obj
.$element
;
804 obj
.$element
.data( 'ooui-infused', obj
);
805 obj
.$element
.data( 'ooui-infused-children', infusedChildren
);
806 // set the 'data-ooui' attribute so we can identify infused widgets
807 obj
.$element
.attr( 'data-ooui', '' );
808 // restore dynamic state after the new element is inserted into DOM
809 domPromise
.done( obj
.restorePreInfuseState
.bind( obj
, state
) );
814 * Pick out parts of `node`'s DOM to be reused when infusing a widget.
816 * This method **must not** make any changes to the DOM, only find interesting pieces and add them
817 * to `config` (which should then be returned). Actual DOM juggling should then be done by the
818 * constructor, which will be given the enhanced config.
821 * @param {HTMLElement} node
822 * @param {Object} config
825 OO
.ui
.Element
.static.reusePreInfuseDOM = function ( node
, config
) {
830 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of an HTML DOM node
831 * (and its children) that represent an Element of the same class and the given configuration,
832 * generated by the PHP implementation.
834 * This method is called just before `node` is detached from the DOM. The return value of this
835 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
836 * is inserted into DOM to replace `node`.
839 * @param {HTMLElement} node
840 * @param {Object} config
843 OO
.ui
.Element
.static.gatherPreInfuseState = function () {
848 * Get a jQuery function within a specific document.
851 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
852 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
854 * @return {Function} Bound jQuery function
856 OO
.ui
.Element
.static.getJQuery = function ( context
, $iframe
) {
857 function wrapper( selector
) {
858 return $( selector
, wrapper
.context
);
861 wrapper
.context
= this.getDocument( context
);
864 wrapper
.$iframe
= $iframe
;
871 * Get the document of an element.
874 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
875 * @return {HTMLDocument|null} Document object
877 OO
.ui
.Element
.static.getDocument = function ( obj
) {
878 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
879 return ( obj
[ 0 ] && obj
[ 0 ].ownerDocument
) ||
880 // Empty jQuery selections might have a context
887 ( obj
.nodeType
=== Node
.DOCUMENT_NODE
&& obj
) ||
892 * Get the window of an element or document.
895 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
896 * @return {Window} Window object
898 OO
.ui
.Element
.static.getWindow = function ( obj
) {
899 var doc
= this.getDocument( obj
);
900 return doc
.defaultView
;
904 * Get the direction of an element or document.
907 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
908 * @return {string} Text direction, either 'ltr' or 'rtl'
910 OO
.ui
.Element
.static.getDir = function ( obj
) {
913 if ( obj
instanceof jQuery
) {
916 isDoc
= obj
.nodeType
=== Node
.DOCUMENT_NODE
;
917 isWin
= obj
.document
!== undefined;
918 if ( isDoc
|| isWin
) {
924 return $( obj
).css( 'direction' );
928 * Get the offset between two frames.
930 * TODO: Make this function not use recursion.
933 * @param {Window} from Window of the child frame
934 * @param {Window} [to=window] Window of the parent frame
935 * @param {Object} [offset] Offset to start with, used internally
936 * @return {Object} Offset object, containing left and top properties
938 OO
.ui
.Element
.static.getFrameOffset = function ( from, to
, offset
) {
939 var i
, len
, frames
, frame
, rect
;
945 offset
= { top
: 0, left
: 0 };
947 if ( from.parent
=== from ) {
951 // Get iframe element
952 frames
= from.parent
.document
.getElementsByTagName( 'iframe' );
953 for ( i
= 0, len
= frames
.length
; i
< len
; i
++ ) {
954 if ( frames
[ i
].contentWindow
=== from ) {
960 // Recursively accumulate offset values
962 rect
= frame
.getBoundingClientRect();
963 offset
.left
+= rect
.left
;
964 offset
.top
+= rect
.top
;
966 this.getFrameOffset( from.parent
, offset
);
973 * Get the offset between two elements.
975 * The two elements may be in a different frame, but in that case the frame $element is in must
976 * be contained in the frame $anchor is in.
979 * @param {jQuery} $element Element whose position to get
980 * @param {jQuery} $anchor Element to get $element's position relative to
981 * @return {Object} Translated position coordinates, containing top and left properties
983 OO
.ui
.Element
.static.getRelativePosition = function ( $element
, $anchor
) {
984 var iframe
, iframePos
,
985 pos
= $element
.offset(),
986 anchorPos
= $anchor
.offset(),
987 elementDocument
= this.getDocument( $element
),
988 anchorDocument
= this.getDocument( $anchor
);
990 // If $element isn't in the same document as $anchor, traverse up
991 while ( elementDocument
!== anchorDocument
) {
992 iframe
= elementDocument
.defaultView
.frameElement
;
994 throw new Error( '$element frame is not contained in $anchor frame' );
996 iframePos
= $( iframe
).offset();
997 pos
.left
+= iframePos
.left
;
998 pos
.top
+= iframePos
.top
;
999 elementDocument
= iframe
.ownerDocument
;
1001 pos
.left
-= anchorPos
.left
;
1002 pos
.top
-= anchorPos
.top
;
1007 * Get element border sizes.
1010 * @param {HTMLElement} el Element to measure
1011 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1013 OO
.ui
.Element
.static.getBorders = function ( el
) {
1014 var doc
= el
.ownerDocument
,
1015 win
= doc
.defaultView
,
1016 style
= win
.getComputedStyle( el
, null ),
1018 top
= parseFloat( style
? style
.borderTopWidth
: $el
.css( 'borderTopWidth' ) ) || 0,
1019 left
= parseFloat( style
? style
.borderLeftWidth
: $el
.css( 'borderLeftWidth' ) ) || 0,
1020 bottom
= parseFloat( style
? style
.borderBottomWidth
: $el
.css( 'borderBottomWidth' ) ) || 0,
1021 right
= parseFloat( style
? style
.borderRightWidth
: $el
.css( 'borderRightWidth' ) ) || 0;
1032 * Get dimensions of an element or window.
1035 * @param {HTMLElement|Window} el Element to measure
1036 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1038 OO
.ui
.Element
.static.getDimensions = function ( el
) {
1040 doc
= el
.ownerDocument
|| el
.document
,
1041 win
= doc
.defaultView
;
1043 if ( win
=== el
|| el
=== doc
.documentElement
) {
1046 borders
: { top
: 0, left
: 0, bottom
: 0, right
: 0 },
1048 top
: $win
.scrollTop(),
1049 left
: $win
.scrollLeft()
1051 scrollbar
: { right
: 0, bottom
: 0 },
1055 bottom
: $win
.innerHeight(),
1056 right
: $win
.innerWidth()
1062 borders
: this.getBorders( el
),
1064 top
: $el
.scrollTop(),
1065 left
: $el
.scrollLeft()
1068 right
: $el
.innerWidth() - el
.clientWidth
,
1069 bottom
: $el
.innerHeight() - el
.clientHeight
1071 rect
: el
.getBoundingClientRect()
1077 * Get the number of pixels that an element's content is scrolled to the left.
1079 * Adapted from <https://github.com/othree/jquery.rtl-scroll-type>.
1080 * Original code copyright 2012 Wei-Ko Kao, licensed under the MIT License.
1082 * This function smooths out browser inconsistencies (nicely described in the README at
1083 * <https://github.com/othree/jquery.rtl-scroll-type>) and produces a result consistent
1084 * with Firefox's 'scrollLeft', which seems the sanest.
1088 * @param {HTMLElement|Window} el Element to measure
1089 * @return {number} Scroll position from the left.
1090 * If the element's direction is LTR, this is a positive number between `0` (initial scroll position)
1091 * and `el.scrollWidth - el.clientWidth` (furthest possible scroll position).
1092 * If the element's direction is RTL, this is a negative number between `0` (initial scroll position)
1093 * and `-el.scrollWidth + el.clientWidth` (furthest possible scroll position).
1095 OO
.ui
.Element
.static.getScrollLeft
= ( function () {
1096 var rtlScrollType
= null;
1099 var $definer
= $( '<div dir="rtl" style="font-size: 14px; width: 1px; height: 1px; position: absolute; top: -1000px; overflow: scroll">A</div>' ),
1100 definer
= $definer
[ 0 ];
1102 $definer
.appendTo( 'body' );
1103 if ( definer
.scrollLeft
> 0 ) {
1105 rtlScrollType
= 'default';
1107 definer
.scrollLeft
= 1;
1108 if ( definer
.scrollLeft
=== 0 ) {
1109 // Firefox, old Opera
1110 rtlScrollType
= 'negative';
1112 // Internet Explorer, Edge
1113 rtlScrollType
= 'reverse';
1119 return function getScrollLeft( el
) {
1120 var isRoot
= el
.window
=== el
||
1121 el
=== el
.ownerDocument
.body
||
1122 el
=== el
.ownerDocument
.documentElement
,
1123 scrollLeft
= isRoot
? $( window
).scrollLeft() : el
.scrollLeft
,
1124 // All browsers use the correct scroll type ('negative') on the root, so don't
1125 // do any fixups when looking at the root element
1126 direction
= isRoot
? 'ltr' : $( el
).css( 'direction' );
1128 if ( direction
=== 'rtl' ) {
1129 if ( rtlScrollType
=== null ) {
1132 if ( rtlScrollType
=== 'reverse' ) {
1133 scrollLeft
= -scrollLeft
;
1134 } else if ( rtlScrollType
=== 'default' ) {
1135 scrollLeft
= scrollLeft
- el
.scrollWidth
+ el
.clientWidth
;
1144 * Get the root scrollable element of given element's document.
1146 * On Blink-based browsers (Chrome etc.), `document.documentElement` can't be used to get or set
1147 * the scrollTop property; instead we have to use `document.body`. Changing and testing the value
1148 * lets us use 'body' or 'documentElement' based on what is working.
1150 * https://code.google.com/p/chromium/issues/detail?id=303131
1153 * @param {HTMLElement} el Element to find root scrollable parent for
1154 * @return {HTMLElement} Scrollable parent, `document.body` or `document.documentElement`
1155 * depending on browser
1157 OO
.ui
.Element
.static.getRootScrollableElement = function ( el
) {
1158 var scrollTop
, body
;
1160 if ( OO
.ui
.scrollableElement
=== undefined ) {
1161 body
= el
.ownerDocument
.body
;
1162 scrollTop
= body
.scrollTop
;
1165 if ( body
.scrollTop
=== 1 ) {
1166 body
.scrollTop
= scrollTop
;
1167 OO
.ui
.scrollableElement
= 'body';
1169 OO
.ui
.scrollableElement
= 'documentElement';
1173 return el
.ownerDocument
[ OO
.ui
.scrollableElement
];
1177 * Get closest scrollable container.
1179 * Traverses up until either a scrollable element or the root is reached, in which case the root
1180 * scrollable element will be returned (see #getRootScrollableElement).
1183 * @param {HTMLElement} el Element to find scrollable container for
1184 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1185 * @return {HTMLElement} Closest scrollable container
1187 OO
.ui
.Element
.static.getClosestScrollableContainer = function ( el
, dimension
) {
1189 // Browsers do not correctly return the computed value of 'overflow' when 'overflow-x' and
1190 // 'overflow-y' have different values, so we need to check the separate properties.
1191 props
= [ 'overflow-x', 'overflow-y' ],
1192 $parent
= $( el
).parent();
1194 if ( dimension
=== 'x' || dimension
=== 'y' ) {
1195 props
= [ 'overflow-' + dimension
];
1198 // Special case for the document root (which doesn't really have any scrollable container, since
1199 // it is the ultimate scrollable container, but this is probably saner than null or exception)
1200 if ( $( el
).is( 'html, body' ) ) {
1201 return this.getRootScrollableElement( el
);
1204 while ( $parent
.length
) {
1205 if ( $parent
[ 0 ] === this.getRootScrollableElement( el
) ) {
1206 return $parent
[ 0 ];
1210 val
= $parent
.css( props
[ i
] );
1211 // We assume that elements with 'overflow' (in any direction) set to 'hidden' will never be
1212 // scrolled in that direction, but they can actually be scrolled programatically. The user can
1213 // unintentionally perform a scroll in such case even if the application doesn't scroll
1214 // programatically, e.g. when jumping to an anchor, or when using built-in find functionality.
1215 // This could cause funny issues...
1216 if ( val
=== 'auto' || val
=== 'scroll' ) {
1217 return $parent
[ 0 ];
1220 $parent
= $parent
.parent();
1222 // The element is unattached... return something mostly sane
1223 return this.getRootScrollableElement( el
);
1227 * Scroll element into view.
1230 * @param {HTMLElement} el Element to scroll into view
1231 * @param {Object} [config] Configuration options
1232 * @param {string} [config.duration='fast'] jQuery animation duration value
1233 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1234 * to scroll in both directions
1235 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1237 OO
.ui
.Element
.static.scrollIntoView = function ( el
, config
) {
1238 var position
, animations
, container
, $container
, elementDimensions
, containerDimensions
, $window
,
1239 deferred
= $.Deferred();
1241 // Configuration initialization
1242 config
= config
|| {};
1245 container
= this.getClosestScrollableContainer( el
, config
.direction
);
1246 $container
= $( container
);
1247 elementDimensions
= this.getDimensions( el
);
1248 containerDimensions
= this.getDimensions( container
);
1249 $window
= $( this.getWindow( el
) );
1251 // Compute the element's position relative to the container
1252 if ( $container
.is( 'html, body' ) ) {
1253 // If the scrollable container is the root, this is easy
1255 top
: elementDimensions
.rect
.top
,
1256 bottom
: $window
.innerHeight() - elementDimensions
.rect
.bottom
,
1257 left
: elementDimensions
.rect
.left
,
1258 right
: $window
.innerWidth() - elementDimensions
.rect
.right
1261 // Otherwise, we have to subtract el's coordinates from container's coordinates
1263 top
: elementDimensions
.rect
.top
- ( containerDimensions
.rect
.top
+ containerDimensions
.borders
.top
),
1264 bottom
: containerDimensions
.rect
.bottom
- containerDimensions
.borders
.bottom
- containerDimensions
.scrollbar
.bottom
- elementDimensions
.rect
.bottom
,
1265 left
: elementDimensions
.rect
.left
- ( containerDimensions
.rect
.left
+ containerDimensions
.borders
.left
),
1266 right
: containerDimensions
.rect
.right
- containerDimensions
.borders
.right
- containerDimensions
.scrollbar
.right
- elementDimensions
.rect
.right
1270 if ( !config
.direction
|| config
.direction
=== 'y' ) {
1271 if ( position
.top
< 0 ) {
1272 animations
.scrollTop
= containerDimensions
.scroll
.top
+ position
.top
;
1273 } else if ( position
.top
> 0 && position
.bottom
< 0 ) {
1274 animations
.scrollTop
= containerDimensions
.scroll
.top
+ Math
.min( position
.top
, -position
.bottom
);
1277 if ( !config
.direction
|| config
.direction
=== 'x' ) {
1278 if ( position
.left
< 0 ) {
1279 animations
.scrollLeft
= containerDimensions
.scroll
.left
+ position
.left
;
1280 } else if ( position
.left
> 0 && position
.right
< 0 ) {
1281 animations
.scrollLeft
= containerDimensions
.scroll
.left
+ Math
.min( position
.left
, -position
.right
);
1284 if ( !$.isEmptyObject( animations
) ) {
1285 $container
.stop( true ).animate( animations
, config
.duration
=== undefined ? 'fast' : config
.duration
);
1286 $container
.queue( function ( next
) {
1293 return deferred
.promise();
1297 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1298 * and reserve space for them, because it probably doesn't.
1300 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1301 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1302 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1303 * and then reattach (or show) them back.
1306 * @param {HTMLElement} el Element to reconsider the scrollbars on
1308 OO
.ui
.Element
.static.reconsiderScrollbars = function ( el
) {
1309 var i
, len
, scrollLeft
, scrollTop
, nodes
= [];
1310 // Save scroll position
1311 scrollLeft
= el
.scrollLeft
;
1312 scrollTop
= el
.scrollTop
;
1313 // Detach all children
1314 while ( el
.firstChild
) {
1315 nodes
.push( el
.firstChild
);
1316 el
.removeChild( el
.firstChild
);
1319 void el
.offsetHeight
;
1320 // Reattach all children
1321 for ( i
= 0, len
= nodes
.length
; i
< len
; i
++ ) {
1322 el
.appendChild( nodes
[ i
] );
1324 // Restore scroll position (no-op if scrollbars disappeared)
1325 el
.scrollLeft
= scrollLeft
;
1326 el
.scrollTop
= scrollTop
;
1332 * Toggle visibility of an element.
1334 * @param {boolean} [show] Make element visible, omit to toggle visibility
1338 OO
.ui
.Element
.prototype.toggle = function ( show
) {
1339 show
= show
=== undefined ? !this.visible
: !!show
;
1341 if ( show
!== this.isVisible() ) {
1342 this.visible
= show
;
1343 this.$element
.toggleClass( 'oo-ui-element-hidden', !this.visible
);
1344 this.emit( 'toggle', show
);
1351 * Check if element is visible.
1353 * @return {boolean} element is visible
1355 OO
.ui
.Element
.prototype.isVisible = function () {
1356 return this.visible
;
1362 * @return {Mixed} Element data
1364 OO
.ui
.Element
.prototype.getData = function () {
1371 * @param {Mixed} data Element data
1374 OO
.ui
.Element
.prototype.setData = function ( data
) {
1380 * Set the element has an 'id' attribute.
1382 * @param {string} id
1385 OO
.ui
.Element
.prototype.setElementId = function ( id
) {
1386 this.elementId
= id
;
1387 this.$element
.attr( 'id', id
);
1392 * Ensure that the element has an 'id' attribute, setting it to an unique value if it's missing,
1393 * and return its value.
1397 OO
.ui
.Element
.prototype.getElementId = function () {
1398 if ( this.elementId
=== null ) {
1399 this.setElementId( OO
.ui
.generateElementId() );
1401 return this.elementId
;
1405 * Check if element supports one or more methods.
1407 * @param {string|string[]} methods Method or list of methods to check
1408 * @return {boolean} All methods are supported
1410 OO
.ui
.Element
.prototype.supports = function ( methods
) {
1414 methods
= Array
.isArray( methods
) ? methods
: [ methods
];
1415 for ( i
= 0, len
= methods
.length
; i
< len
; i
++ ) {
1416 if ( $.isFunction( this[ methods
[ i
] ] ) ) {
1421 return methods
.length
=== support
;
1425 * Update the theme-provided classes.
1427 * @localdoc This is called in element mixins and widget classes any time state changes.
1428 * Updating is debounced, minimizing overhead of changing multiple attributes and
1429 * guaranteeing that theme updates do not occur within an element's constructor
1431 OO
.ui
.Element
.prototype.updateThemeClasses = function () {
1432 OO
.ui
.theme
.queueUpdateElementClasses( this );
1436 * Get the HTML tag name.
1438 * Override this method to base the result on instance information.
1440 * @return {string} HTML tag name
1442 OO
.ui
.Element
.prototype.getTagName = function () {
1443 return this.constructor.static.tagName
;
1447 * Check if the element is attached to the DOM
1449 * @return {boolean} The element is attached to the DOM
1451 OO
.ui
.Element
.prototype.isElementAttached = function () {
1452 return $.contains( this.getElementDocument(), this.$element
[ 0 ] );
1456 * Get the DOM document.
1458 * @return {HTMLDocument} Document object
1460 OO
.ui
.Element
.prototype.getElementDocument = function () {
1461 // Don't cache this in other ways either because subclasses could can change this.$element
1462 return OO
.ui
.Element
.static.getDocument( this.$element
);
1466 * Get the DOM window.
1468 * @return {Window} Window object
1470 OO
.ui
.Element
.prototype.getElementWindow = function () {
1471 return OO
.ui
.Element
.static.getWindow( this.$element
);
1475 * Get closest scrollable container.
1477 * @return {HTMLElement} Closest scrollable container
1479 OO
.ui
.Element
.prototype.getClosestScrollableElementContainer = function () {
1480 return OO
.ui
.Element
.static.getClosestScrollableContainer( this.$element
[ 0 ] );
1484 * Get group element is in.
1486 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1488 OO
.ui
.Element
.prototype.getElementGroup = function () {
1489 return this.elementGroup
;
1493 * Set group element is in.
1495 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1498 OO
.ui
.Element
.prototype.setElementGroup = function ( group
) {
1499 this.elementGroup
= group
;
1504 * Scroll element into view.
1506 * @param {Object} [config] Configuration options
1507 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1509 OO
.ui
.Element
.prototype.scrollElementIntoView = function ( config
) {
1511 !this.isElementAttached() ||
1512 !this.isVisible() ||
1513 ( this.getElementGroup() && !this.getElementGroup().isVisible() )
1515 return $.Deferred().resolve();
1517 return OO
.ui
.Element
.static.scrollIntoView( this.$element
[ 0 ], config
);
1521 * Restore the pre-infusion dynamic state for this widget.
1523 * This method is called after #$element has been inserted into DOM. The parameter is the return
1524 * value of #gatherPreInfuseState.
1527 * @param {Object} state
1529 OO
.ui
.Element
.prototype.restorePreInfuseState = function () {
1533 * Wraps an HTML snippet for use with configuration values which default
1534 * to strings. This bypasses the default html-escaping done to string
1540 * @param {string} [content] HTML content
1542 OO
.ui
.HtmlSnippet
= function OoUiHtmlSnippet( content
) {
1544 this.content
= content
;
1549 OO
.initClass( OO
.ui
.HtmlSnippet
);
1556 * @return {string} Unchanged HTML snippet.
1558 OO
.ui
.HtmlSnippet
.prototype.toString = function () {
1559 return this.content
;
1563 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1564 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1565 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1566 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1567 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1571 * @extends OO.ui.Element
1572 * @mixins OO.EventEmitter
1575 * @param {Object} [config] Configuration options
1577 OO
.ui
.Layout
= function OoUiLayout( config
) {
1578 // Configuration initialization
1579 config
= config
|| {};
1581 // Parent constructor
1582 OO
.ui
.Layout
.parent
.call( this, config
);
1584 // Mixin constructors
1585 OO
.EventEmitter
.call( this );
1588 this.$element
.addClass( 'oo-ui-layout' );
1593 OO
.inheritClass( OO
.ui
.Layout
, OO
.ui
.Element
);
1594 OO
.mixinClass( OO
.ui
.Layout
, OO
.EventEmitter
);
1597 * Widgets are compositions of one or more OOjs UI elements that users can both view
1598 * and interact with. All widgets can be configured and modified via a standard API,
1599 * and their state can change dynamically according to a model.
1603 * @extends OO.ui.Element
1604 * @mixins OO.EventEmitter
1607 * @param {Object} [config] Configuration options
1608 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1609 * appearance reflects this state.
1611 OO
.ui
.Widget
= function OoUiWidget( config
) {
1612 // Initialize config
1613 config
= $.extend( { disabled
: false }, config
);
1615 // Parent constructor
1616 OO
.ui
.Widget
.parent
.call( this, config
);
1618 // Mixin constructors
1619 OO
.EventEmitter
.call( this );
1622 this.disabled
= null;
1623 this.wasDisabled
= null;
1626 this.$element
.addClass( 'oo-ui-widget' );
1627 this.setDisabled( !!config
.disabled
);
1632 OO
.inheritClass( OO
.ui
.Widget
, OO
.ui
.Element
);
1633 OO
.mixinClass( OO
.ui
.Widget
, OO
.EventEmitter
);
1635 /* Static Properties */
1638 * Whether this widget will behave reasonably when wrapped in an HTML `<label>`. If this is true,
1639 * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click
1644 * @property {boolean}
1646 OO
.ui
.Widget
.static.supportsSimpleLabel
= false;
1653 * A 'disable' event is emitted when the disabled state of the widget changes
1654 * (i.e. on disable **and** enable).
1656 * @param {boolean} disabled Widget is disabled
1662 * A 'toggle' event is emitted when the visibility of the widget changes.
1664 * @param {boolean} visible Widget is visible
1670 * Check if the widget is disabled.
1672 * @return {boolean} Widget is disabled
1674 OO
.ui
.Widget
.prototype.isDisabled = function () {
1675 return this.disabled
;
1679 * Set the 'disabled' state of the widget.
1681 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1683 * @param {boolean} disabled Disable widget
1686 OO
.ui
.Widget
.prototype.setDisabled = function ( disabled
) {
1689 this.disabled
= !!disabled
;
1690 isDisabled
= this.isDisabled();
1691 if ( isDisabled
!== this.wasDisabled
) {
1692 this.$element
.toggleClass( 'oo-ui-widget-disabled', isDisabled
);
1693 this.$element
.toggleClass( 'oo-ui-widget-enabled', !isDisabled
);
1694 this.$element
.attr( 'aria-disabled', isDisabled
.toString() );
1695 this.emit( 'disable', isDisabled
);
1696 this.updateThemeClasses();
1698 this.wasDisabled
= isDisabled
;
1704 * Update the disabled state, in case of changes in parent widget.
1708 OO
.ui
.Widget
.prototype.updateDisabled = function () {
1709 this.setDisabled( this.disabled
);
1721 OO
.ui
.Theme
= function OoUiTheme() {
1722 this.elementClassesQueue
= [];
1723 this.debouncedUpdateQueuedElementClasses
= OO
.ui
.debounce( this.updateQueuedElementClasses
);
1728 OO
.initClass( OO
.ui
.Theme
);
1733 * Get a list of classes to be applied to a widget.
1735 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
1736 * otherwise state transitions will not work properly.
1738 * @param {OO.ui.Element} element Element for which to get classes
1739 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
1741 OO
.ui
.Theme
.prototype.getElementClasses = function () {
1742 return { on
: [], off
: [] };
1746 * Update CSS classes provided by the theme.
1748 * For elements with theme logic hooks, this should be called any time there's a state change.
1750 * @param {OO.ui.Element} element Element for which to update classes
1752 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
1753 var $elements
= $( [] ),
1754 classes
= this.getElementClasses( element
);
1756 if ( element
.$icon
) {
1757 $elements
= $elements
.add( element
.$icon
);
1759 if ( element
.$indicator
) {
1760 $elements
= $elements
.add( element
.$indicator
);
1764 .removeClass( classes
.off
.join( ' ' ) )
1765 .addClass( classes
.on
.join( ' ' ) );
1771 OO
.ui
.Theme
.prototype.updateQueuedElementClasses = function () {
1773 for ( i
= 0; i
< this.elementClassesQueue
.length
; i
++ ) {
1774 this.updateElementClasses( this.elementClassesQueue
[ i
] );
1777 this.elementClassesQueue
= [];
1781 * Queue #updateElementClasses to be called for this element.
1783 * @localdoc QUnit tests override this method to directly call #queueUpdateElementClasses,
1784 * to make them synchronous.
1786 * @param {OO.ui.Element} element Element for which to update classes
1788 OO
.ui
.Theme
.prototype.queueUpdateElementClasses = function ( element
) {
1789 // Keep items in the queue unique. Use lastIndexOf to start checking from the end because that's
1790 // the most common case (this method is often called repeatedly for the same element).
1791 if ( this.elementClassesQueue
.lastIndexOf( element
) !== -1 ) {
1794 this.elementClassesQueue
.push( element
);
1795 this.debouncedUpdateQueuedElementClasses();
1799 * Get the transition duration in milliseconds for dialogs opening/closing
1801 * The dialog should be fully rendered this many milliseconds after the
1802 * ready process has executed.
1804 * @return {number} Transition duration in milliseconds
1806 OO
.ui
.Theme
.prototype.getDialogTransitionDuration = function () {
1811 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
1812 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
1813 * order in which users will navigate through the focusable elements via the "tab" key.
1816 * // TabIndexedElement is mixed into the ButtonWidget class
1817 * // to provide a tabIndex property.
1818 * var button1 = new OO.ui.ButtonWidget( {
1822 * var button2 = new OO.ui.ButtonWidget( {
1826 * var button3 = new OO.ui.ButtonWidget( {
1830 * var button4 = new OO.ui.ButtonWidget( {
1834 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
1840 * @param {Object} [config] Configuration options
1841 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
1842 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
1843 * functionality will be applied to it instead.
1844 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
1845 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
1846 * to remove the element from the tab-navigation flow.
1848 OO
.ui
.mixin
.TabIndexedElement
= function OoUiMixinTabIndexedElement( config
) {
1849 // Configuration initialization
1850 config
= $.extend( { tabIndex
: 0 }, config
);
1853 this.$tabIndexed
= null;
1854 this.tabIndex
= null;
1857 this.connect( this, { disable
: 'onTabIndexedElementDisable' } );
1860 this.setTabIndex( config
.tabIndex
);
1861 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
1866 OO
.initClass( OO
.ui
.mixin
.TabIndexedElement
);
1871 * Set the element that should use the tabindex functionality.
1873 * This method is used to retarget a tabindex mixin so that its functionality applies
1874 * to the specified element. If an element is currently using the functionality, the mixin’s
1875 * effect on that element is removed before the new element is set up.
1877 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
1880 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
1881 var tabIndex
= this.tabIndex
;
1882 // Remove attributes from old $tabIndexed
1883 this.setTabIndex( null );
1884 // Force update of new $tabIndexed
1885 this.$tabIndexed
= $tabIndexed
;
1886 this.tabIndex
= tabIndex
;
1887 return this.updateTabIndex();
1891 * Set the value of the tabindex.
1893 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
1896 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
1897 tabIndex
= typeof tabIndex
=== 'number' ? tabIndex
: null;
1899 if ( this.tabIndex
!== tabIndex
) {
1900 this.tabIndex
= tabIndex
;
1901 this.updateTabIndex();
1908 * Update the `tabindex` attribute, in case of changes to tab index or
1914 OO
.ui
.mixin
.TabIndexedElement
.prototype.updateTabIndex = function () {
1915 if ( this.$tabIndexed
) {
1916 if ( this.tabIndex
!== null ) {
1917 // Do not index over disabled elements
1918 this.$tabIndexed
.attr( {
1919 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
1920 // Support: ChromeVox and NVDA
1921 // These do not seem to inherit aria-disabled from parent elements
1922 'aria-disabled': this.isDisabled().toString()
1925 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
1932 * Handle disable events.
1935 * @param {boolean} disabled Element is disabled
1937 OO
.ui
.mixin
.TabIndexedElement
.prototype.onTabIndexedElementDisable = function () {
1938 this.updateTabIndex();
1942 * Get the value of the tabindex.
1944 * @return {number|null} Tabindex value
1946 OO
.ui
.mixin
.TabIndexedElement
.prototype.getTabIndex = function () {
1947 return this.tabIndex
;
1951 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
1952 * interface element that can be configured with access keys for accessibility.
1953 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
1955 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
1961 * @param {Object} [config] Configuration options
1962 * @cfg {jQuery} [$button] The button element created by the class.
1963 * If this configuration is omitted, the button element will use a generated `<a>`.
1964 * @cfg {boolean} [framed=true] Render the button with a frame
1966 OO
.ui
.mixin
.ButtonElement
= function OoUiMixinButtonElement( config
) {
1967 // Configuration initialization
1968 config
= config
|| {};
1971 this.$button
= null;
1973 this.active
= config
.active
!== undefined && config
.active
;
1974 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
1975 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
1976 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
1977 this.onKeyUpHandler
= this.onKeyUp
.bind( this );
1978 this.onClickHandler
= this.onClick
.bind( this );
1979 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
1982 this.$element
.addClass( 'oo-ui-buttonElement' );
1983 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
1984 this.setButtonElement( config
.$button
|| $( '<a>' ) );
1989 OO
.initClass( OO
.ui
.mixin
.ButtonElement
);
1991 /* Static Properties */
1994 * Cancel mouse down events.
1996 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
1997 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
1998 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
2003 * @property {boolean}
2005 OO
.ui
.mixin
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
2010 * A 'click' event is emitted when the button element is clicked.
2018 * Set the button element.
2020 * This method is used to retarget a button mixin so that its functionality applies to
2021 * the specified button element instead of the one created by the class. If a button element
2022 * is already set, the method will remove the mixin’s effect on that element.
2024 * @param {jQuery} $button Element to use as button
2026 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
2027 if ( this.$button
) {
2029 .removeClass( 'oo-ui-buttonElement-button' )
2030 .removeAttr( 'role accesskey' )
2032 mousedown
: this.onMouseDownHandler
,
2033 keydown
: this.onKeyDownHandler
,
2034 click
: this.onClickHandler
,
2035 keypress
: this.onKeyPressHandler
2039 this.$button
= $button
2040 .addClass( 'oo-ui-buttonElement-button' )
2042 mousedown
: this.onMouseDownHandler
,
2043 keydown
: this.onKeyDownHandler
,
2044 click
: this.onClickHandler
,
2045 keypress
: this.onKeyPressHandler
2048 // Add `role="button"` on `<a>` elements, where it's needed
2049 // `toUppercase()` is added for XHTML documents
2050 if ( this.$button
.prop( 'tagName' ).toUpperCase() === 'A' ) {
2051 this.$button
.attr( 'role', 'button' );
2056 * Handles mouse down events.
2059 * @param {jQuery.Event} e Mouse down event
2061 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown = function ( e
) {
2062 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
2065 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
2066 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
2067 // reliably remove the pressed class
2068 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
2069 // Prevent change of focus unless specifically configured otherwise
2070 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
2076 * Handles mouse up events.
2079 * @param {MouseEvent} e Mouse up event
2081 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp = function ( e
) {
2082 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
2085 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
2086 // Stop listening for mouseup, since we only needed this once
2087 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
2091 * Handles mouse click events.
2094 * @param {jQuery.Event} e Mouse click event
2097 OO
.ui
.mixin
.ButtonElement
.prototype.onClick = function ( e
) {
2098 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
2099 if ( this.emit( 'click' ) ) {
2106 * Handles key down events.
2109 * @param {jQuery.Event} e Key down event
2111 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyDown = function ( e
) {
2112 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
2115 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
2116 // Run the keyup handler no matter where the key is when the button is let go, so we can
2117 // reliably remove the pressed class
2118 this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler
, true );
2122 * Handles key up events.
2125 * @param {KeyboardEvent} e Key up event
2127 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyUp = function ( e
) {
2128 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
2131 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
2132 // Stop listening for keyup, since we only needed this once
2133 this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler
, true );
2137 * Handles key press events.
2140 * @param {jQuery.Event} e Key press event
2143 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyPress = function ( e
) {
2144 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
2145 if ( this.emit( 'click' ) ) {
2152 * Check if button has a frame.
2154 * @return {boolean} Button is framed
2156 OO
.ui
.mixin
.ButtonElement
.prototype.isFramed = function () {
2161 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
2163 * @param {boolean} [framed] Make button framed, omit to toggle
2166 OO
.ui
.mixin
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
2167 framed
= framed
=== undefined ? !this.framed
: !!framed
;
2168 if ( framed
!== this.framed
) {
2169 this.framed
= framed
;
2171 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
2172 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
2173 this.updateThemeClasses();
2180 * Set the button's active state.
2182 * The active state can be set on:
2184 * - {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} when it is selected
2185 * - {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} when it is toggle on
2186 * - {@link OO.ui.ButtonWidget ButtonWidget} when clicking the button would only refresh the page
2189 * @param {boolean} value Make button active
2192 OO
.ui
.mixin
.ButtonElement
.prototype.setActive = function ( value
) {
2193 this.active
= !!value
;
2194 this.$element
.toggleClass( 'oo-ui-buttonElement-active', this.active
);
2195 this.updateThemeClasses();
2200 * Check if the button is active
2203 * @return {boolean} The button is active
2205 OO
.ui
.mixin
.ButtonElement
.prototype.isActive = function () {
2210 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
2211 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
2212 * items from the group is done through the interface the class provides.
2213 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2215 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
2218 * @mixins OO.EmitterList
2222 * @param {Object} [config] Configuration options
2223 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
2224 * is omitted, the group element will use a generated `<div>`.
2226 OO
.ui
.mixin
.GroupElement
= function OoUiMixinGroupElement( config
) {
2227 // Configuration initialization
2228 config
= config
|| {};
2230 // Mixin constructors
2231 OO
.EmitterList
.call( this, config
);
2237 this.setGroupElement( config
.$group
|| $( '<div>' ) );
2242 OO
.mixinClass( OO
.ui
.mixin
.GroupElement
, OO
.EmitterList
);
2249 * A change event is emitted when the set of selected items changes.
2251 * @param {OO.ui.Element[]} items Items currently in the group
2257 * Set the group element.
2259 * If an element is already set, items will be moved to the new element.
2261 * @param {jQuery} $group Element to use as group
2263 OO
.ui
.mixin
.GroupElement
.prototype.setGroupElement = function ( $group
) {
2266 this.$group
= $group
;
2267 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2268 this.$group
.append( this.items
[ i
].$element
);
2273 * Get an item by its data.
2275 * Only the first item with matching data will be returned. To return all matching items,
2276 * use the #getItemsFromData method.
2278 * @param {Object} data Item data to search for
2279 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
2281 OO
.ui
.mixin
.GroupElement
.prototype.getItemFromData = function ( data
) {
2283 hash
= OO
.getHash( data
);
2285 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2286 item
= this.items
[ i
];
2287 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2296 * Get items by their data.
2298 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
2300 * @param {Object} data Item data to search for
2301 * @return {OO.ui.Element[]} Items with equivalent data
2303 OO
.ui
.mixin
.GroupElement
.prototype.getItemsFromData = function ( data
) {
2305 hash
= OO
.getHash( data
),
2308 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2309 item
= this.items
[ i
];
2310 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2319 * Add items to the group.
2321 * Items will be added to the end of the group array unless the optional `index` parameter specifies
2322 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
2324 * @param {OO.ui.Element[]} items An array of items to add to the group
2325 * @param {number} [index] Index of the insertion point
2328 OO
.ui
.mixin
.GroupElement
.prototype.addItems = function ( items
, index
) {
2330 OO
.EmitterList
.prototype.addItems
.call( this, items
, index
);
2332 this.emit( 'change', this.getItems() );
2339 OO
.ui
.mixin
.GroupElement
.prototype.moveItem = function ( items
, newIndex
) {
2340 // insertItemElements expects this.items to not have been modified yet, so call before the mixin
2341 this.insertItemElements( items
, newIndex
);
2344 newIndex
= OO
.EmitterList
.prototype.moveItem
.call( this, items
, newIndex
);
2352 OO
.ui
.mixin
.GroupElement
.prototype.insertItem = function ( item
, index
) {
2353 item
.setElementGroup( this );
2354 this.insertItemElements( item
, index
);
2357 index
= OO
.EmitterList
.prototype.insertItem
.call( this, item
, index
);
2363 * Insert elements into the group
2366 * @param {OO.ui.Element} itemWidget Item to insert
2367 * @param {number} index Insertion index
2369 OO
.ui
.mixin
.GroupElement
.prototype.insertItemElements = function ( itemWidget
, index
) {
2370 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
2371 this.$group
.append( itemWidget
.$element
);
2372 } else if ( index
=== 0 ) {
2373 this.$group
.prepend( itemWidget
.$element
);
2375 this.items
[ index
].$element
.before( itemWidget
.$element
);
2380 * Remove the specified items from a group.
2382 * Removed items are detached (not removed) from the DOM so that they may be reused.
2383 * To remove all items from a group, you may wish to use the #clearItems method instead.
2385 * @param {OO.ui.Element[]} items An array of items to remove
2388 OO
.ui
.mixin
.GroupElement
.prototype.removeItems = function ( items
) {
2389 var i
, len
, item
, index
;
2391 // Remove specific items elements
2392 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
2394 index
= this.items
.indexOf( item
);
2395 if ( index
!== -1 ) {
2396 item
.setElementGroup( null );
2397 item
.$element
.detach();
2402 OO
.EmitterList
.prototype.removeItems
.call( this, items
);
2404 this.emit( 'change', this.getItems() );
2409 * Clear all items from the group.
2411 * Cleared items are detached from the DOM, not removed, so that they may be reused.
2412 * To remove only a subset of items from a group, use the #removeItems method.
2416 OO
.ui
.mixin
.GroupElement
.prototype.clearItems = function () {
2419 // Remove all item elements
2420 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2421 this.items
[ i
].setElementGroup( null );
2422 this.items
[ i
].$element
.detach();
2426 OO
.EmitterList
.prototype.clearItems
.call( this );
2428 this.emit( 'change', this.getItems() );
2433 * IconElement is often mixed into other classes to generate an icon.
2434 * Icons are graphics, about the size of normal text. They are used to aid the user
2435 * in locating a control or to convey information in a space-efficient way. See the
2436 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
2437 * included in the library.
2439 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
2445 * @param {Object} [config] Configuration options
2446 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
2447 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
2448 * the icon element be set to an existing icon instead of the one generated by this class, set a
2449 * value using a jQuery selection. For example:
2451 * // Use a <div> tag instead of a <span>
2453 * // Use an existing icon element instead of the one generated by the class
2454 * $icon: this.$element
2455 * // Use an icon element from a child widget
2456 * $icon: this.childwidget.$element
2457 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
2458 * symbolic names. A map is used for i18n purposes and contains a `default` icon
2459 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
2460 * by the user's language.
2462 * Example of an i18n map:
2464 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2465 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
2466 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
2467 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
2468 * text. The icon title is displayed when users move the mouse over the icon.
2470 OO
.ui
.mixin
.IconElement
= function OoUiMixinIconElement( config
) {
2471 // Configuration initialization
2472 config
= config
|| {};
2477 this.iconTitle
= null;
2480 this.setIcon( config
.icon
|| this.constructor.static.icon
);
2481 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
2482 this.setIconElement( config
.$icon
|| $( '<span>' ) );
2487 OO
.initClass( OO
.ui
.mixin
.IconElement
);
2489 /* Static Properties */
2492 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
2493 * for i18n purposes and contains a `default` icon name and additional names keyed by
2494 * language code. The `default` name is used when no icon is keyed by the user's language.
2496 * Example of an i18n map:
2498 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2500 * Note: the static property will be overridden if the #icon configuration is used.
2504 * @property {Object|string}
2506 OO
.ui
.mixin
.IconElement
.static.icon
= null;
2509 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
2510 * function that returns title text, or `null` for no title.
2512 * The static property will be overridden if the #iconTitle configuration is used.
2516 * @property {string|Function|null}
2518 OO
.ui
.mixin
.IconElement
.static.iconTitle
= null;
2523 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
2524 * applies to the specified icon element instead of the one created by the class. If an icon
2525 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
2526 * and mixin methods will no longer affect the element.
2528 * @param {jQuery} $icon Element to use as icon
2530 OO
.ui
.mixin
.IconElement
.prototype.setIconElement = function ( $icon
) {
2533 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
2534 .removeAttr( 'title' );
2538 .addClass( 'oo-ui-iconElement-icon' )
2539 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
2540 if ( this.iconTitle
!== null ) {
2541 this.$icon
.attr( 'title', this.iconTitle
);
2544 this.updateThemeClasses();
2548 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
2549 * The icon parameter can also be set to a map of icon names. See the #icon config setting
2552 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
2553 * by language code, or `null` to remove the icon.
2556 OO
.ui
.mixin
.IconElement
.prototype.setIcon = function ( icon
) {
2557 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
2558 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
2560 if ( this.icon
!== icon
) {
2562 if ( this.icon
!== null ) {
2563 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
2565 if ( icon
!== null ) {
2566 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
2572 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
2573 this.updateThemeClasses();
2579 * Set the icon title. Use `null` to remove the title.
2581 * @param {string|Function|null} iconTitle A text string used as the icon title,
2582 * a function that returns title text, or `null` for no title.
2585 OO
.ui
.mixin
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
2586 iconTitle
= typeof iconTitle
=== 'function' ||
2587 ( typeof iconTitle
=== 'string' && iconTitle
.length
) ?
2588 OO
.ui
.resolveMsg( iconTitle
) : null;
2590 if ( this.iconTitle
!== iconTitle
) {
2591 this.iconTitle
= iconTitle
;
2593 if ( this.iconTitle
!== null ) {
2594 this.$icon
.attr( 'title', iconTitle
);
2596 this.$icon
.removeAttr( 'title' );
2605 * Get the symbolic name of the icon.
2607 * @return {string} Icon name
2609 OO
.ui
.mixin
.IconElement
.prototype.getIcon = function () {
2614 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
2616 * @return {string} Icon title text
2618 OO
.ui
.mixin
.IconElement
.prototype.getIconTitle = function () {
2619 return this.iconTitle
;
2623 * IndicatorElement is often mixed into other classes to generate an indicator.
2624 * Indicators are small graphics that are generally used in two ways:
2626 * - To draw attention to the status of an item. For example, an indicator might be
2627 * used to show that an item in a list has errors that need to be resolved.
2628 * - To clarify the function of a control that acts in an exceptional way (a button
2629 * that opens a menu instead of performing an action directly, for example).
2631 * For a list of indicators included in the library, please see the
2632 * [OOjs UI documentation on MediaWiki] [1].
2634 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2640 * @param {Object} [config] Configuration options
2641 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
2642 * configuration is omitted, the indicator element will use a generated `<span>`.
2643 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2644 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
2646 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2647 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
2648 * or a function that returns title text. The indicator title is displayed when users move
2649 * the mouse over the indicator.
2651 OO
.ui
.mixin
.IndicatorElement
= function OoUiMixinIndicatorElement( config
) {
2652 // Configuration initialization
2653 config
= config
|| {};
2656 this.$indicator
= null;
2657 this.indicator
= null;
2658 this.indicatorTitle
= null;
2661 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
2662 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
2663 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
2668 OO
.initClass( OO
.ui
.mixin
.IndicatorElement
);
2670 /* Static Properties */
2673 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2674 * The static property will be overridden if the #indicator configuration is used.
2678 * @property {string|null}
2680 OO
.ui
.mixin
.IndicatorElement
.static.indicator
= null;
2683 * A text string used as the indicator title, a function that returns title text, or `null`
2684 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
2688 * @property {string|Function|null}
2690 OO
.ui
.mixin
.IndicatorElement
.static.indicatorTitle
= null;
2695 * Set the indicator element.
2697 * If an element is already set, it will be cleaned up before setting up the new element.
2699 * @param {jQuery} $indicator Element to use as indicator
2701 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
2702 if ( this.$indicator
) {
2704 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
2705 .removeAttr( 'title' );
2708 this.$indicator
= $indicator
2709 .addClass( 'oo-ui-indicatorElement-indicator' )
2710 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
2711 if ( this.indicatorTitle
!== null ) {
2712 this.$indicator
.attr( 'title', this.indicatorTitle
);
2715 this.updateThemeClasses();
2719 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
2721 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
2724 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
2725 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
2727 if ( this.indicator
!== indicator
) {
2728 if ( this.$indicator
) {
2729 if ( this.indicator
!== null ) {
2730 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
2732 if ( indicator
!== null ) {
2733 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
2736 this.indicator
= indicator
;
2739 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
2740 this.updateThemeClasses();
2746 * Set the indicator title.
2748 * The title is displayed when a user moves the mouse over the indicator.
2750 * @param {string|Function|null} indicatorTitle Indicator title text, a function that returns text, or
2751 * `null` for no indicator title
2754 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorTitle = function ( indicatorTitle
) {
2755 indicatorTitle
= typeof indicatorTitle
=== 'function' ||
2756 ( typeof indicatorTitle
=== 'string' && indicatorTitle
.length
) ?
2757 OO
.ui
.resolveMsg( indicatorTitle
) : null;
2759 if ( this.indicatorTitle
!== indicatorTitle
) {
2760 this.indicatorTitle
= indicatorTitle
;
2761 if ( this.$indicator
) {
2762 if ( this.indicatorTitle
!== null ) {
2763 this.$indicator
.attr( 'title', indicatorTitle
);
2765 this.$indicator
.removeAttr( 'title' );
2774 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2776 * @return {string} Symbolic name of indicator
2778 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicator = function () {
2779 return this.indicator
;
2783 * Get the indicator title.
2785 * The title is displayed when a user moves the mouse over the indicator.
2787 * @return {string} Indicator title text
2789 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicatorTitle = function () {
2790 return this.indicatorTitle
;
2794 * LabelElement is often mixed into other classes to generate a label, which
2795 * helps identify the function of an interface element.
2796 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
2798 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
2804 * @param {Object} [config] Configuration options
2805 * @cfg {jQuery} [$label] The label element created by the class. If this
2806 * configuration is omitted, the label element will use a generated `<span>`.
2807 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
2808 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
2809 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
2810 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
2812 OO
.ui
.mixin
.LabelElement
= function OoUiMixinLabelElement( config
) {
2813 // Configuration initialization
2814 config
= config
|| {};
2821 this.setLabel( config
.label
|| this.constructor.static.label
);
2822 this.setLabelElement( config
.$label
|| $( '<span>' ) );
2827 OO
.initClass( OO
.ui
.mixin
.LabelElement
);
2832 * @event labelChange
2833 * @param {string} value
2836 /* Static Properties */
2839 * The label text. The label can be specified as a plaintext string, a function that will
2840 * produce a string in the future, or `null` for no label. The static value will
2841 * be overridden if a label is specified with the #label config option.
2845 * @property {string|Function|null}
2847 OO
.ui
.mixin
.LabelElement
.static.label
= null;
2849 /* Static methods */
2852 * Highlight the first occurrence of the query in the given text
2854 * @param {string} text Text
2855 * @param {string} query Query to find
2856 * @return {jQuery} Text with the first match of the query
2857 * sub-string wrapped in highlighted span
2859 OO
.ui
.mixin
.LabelElement
.static.highlightQuery = function ( text
, query
) {
2860 var $result
= $( '<span>' ),
2861 offset
= text
.toLowerCase().indexOf( query
.toLowerCase() );
2863 if ( !query
.length
|| offset
=== -1 ) {
2864 return $result
.text( text
);
2867 document
.createTextNode( text
.slice( 0, offset
) ),
2869 .addClass( 'oo-ui-labelElement-label-highlight' )
2870 .text( text
.slice( offset
, offset
+ query
.length
) ),
2871 document
.createTextNode( text
.slice( offset
+ query
.length
) )
2873 return $result
.contents();
2879 * Set the label element.
2881 * If an element is already set, it will be cleaned up before setting up the new element.
2883 * @param {jQuery} $label Element to use as label
2885 OO
.ui
.mixin
.LabelElement
.prototype.setLabelElement = function ( $label
) {
2886 if ( this.$label
) {
2887 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
2890 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
2891 this.setLabelContent( this.label
);
2897 * An empty string will result in the label being hidden. A string containing only whitespace will
2898 * be converted to a single ` `.
2900 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
2901 * text; or null for no label
2904 OO
.ui
.mixin
.LabelElement
.prototype.setLabel = function ( label
) {
2905 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
2906 label
= ( ( typeof label
=== 'string' || label
instanceof jQuery
) && label
.length
) || ( label
instanceof OO
.ui
.HtmlSnippet
&& label
.toString().length
) ? label
: null;
2908 if ( this.label
!== label
) {
2909 if ( this.$label
) {
2910 this.setLabelContent( label
);
2913 this.emit( 'labelChange' );
2916 this.$element
.toggleClass( 'oo-ui-labelElement', !!this.label
);
2922 * Set the label as plain text with a highlighted query
2924 * @param {string} text Text label to set
2925 * @param {string} query Substring of text to highlight
2928 OO
.ui
.mixin
.LabelElement
.prototype.setHighlightedQuery = function ( text
, query
) {
2929 return this.setLabel( this.constructor.static.highlightQuery( text
, query
) );
2935 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
2936 * text; or null for no label
2938 OO
.ui
.mixin
.LabelElement
.prototype.getLabel = function () {
2943 * Set the content of the label.
2945 * Do not call this method until after the label element has been set by #setLabelElement.
2948 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
2949 * text; or null for no label
2951 OO
.ui
.mixin
.LabelElement
.prototype.setLabelContent = function ( label
) {
2952 if ( typeof label
=== 'string' ) {
2953 if ( label
.match( /^\s*$/ ) ) {
2954 // Convert whitespace only string to a single non-breaking space
2955 this.$label
.html( ' ' );
2957 this.$label
.text( label
);
2959 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
2960 this.$label
.html( label
.toString() );
2961 } else if ( label
instanceof jQuery
) {
2962 this.$label
.empty().append( label
);
2964 this.$label
.empty();
2969 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
2970 * additional functionality to an element created by another class. The class provides
2971 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
2972 * which are used to customize the look and feel of a widget to better describe its
2973 * importance and functionality.
2975 * The library currently contains the following styling flags for general use:
2977 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
2978 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
2979 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
2981 * The flags affect the appearance of the buttons:
2984 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
2985 * var button1 = new OO.ui.ButtonWidget( {
2986 * label: 'Constructive',
2987 * flags: 'constructive'
2989 * var button2 = new OO.ui.ButtonWidget( {
2990 * label: 'Destructive',
2991 * flags: 'destructive'
2993 * var button3 = new OO.ui.ButtonWidget( {
2994 * label: 'Progressive',
2995 * flags: 'progressive'
2997 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
2999 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
3000 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
3002 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
3008 * @param {Object} [config] Configuration options
3009 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
3010 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
3011 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
3012 * @cfg {jQuery} [$flagged] The flagged element. By default,
3013 * the flagged functionality is applied to the element created by the class ($element).
3014 * If a different element is specified, the flagged functionality will be applied to it instead.
3016 OO
.ui
.mixin
.FlaggedElement
= function OoUiMixinFlaggedElement( config
) {
3017 // Configuration initialization
3018 config
= config
|| {};
3022 this.$flagged
= null;
3025 this.setFlags( config
.flags
);
3026 this.setFlaggedElement( config
.$flagged
|| this.$element
);
3033 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
3034 * parameter contains the name of each modified flag and indicates whether it was
3037 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
3038 * that the flag was added, `false` that the flag was removed.
3044 * Set the flagged element.
3046 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
3047 * If an element is already set, the method will remove the mixin’s effect on that element.
3049 * @param {jQuery} $flagged Element that should be flagged
3051 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
3052 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
3053 return 'oo-ui-flaggedElement-' + flag
;
3056 if ( this.$flagged
) {
3057 this.$flagged
.removeClass( classNames
);
3060 this.$flagged
= $flagged
.addClass( classNames
);
3064 * Check if the specified flag is set.
3066 * @param {string} flag Name of flag
3067 * @return {boolean} The flag is set
3069 OO
.ui
.mixin
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
3070 // This may be called before the constructor, thus before this.flags is set
3071 return this.flags
&& ( flag
in this.flags
);
3075 * Get the names of all flags set.
3077 * @return {string[]} Flag names
3079 OO
.ui
.mixin
.FlaggedElement
.prototype.getFlags = function () {
3080 // This may be called before the constructor, thus before this.flags is set
3081 return Object
.keys( this.flags
|| {} );
3090 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags = function () {
3091 var flag
, className
,
3094 classPrefix
= 'oo-ui-flaggedElement-';
3096 for ( flag
in this.flags
) {
3097 className
= classPrefix
+ flag
;
3098 changes
[ flag
] = false;
3099 delete this.flags
[ flag
];
3100 remove
.push( className
);
3103 if ( this.$flagged
) {
3104 this.$flagged
.removeClass( remove
.join( ' ' ) );
3107 this.updateThemeClasses();
3108 this.emit( 'flag', changes
);
3114 * Add one or more flags.
3116 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
3117 * or an object keyed by flag name with a boolean value that indicates whether the flag should
3118 * be added (`true`) or removed (`false`).
3122 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags = function ( flags
) {
3123 var i
, len
, flag
, className
,
3127 classPrefix
= 'oo-ui-flaggedElement-';
3129 if ( typeof flags
=== 'string' ) {
3130 className
= classPrefix
+ flags
;
3132 if ( !this.flags
[ flags
] ) {
3133 this.flags
[ flags
] = true;
3134 add
.push( className
);
3136 } else if ( Array
.isArray( flags
) ) {
3137 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
3139 className
= classPrefix
+ flag
;
3141 if ( !this.flags
[ flag
] ) {
3142 changes
[ flag
] = true;
3143 this.flags
[ flag
] = true;
3144 add
.push( className
);
3147 } else if ( OO
.isPlainObject( flags
) ) {
3148 for ( flag
in flags
) {
3149 className
= classPrefix
+ flag
;
3150 if ( flags
[ flag
] ) {
3152 if ( !this.flags
[ flag
] ) {
3153 changes
[ flag
] = true;
3154 this.flags
[ flag
] = true;
3155 add
.push( className
);
3159 if ( this.flags
[ flag
] ) {
3160 changes
[ flag
] = false;
3161 delete this.flags
[ flag
];
3162 remove
.push( className
);
3168 if ( this.$flagged
) {
3170 .addClass( add
.join( ' ' ) )
3171 .removeClass( remove
.join( ' ' ) );
3174 this.updateThemeClasses();
3175 this.emit( 'flag', changes
);
3181 * TitledElement is mixed into other classes to provide a `title` attribute.
3182 * Titles are rendered by the browser and are made visible when the user moves
3183 * the mouse over the element. Titles are not visible on touch devices.
3186 * // TitledElement provides a 'title' attribute to the
3187 * // ButtonWidget class
3188 * var button = new OO.ui.ButtonWidget( {
3189 * label: 'Button with Title',
3190 * title: 'I am a button'
3192 * $( 'body' ).append( button.$element );
3198 * @param {Object} [config] Configuration options
3199 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
3200 * If this config is omitted, the title functionality is applied to $element, the
3201 * element created by the class.
3202 * @cfg {string|Function} [title] The title text or a function that returns text. If
3203 * this config is omitted, the value of the {@link #static-title static title} property is used.
3205 OO
.ui
.mixin
.TitledElement
= function OoUiMixinTitledElement( config
) {
3206 // Configuration initialization
3207 config
= config
|| {};
3210 this.$titled
= null;
3214 this.setTitle( config
.title
!== undefined ? config
.title
: this.constructor.static.title
);
3215 this.setTitledElement( config
.$titled
|| this.$element
);
3220 OO
.initClass( OO
.ui
.mixin
.TitledElement
);
3222 /* Static Properties */
3225 * The title text, a function that returns text, or `null` for no title. The value of the static property
3226 * is overridden if the #title config option is used.
3230 * @property {string|Function|null}
3232 OO
.ui
.mixin
.TitledElement
.static.title
= null;
3237 * Set the titled element.
3239 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
3240 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
3242 * @param {jQuery} $titled Element that should use the 'titled' functionality
3244 OO
.ui
.mixin
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
3245 if ( this.$titled
) {
3246 this.$titled
.removeAttr( 'title' );
3249 this.$titled
= $titled
;
3251 this.$titled
.attr( 'title', this.title
);
3258 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
3261 OO
.ui
.mixin
.TitledElement
.prototype.setTitle = function ( title
) {
3262 title
= typeof title
=== 'function' ? OO
.ui
.resolveMsg( title
) : title
;
3263 title
= ( typeof title
=== 'string' && title
.length
) ? title
: null;
3265 if ( this.title
!== title
) {
3266 if ( this.$titled
) {
3267 if ( title
!== null ) {
3268 this.$titled
.attr( 'title', title
);
3270 this.$titled
.removeAttr( 'title' );
3282 * @return {string} Title string
3284 OO
.ui
.mixin
.TitledElement
.prototype.getTitle = function () {
3289 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
3290 * Accesskeys allow an user to go to a specific element by using
3291 * a shortcut combination of a browser specific keys + the key
3295 * // AccessKeyedElement provides an 'accesskey' attribute to the
3296 * // ButtonWidget class
3297 * var button = new OO.ui.ButtonWidget( {
3298 * label: 'Button with Accesskey',
3301 * $( 'body' ).append( button.$element );
3307 * @param {Object} [config] Configuration options
3308 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
3309 * If this config is omitted, the accesskey functionality is applied to $element, the
3310 * element created by the class.
3311 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
3312 * this config is omitted, no accesskey will be added.
3314 OO
.ui
.mixin
.AccessKeyedElement
= function OoUiMixinAccessKeyedElement( config
) {
3315 // Configuration initialization
3316 config
= config
|| {};
3319 this.$accessKeyed
= null;
3320 this.accessKey
= null;
3323 this.setAccessKey( config
.accessKey
|| null );
3324 this.setAccessKeyedElement( config
.$accessKeyed
|| this.$element
);
3329 OO
.initClass( OO
.ui
.mixin
.AccessKeyedElement
);
3331 /* Static Properties */
3334 * The access key, a function that returns a key, or `null` for no accesskey.
3338 * @property {string|Function|null}
3340 OO
.ui
.mixin
.AccessKeyedElement
.static.accessKey
= null;
3345 * Set the accesskeyed element.
3347 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
3348 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
3350 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
3352 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKeyedElement = function ( $accessKeyed
) {
3353 if ( this.$accessKeyed
) {
3354 this.$accessKeyed
.removeAttr( 'accesskey' );
3357 this.$accessKeyed
= $accessKeyed
;
3358 if ( this.accessKey
) {
3359 this.$accessKeyed
.attr( 'accesskey', this.accessKey
);
3366 * @param {string|Function|null} accessKey Key, a function that returns a key, or `null` for no accesskey
3369 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKey = function ( accessKey
) {
3370 accessKey
= typeof accessKey
=== 'string' ? OO
.ui
.resolveMsg( accessKey
) : null;
3372 if ( this.accessKey
!== accessKey
) {
3373 if ( this.$accessKeyed
) {
3374 if ( accessKey
!== null ) {
3375 this.$accessKeyed
.attr( 'accesskey', accessKey
);
3377 this.$accessKeyed
.removeAttr( 'accesskey' );
3380 this.accessKey
= accessKey
;
3389 * @return {string} accessKey string
3391 OO
.ui
.mixin
.AccessKeyedElement
.prototype.getAccessKey = function () {
3392 return this.accessKey
;
3396 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
3397 * feels, and functionality can be customized via the class’s configuration options
3398 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
3401 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
3404 * // A button widget
3405 * var button = new OO.ui.ButtonWidget( {
3406 * label: 'Button with Icon',
3408 * iconTitle: 'Remove'
3410 * $( 'body' ).append( button.$element );
3412 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
3415 * @extends OO.ui.Widget
3416 * @mixins OO.ui.mixin.ButtonElement
3417 * @mixins OO.ui.mixin.IconElement
3418 * @mixins OO.ui.mixin.IndicatorElement
3419 * @mixins OO.ui.mixin.LabelElement
3420 * @mixins OO.ui.mixin.TitledElement
3421 * @mixins OO.ui.mixin.FlaggedElement
3422 * @mixins OO.ui.mixin.TabIndexedElement
3423 * @mixins OO.ui.mixin.AccessKeyedElement
3426 * @param {Object} [config] Configuration options
3427 * @cfg {boolean} [active=false] Whether button should be shown as active
3428 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
3429 * @cfg {string} [target] The frame or window in which to open the hyperlink.
3430 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
3432 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
3433 // Configuration initialization
3434 config
= config
|| {};
3436 // Parent constructor
3437 OO
.ui
.ButtonWidget
.parent
.call( this, config
);
3439 // Mixin constructors
3440 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
3441 OO
.ui
.mixin
.IconElement
.call( this, config
);
3442 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
3443 OO
.ui
.mixin
.LabelElement
.call( this, config
);
3444 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
3445 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
3446 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
3447 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$button
} ) );
3452 this.noFollow
= false;
3455 this.connect( this, { disable
: 'onDisable' } );
3458 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
3460 .addClass( 'oo-ui-buttonWidget' )
3461 .append( this.$button
);
3462 this.setActive( config
.active
);
3463 this.setHref( config
.href
);
3464 this.setTarget( config
.target
);
3465 this.setNoFollow( config
.noFollow
);
3470 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
3471 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
3472 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IconElement
);
3473 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
3474 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.LabelElement
);
3475 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TitledElement
);
3476 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
3477 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
3478 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
3480 /* Static Properties */
3486 OO
.ui
.ButtonWidget
.static.cancelButtonMouseDownEvents
= false;
3492 OO
.ui
.ButtonWidget
.static.tagName
= 'span';
3497 * Get hyperlink location.
3499 * @return {string} Hyperlink location
3501 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
3506 * Get hyperlink target.
3508 * @return {string} Hyperlink target
3510 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
3515 * Get search engine traversal hint.
3517 * @return {boolean} Whether search engines should avoid traversing this hyperlink
3519 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
3520 return this.noFollow
;
3524 * Set hyperlink location.
3526 * @param {string|null} href Hyperlink location, null to remove
3528 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
3529 href
= typeof href
=== 'string' ? href
: null;
3530 if ( href
!== null && !OO
.ui
.isSafeUrl( href
) ) {
3534 if ( href
!== this.href
) {
3543 * Update the `href` attribute, in case of changes to href or
3549 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
3550 if ( this.href
!== null && !this.isDisabled() ) {
3551 this.$button
.attr( 'href', this.href
);
3553 this.$button
.removeAttr( 'href' );
3560 * Handle disable events.
3563 * @param {boolean} disabled Element is disabled
3565 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
3570 * Set hyperlink target.
3572 * @param {string|null} target Hyperlink target, null to remove
3574 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
3575 target
= typeof target
=== 'string' ? target
: null;
3577 if ( target
!== this.target
) {
3578 this.target
= target
;
3579 if ( target
!== null ) {
3580 this.$button
.attr( 'target', target
);
3582 this.$button
.removeAttr( 'target' );
3590 * Set search engine traversal hint.
3592 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
3594 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
3595 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
3597 if ( noFollow
!== this.noFollow
) {
3598 this.noFollow
= noFollow
;
3600 this.$button
.attr( 'rel', 'nofollow' );
3602 this.$button
.removeAttr( 'rel' );
3609 // Override method visibility hints from ButtonElement
3620 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
3621 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
3622 * removed, and cleared from the group.
3625 * // Example: A ButtonGroupWidget with two buttons
3626 * var button1 = new OO.ui.PopupButtonWidget( {
3627 * label: 'Select a category',
3630 * $content: $( '<p>List of categories...</p>' ),
3635 * var button2 = new OO.ui.ButtonWidget( {
3638 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
3639 * items: [button1, button2]
3641 * $( 'body' ).append( buttonGroup.$element );
3644 * @extends OO.ui.Widget
3645 * @mixins OO.ui.mixin.GroupElement
3648 * @param {Object} [config] Configuration options
3649 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
3651 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
3652 // Configuration initialization
3653 config
= config
|| {};
3655 // Parent constructor
3656 OO
.ui
.ButtonGroupWidget
.parent
.call( this, config
);
3658 // Mixin constructors
3659 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
3662 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
3663 if ( Array
.isArray( config
.items
) ) {
3664 this.addItems( config
.items
);
3670 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
3671 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.GroupElement
);
3673 /* Static Properties */
3679 OO
.ui
.ButtonGroupWidget
.static.tagName
= 'span';
3682 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
3683 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
3684 * for a list of icons included in the library.
3687 * // An icon widget with a label
3688 * var myIcon = new OO.ui.IconWidget( {
3692 * // Create a label.
3693 * var iconLabel = new OO.ui.LabelWidget( {
3696 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
3698 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
3701 * @extends OO.ui.Widget
3702 * @mixins OO.ui.mixin.IconElement
3703 * @mixins OO.ui.mixin.TitledElement
3704 * @mixins OO.ui.mixin.FlaggedElement
3707 * @param {Object} [config] Configuration options
3709 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
3710 // Configuration initialization
3711 config
= config
|| {};
3713 // Parent constructor
3714 OO
.ui
.IconWidget
.parent
.call( this, config
);
3716 // Mixin constructors
3717 OO
.ui
.mixin
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
3718 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
3719 OO
.ui
.mixin
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
3722 this.$element
.addClass( 'oo-ui-iconWidget' );
3727 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
3728 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.IconElement
);
3729 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.TitledElement
);
3730 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.FlaggedElement
);
3732 /* Static Properties */
3738 OO
.ui
.IconWidget
.static.tagName
= 'span';
3741 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
3742 * attention to the status of an item or to clarify the function of a control. For a list of
3743 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
3746 * // Example of an indicator widget
3747 * var indicator1 = new OO.ui.IndicatorWidget( {
3748 * indicator: 'alert'
3751 * // Create a fieldset layout to add a label
3752 * var fieldset = new OO.ui.FieldsetLayout();
3753 * fieldset.addItems( [
3754 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
3756 * $( 'body' ).append( fieldset.$element );
3758 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3761 * @extends OO.ui.Widget
3762 * @mixins OO.ui.mixin.IndicatorElement
3763 * @mixins OO.ui.mixin.TitledElement
3766 * @param {Object} [config] Configuration options
3768 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
3769 // Configuration initialization
3770 config
= config
|| {};
3772 // Parent constructor
3773 OO
.ui
.IndicatorWidget
.parent
.call( this, config
);
3775 // Mixin constructors
3776 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
3777 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
3780 this.$element
.addClass( 'oo-ui-indicatorWidget' );
3785 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
3786 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.IndicatorElement
);
3787 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.TitledElement
);
3789 /* Static Properties */
3795 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
3798 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
3799 * be configured with a `label` option that is set to a string, a label node, or a function:
3801 * - String: a plaintext string
3802 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
3803 * label that includes a link or special styling, such as a gray color or additional graphical elements.
3804 * - Function: a function that will produce a string in the future. Functions are used
3805 * in cases where the value of the label is not currently defined.
3807 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
3808 * will come into focus when the label is clicked.
3811 * // Examples of LabelWidgets
3812 * var label1 = new OO.ui.LabelWidget( {
3813 * label: 'plaintext label'
3815 * var label2 = new OO.ui.LabelWidget( {
3816 * label: $( '<a href="default.html">jQuery label</a>' )
3818 * // Create a fieldset layout with fields for each example
3819 * var fieldset = new OO.ui.FieldsetLayout();
3820 * fieldset.addItems( [
3821 * new OO.ui.FieldLayout( label1 ),
3822 * new OO.ui.FieldLayout( label2 )
3824 * $( 'body' ).append( fieldset.$element );
3827 * @extends OO.ui.Widget
3828 * @mixins OO.ui.mixin.LabelElement
3829 * @mixins OO.ui.mixin.TitledElement
3832 * @param {Object} [config] Configuration options
3833 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
3834 * Clicking the label will focus the specified input field.
3836 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
3837 // Configuration initialization
3838 config
= config
|| {};
3840 // Parent constructor
3841 OO
.ui
.LabelWidget
.parent
.call( this, config
);
3843 // Mixin constructors
3844 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
3845 OO
.ui
.mixin
.TitledElement
.call( this, config
);
3848 this.input
= config
.input
;
3851 if ( this.input
instanceof OO
.ui
.InputWidget
) {
3852 if ( this.input
.getInputId() ) {
3853 this.$element
.attr( 'for', this.input
.getInputId() );
3855 this.$label
.on( 'click', function () {
3856 this.fieldWidget
.focus();
3861 this.$element
.addClass( 'oo-ui-labelWidget' );
3866 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
3867 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.LabelElement
);
3868 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.TitledElement
);
3870 /* Static Properties */
3876 OO
.ui
.LabelWidget
.static.tagName
= 'label';
3879 * PendingElement is a mixin that is used to create elements that notify users that something is happening
3880 * and that they should wait before proceeding. The pending state is visually represented with a pending
3881 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
3882 * field of a {@link OO.ui.TextInputWidget text input widget}.
3884 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
3885 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
3886 * in process dialogs.
3889 * function MessageDialog( config ) {
3890 * MessageDialog.parent.call( this, config );
3892 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
3894 * MessageDialog.static.name = 'myMessageDialog';
3895 * MessageDialog.static.actions = [
3896 * { action: 'save', label: 'Done', flags: 'primary' },
3897 * { label: 'Cancel', flags: 'safe' }
3900 * MessageDialog.prototype.initialize = function () {
3901 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
3902 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
3903 * 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>' );
3904 * this.$body.append( this.content.$element );
3906 * MessageDialog.prototype.getBodyHeight = function () {
3909 * MessageDialog.prototype.getActionProcess = function ( action ) {
3910 * var dialog = this;
3911 * if ( action === 'save' ) {
3912 * dialog.getActions().get({actions: 'save'})[0].pushPending();
3913 * return new OO.ui.Process()
3915 * .next( function () {
3916 * dialog.getActions().get({actions: 'save'})[0].popPending();
3919 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
3922 * var windowManager = new OO.ui.WindowManager();
3923 * $( 'body' ).append( windowManager.$element );
3925 * var dialog = new MessageDialog();
3926 * windowManager.addWindows( [ dialog ] );
3927 * windowManager.openWindow( dialog );
3933 * @param {Object} [config] Configuration options
3934 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
3936 OO
.ui
.mixin
.PendingElement
= function OoUiMixinPendingElement( config
) {
3937 // Configuration initialization
3938 config
= config
|| {};
3942 this.$pending
= null;
3945 this.setPendingElement( config
.$pending
|| this.$element
);
3950 OO
.initClass( OO
.ui
.mixin
.PendingElement
);
3955 * Set the pending element (and clean up any existing one).
3957 * @param {jQuery} $pending The element to set to pending.
3959 OO
.ui
.mixin
.PendingElement
.prototype.setPendingElement = function ( $pending
) {
3960 if ( this.$pending
) {
3961 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
3964 this.$pending
= $pending
;
3965 if ( this.pending
> 0 ) {
3966 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
3971 * Check if an element is pending.
3973 * @return {boolean} Element is pending
3975 OO
.ui
.mixin
.PendingElement
.prototype.isPending = function () {
3976 return !!this.pending
;
3980 * Increase the pending counter. The pending state will remain active until the counter is zero
3981 * (i.e., the number of calls to #pushPending and #popPending is the same).
3985 OO
.ui
.mixin
.PendingElement
.prototype.pushPending = function () {
3986 if ( this.pending
=== 0 ) {
3987 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
3988 this.updateThemeClasses();
3996 * Decrease the pending counter. The pending state will remain active until the counter is zero
3997 * (i.e., the number of calls to #pushPending and #popPending is the same).
4001 OO
.ui
.mixin
.PendingElement
.prototype.popPending = function () {
4002 if ( this.pending
=== 1 ) {
4003 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
4004 this.updateThemeClasses();
4006 this.pending
= Math
.max( 0, this.pending
- 1 );
4012 * Element that will stick adjacent to a specified container, even when it is inserted elsewhere
4013 * in the document (for example, in an OO.ui.Window's $overlay).
4015 * The elements's position is automatically calculated and maintained when window is resized or the
4016 * page is scrolled. If you reposition the container manually, you have to call #position to make
4017 * sure the element is still placed correctly.
4019 * As positioning is only possible when both the element and the container are attached to the DOM
4020 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
4021 * the #toggle method to display a floating popup, for example.
4027 * @param {Object} [config] Configuration options
4028 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
4029 * @cfg {jQuery} [$floatableContainer] Node to position adjacent to
4030 * @cfg {string} [verticalPosition='below'] Where to position $floatable vertically:
4031 * 'below': Directly below $floatableContainer, aligning f's top edge with fC's bottom edge
4032 * 'above': Directly above $floatableContainer, aligning f's bottom edge with fC's top edge
4033 * 'top': Align the top edge with $floatableContainer's top edge
4034 * 'bottom': Align the bottom edge with $floatableContainer's bottom edge
4035 * 'center': Vertically align the center with $floatableContainer's center
4036 * @cfg {string} [horizontalPosition='start'] Where to position $floatable horizontally:
4037 * 'before': Directly before $floatableContainer, aligning f's end edge with fC's start edge
4038 * 'after': Directly after $floatableContainer, algining f's start edge with fC's end edge
4039 * 'start': Align the start (left in LTR, right in RTL) edge with $floatableContainer's start edge
4040 * 'end': Align the end (right in LTR, left in RTL) edge with $floatableContainer's end edge
4041 * 'center': Horizontally align the center with $floatableContainer's center
4042 * @cfg {boolean} [hideWhenOutOfView=true] Whether to hide the floatable element if the container
4045 OO
.ui
.mixin
.FloatableElement
= function OoUiMixinFloatableElement( config
) {
4046 // Configuration initialization
4047 config
= config
|| {};
4050 this.$floatable
= null;
4051 this.$floatableContainer
= null;
4052 this.$floatableWindow
= null;
4053 this.$floatableClosestScrollable
= null;
4054 this.onFloatableScrollHandler
= this.position
.bind( this );
4055 this.onFloatableWindowResizeHandler
= this.position
.bind( this );
4058 this.setFloatableContainer( config
.$floatableContainer
);
4059 this.setFloatableElement( config
.$floatable
|| this.$element
);
4060 this.setVerticalPosition( config
.verticalPosition
|| 'below' );
4061 this.setHorizontalPosition( config
.horizontalPosition
|| 'start' );
4062 this.hideWhenOutOfView
= config
.hideWhenOutOfView
=== undefined ? true : !!config
.hideWhenOutOfView
;
4068 * Set floatable element.
4070 * If an element is already set, it will be cleaned up before setting up the new element.
4072 * @param {jQuery} $floatable Element to make floatable
4074 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableElement = function ( $floatable
) {
4075 if ( this.$floatable
) {
4076 this.$floatable
.removeClass( 'oo-ui-floatableElement-floatable' );
4077 this.$floatable
.css( { left
: '', top
: '' } );
4080 this.$floatable
= $floatable
.addClass( 'oo-ui-floatableElement-floatable' );
4085 * Set floatable container.
4087 * The element will be positioned relative to the specified container.
4089 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
4091 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableContainer = function ( $floatableContainer
) {
4092 this.$floatableContainer
= $floatableContainer
;
4093 if ( this.$floatable
) {
4099 * Change how the element is positioned vertically.
4101 * @param {string} position 'below', 'above', 'top', 'bottom' or 'center'
4103 OO
.ui
.mixin
.FloatableElement
.prototype.setVerticalPosition = function ( position
) {
4104 if ( [ 'below', 'above', 'top', 'bottom', 'center' ].indexOf( position
) === -1 ) {
4105 throw new Error( 'Invalid value for vertical position: ' + position
);
4107 if ( this.verticalPosition
!== position
) {
4108 this.verticalPosition
= position
;
4109 if ( this.$floatable
) {
4116 * Change how the element is positioned horizontally.
4118 * @param {string} position 'before', 'after', 'start', 'end' or 'center'
4120 OO
.ui
.mixin
.FloatableElement
.prototype.setHorizontalPosition = function ( position
) {
4121 if ( [ 'before', 'after', 'start', 'end', 'center' ].indexOf( position
) === -1 ) {
4122 throw new Error( 'Invalid value for horizontal position: ' + position
);
4124 if ( this.horizontalPosition
!== position
) {
4125 this.horizontalPosition
= position
;
4126 if ( this.$floatable
) {
4133 * Toggle positioning.
4135 * Do not turn positioning on until after the element is attached to the DOM and visible.
4137 * @param {boolean} [positioning] Enable positioning, omit to toggle
4140 OO
.ui
.mixin
.FloatableElement
.prototype.togglePositioning = function ( positioning
) {
4141 var closestScrollableOfContainer
;
4143 if ( !this.$floatable
|| !this.$floatableContainer
) {
4147 positioning
= positioning
=== undefined ? !this.positioning
: !!positioning
;
4149 if ( positioning
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
4150 OO
.ui
.warnDeprecation( 'FloatableElement#togglePositioning: Before calling this method, the element must be attached to the DOM.' );
4151 this.warnedUnattached
= true;
4154 if ( this.positioning
!== positioning
) {
4155 this.positioning
= positioning
;
4157 this.needsCustomPosition
=
4158 this.verticalPostion
!== 'below' ||
4159 this.horizontalPosition
!== 'start' ||
4160 !OO
.ui
.contains( this.$floatableContainer
[ 0 ], this.$floatable
[ 0 ] );
4162 closestScrollableOfContainer
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatableContainer
[ 0 ] );
4163 // If the scrollable is the root, we have to listen to scroll events
4164 // on the window because of browser inconsistencies.
4165 if ( $( closestScrollableOfContainer
).is( 'html, body' ) ) {
4166 closestScrollableOfContainer
= OO
.ui
.Element
.static.getWindow( closestScrollableOfContainer
);
4169 if ( positioning
) {
4170 this.$floatableWindow
= $( this.getElementWindow() );
4171 this.$floatableWindow
.on( 'resize', this.onFloatableWindowResizeHandler
);
4173 this.$floatableClosestScrollable
= $( closestScrollableOfContainer
);
4174 this.$floatableClosestScrollable
.on( 'scroll', this.onFloatableScrollHandler
);
4176 // Initial position after visible
4179 if ( this.$floatableWindow
) {
4180 this.$floatableWindow
.off( 'resize', this.onFloatableWindowResizeHandler
);
4181 this.$floatableWindow
= null;
4184 if ( this.$floatableClosestScrollable
) {
4185 this.$floatableClosestScrollable
.off( 'scroll', this.onFloatableScrollHandler
);
4186 this.$floatableClosestScrollable
= null;
4189 this.$floatable
.css( { left
: '', right
: '', top
: '' } );
4197 * Check whether the bottom edge of the given element is within the viewport of the given container.
4200 * @param {jQuery} $element
4201 * @param {jQuery} $container
4204 OO
.ui
.mixin
.FloatableElement
.prototype.isElementInViewport = function ( $element
, $container
) {
4205 var elemRect
, contRect
, topEdgeInBounds
, bottomEdgeInBounds
, leftEdgeInBounds
, rightEdgeInBounds
,
4206 startEdgeInBounds
, endEdgeInBounds
,
4207 direction
= $element
.css( 'direction' );
4209 elemRect
= $element
[ 0 ].getBoundingClientRect();
4210 if ( $container
[ 0 ] === window
) {
4214 right
: document
.documentElement
.clientWidth
,
4215 bottom
: document
.documentElement
.clientHeight
4218 contRect
= $container
[ 0 ].getBoundingClientRect();
4221 topEdgeInBounds
= elemRect
.top
>= contRect
.top
&& elemRect
.top
<= contRect
.bottom
;
4222 bottomEdgeInBounds
= elemRect
.bottom
>= contRect
.top
&& elemRect
.bottom
<= contRect
.bottom
;
4223 leftEdgeInBounds
= elemRect
.left
>= contRect
.left
&& elemRect
.left
<= contRect
.right
;
4224 rightEdgeInBounds
= elemRect
.right
>= contRect
.left
&& elemRect
.right
<= contRect
.right
;
4225 if ( direction
=== 'rtl' ) {
4226 startEdgeInBounds
= rightEdgeInBounds
;
4227 endEdgeInBounds
= leftEdgeInBounds
;
4229 startEdgeInBounds
= leftEdgeInBounds
;
4230 endEdgeInBounds
= rightEdgeInBounds
;
4233 if ( this.verticalPosition
=== 'below' && !bottomEdgeInBounds
) {
4236 if ( this.verticalPosition
=== 'above' && !topEdgeInBounds
) {
4239 if ( this.horizontalPosition
=== 'before' && !startEdgeInBounds
) {
4242 if ( this.horizontalPosition
=== 'after' && !endEdgeInBounds
) {
4246 // The other positioning values are all about being inside the container,
4247 // so in those cases all we care about is that any part of the container is visible.
4248 return elemRect
.top
<= contRect
.bottom
&& elemRect
.bottom
>= contRect
.top
&&
4249 elemRect
.left
<= contRect
.right
&& elemRect
.right
>= contRect
.left
;
4253 * Position the floatable below its container.
4255 * This should only be done when both of them are attached to the DOM and visible.
4259 OO
.ui
.mixin
.FloatableElement
.prototype.position = function () {
4260 if ( !this.positioning
) {
4265 // To continue, some things need to be true:
4266 // The element must actually be in the DOM
4267 this.isElementAttached() && (
4268 // The closest scrollable is the current window
4269 this.$floatableClosestScrollable
[ 0 ] === this.getElementWindow() ||
4270 // OR is an element in the element's DOM
4271 $.contains( this.getElementDocument(), this.$floatableClosestScrollable
[ 0 ] )
4274 // Abort early if important parts of the widget are no longer attached to the DOM
4278 if ( this.hideWhenOutOfView
&& !this.isElementInViewport( this.$floatableContainer
, this.$floatableClosestScrollable
) ) {
4279 this.$floatable
.addClass( 'oo-ui-element-hidden' );
4282 this.$floatable
.removeClass( 'oo-ui-element-hidden' );
4285 if ( !this.needsCustomPosition
) {
4289 this.$floatable
.css( this.computePosition() );
4291 // We updated the position, so re-evaluate the clipping state.
4292 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
4293 // will not notice the need to update itself.)
4294 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
4295 // it not listen to the right events in the right places?
4304 * Compute how #$floatable should be positioned based on the position of #$floatableContainer
4305 * and the positioning settings. This is a helper for #position that shouldn't be called directly,
4306 * but may be overridden by subclasses if they want to change or add to the positioning logic.
4308 * @return {Object} New position to apply with .css(). Keys are 'top', 'left', 'bottom' and 'right'.
4310 OO
.ui
.mixin
.FloatableElement
.prototype.computePosition = function () {
4311 var isBody
, scrollableX
, scrollableY
, containerPos
,
4312 horizScrollbarHeight
, vertScrollbarWidth
, scrollTop
, scrollLeft
,
4313 newPos
= { top
: '', left
: '', bottom
: '', right
: '' },
4314 direction
= this.$floatableContainer
.css( 'direction' ),
4315 $offsetParent
= this.$floatable
.offsetParent();
4317 if ( $offsetParent
.is( 'html' ) ) {
4318 // The innerHeight/Width and clientHeight/Width calculations don't work well on the
4319 // <html> element, but they do work on the <body>
4320 $offsetParent
= $( $offsetParent
[ 0 ].ownerDocument
.body
);
4322 isBody
= $offsetParent
.is( 'body' );
4323 scrollableX
= $offsetParent
.css( 'overflow-x' ) === 'scroll' || $offsetParent
.css( 'overflow-x' ) === 'auto';
4324 scrollableY
= $offsetParent
.css( 'overflow-y' ) === 'scroll' || $offsetParent
.css( 'overflow-y' ) === 'auto';
4326 vertScrollbarWidth
= $offsetParent
.innerWidth() - $offsetParent
.prop( 'clientWidth' );
4327 horizScrollbarHeight
= $offsetParent
.innerHeight() - $offsetParent
.prop( 'clientHeight' );
4328 // We don't need to compute and add scrollTop and scrollLeft if the scrollable container is the body,
4329 // or if it isn't scrollable
4330 scrollTop
= scrollableY
&& !isBody
? $offsetParent
.scrollTop() : 0;
4331 scrollLeft
= scrollableX
&& !isBody
? OO
.ui
.Element
.static.getScrollLeft( $offsetParent
[ 0 ] ) : 0;
4333 // Avoid passing the <body> to getRelativePosition(), because it won't return what we expect
4334 // if the <body> has a margin
4335 containerPos
= isBody
?
4336 this.$floatableContainer
.offset() :
4337 OO
.ui
.Element
.static.getRelativePosition( this.$floatableContainer
, $offsetParent
);
4338 containerPos
.bottom
= containerPos
.top
+ this.$floatableContainer
.outerHeight();
4339 containerPos
.right
= containerPos
.left
+ this.$floatableContainer
.outerWidth();
4340 containerPos
.start
= direction
=== 'rtl' ? containerPos
.right
: containerPos
.left
;
4341 containerPos
.end
= direction
=== 'rtl' ? containerPos
.left
: containerPos
.right
;
4343 if ( this.verticalPosition
=== 'below' ) {
4344 newPos
.top
= containerPos
.bottom
;
4345 } else if ( this.verticalPosition
=== 'above' ) {
4346 newPos
.bottom
= $offsetParent
.outerHeight() - containerPos
.top
;
4347 } else if ( this.verticalPosition
=== 'top' ) {
4348 newPos
.top
= containerPos
.top
;
4349 } else if ( this.verticalPosition
=== 'bottom' ) {
4350 newPos
.bottom
= $offsetParent
.outerHeight() - containerPos
.bottom
;
4351 } else if ( this.verticalPosition
=== 'center' ) {
4352 newPos
.top
= containerPos
.top
+
4353 ( this.$floatableContainer
.height() - this.$floatable
.height() ) / 2;
4356 if ( this.horizontalPosition
=== 'before' ) {
4357 newPos
.end
= containerPos
.start
;
4358 } else if ( this.horizontalPosition
=== 'after' ) {
4359 newPos
.start
= containerPos
.end
;
4360 } else if ( this.horizontalPosition
=== 'start' ) {
4361 newPos
.start
= containerPos
.start
;
4362 } else if ( this.horizontalPosition
=== 'end' ) {
4363 newPos
.end
= containerPos
.end
;
4364 } else if ( this.horizontalPosition
=== 'center' ) {
4365 newPos
.left
= containerPos
.left
+
4366 ( this.$floatableContainer
.width() - this.$floatable
.width() ) / 2;
4369 if ( newPos
.start
!== undefined ) {
4370 if ( direction
=== 'rtl' ) {
4371 newPos
.right
= ( isBody
? $( $offsetParent
[ 0 ].ownerDocument
.documentElement
) : $offsetParent
).outerWidth() - newPos
.start
;
4373 newPos
.left
= newPos
.start
;
4375 delete newPos
.start
;
4377 if ( newPos
.end
!== undefined ) {
4378 if ( direction
=== 'rtl' ) {
4379 newPos
.left
= newPos
.end
;
4381 newPos
.right
= ( isBody
? $( $offsetParent
[ 0 ].ownerDocument
.documentElement
) : $offsetParent
).outerWidth() - newPos
.end
;
4386 // Account for scroll position
4387 if ( newPos
.top
!== '' ) {
4388 newPos
.top
+= scrollTop
;
4390 if ( newPos
.bottom
!== '' ) {
4391 newPos
.bottom
-= scrollTop
;
4393 if ( newPos
.left
!== '' ) {
4394 newPos
.left
+= scrollLeft
;
4396 if ( newPos
.right
!== '' ) {
4397 newPos
.right
-= scrollLeft
;
4400 // Account for scrollbar gutter
4401 if ( newPos
.bottom
!== '' ) {
4402 newPos
.bottom
-= horizScrollbarHeight
;
4404 if ( direction
=== 'rtl' ) {
4405 if ( newPos
.left
!== '' ) {
4406 newPos
.left
-= vertScrollbarWidth
;
4409 if ( newPos
.right
!== '' ) {
4410 newPos
.right
-= vertScrollbarWidth
;
4418 * Element that can be automatically clipped to visible boundaries.
4420 * Whenever the element's natural height changes, you have to call
4421 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
4422 * clipping correctly.
4424 * The dimensions of #$clippableContainer will be compared to the boundaries of the
4425 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
4426 * then #$clippable will be given a fixed reduced height and/or width and will be made
4427 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
4428 * but you can build a static footer by setting #$clippableContainer to an element that contains
4429 * #$clippable and the footer.
4435 * @param {Object} [config] Configuration options
4436 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
4437 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
4438 * omit to use #$clippable
4440 OO
.ui
.mixin
.ClippableElement
= function OoUiMixinClippableElement( config
) {
4441 // Configuration initialization
4442 config
= config
|| {};
4445 this.$clippable
= null;
4446 this.$clippableContainer
= null;
4447 this.clipping
= false;
4448 this.clippedHorizontally
= false;
4449 this.clippedVertically
= false;
4450 this.$clippableScrollableContainer
= null;
4451 this.$clippableScroller
= null;
4452 this.$clippableWindow
= null;
4453 this.idealWidth
= null;
4454 this.idealHeight
= null;
4455 this.onClippableScrollHandler
= this.clip
.bind( this );
4456 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
4459 if ( config
.$clippableContainer
) {
4460 this.setClippableContainer( config
.$clippableContainer
);
4462 this.setClippableElement( config
.$clippable
|| this.$element
);
4468 * Set clippable element.
4470 * If an element is already set, it will be cleaned up before setting up the new element.
4472 * @param {jQuery} $clippable Element to make clippable
4474 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
4475 if ( this.$clippable
) {
4476 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
4477 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
4478 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4481 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
4486 * Set clippable container.
4488 * This is the container that will be measured when deciding whether to clip. When clipping,
4489 * #$clippable will be resized in order to keep the clippable container fully visible.
4491 * If the clippable container is unset, #$clippable will be used.
4493 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
4495 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableContainer = function ( $clippableContainer
) {
4496 this.$clippableContainer
= $clippableContainer
;
4497 if ( this.$clippable
) {
4505 * Do not turn clipping on until after the element is attached to the DOM and visible.
4507 * @param {boolean} [clipping] Enable clipping, omit to toggle
4510 OO
.ui
.mixin
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
4511 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
4513 if ( clipping
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
4514 OO
.ui
.warnDeprecation( 'ClippableElement#toggleClipping: Before calling this method, the element must be attached to the DOM.' );
4515 this.warnedUnattached
= true;
4518 if ( this.clipping
!== clipping
) {
4519 this.clipping
= clipping
;
4521 this.$clippableScrollableContainer
= $( this.getClosestScrollableElementContainer() );
4522 // If the clippable container is the root, we have to listen to scroll events and check
4523 // jQuery.scrollTop on the window because of browser inconsistencies
4524 this.$clippableScroller
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
4525 $( OO
.ui
.Element
.static.getWindow( this.$clippableScrollableContainer
) ) :
4526 this.$clippableScrollableContainer
;
4527 this.$clippableScroller
.on( 'scroll', this.onClippableScrollHandler
);
4528 this.$clippableWindow
= $( this.getElementWindow() )
4529 .on( 'resize', this.onClippableWindowResizeHandler
);
4530 // Initial clip after visible
4533 this.$clippable
.css( {
4541 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4543 this.$clippableScrollableContainer
= null;
4544 this.$clippableScroller
.off( 'scroll', this.onClippableScrollHandler
);
4545 this.$clippableScroller
= null;
4546 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
4547 this.$clippableWindow
= null;
4555 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
4557 * @return {boolean} Element will be clipped to the visible area
4559 OO
.ui
.mixin
.ClippableElement
.prototype.isClipping = function () {
4560 return this.clipping
;
4564 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
4566 * @return {boolean} Part of the element is being clipped
4568 OO
.ui
.mixin
.ClippableElement
.prototype.isClipped = function () {
4569 return this.clippedHorizontally
|| this.clippedVertically
;
4573 * Check if the right of the element is being clipped by the nearest scrollable container.
4575 * @return {boolean} Part of the element is being clipped
4577 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedHorizontally = function () {
4578 return this.clippedHorizontally
;
4582 * Check if the bottom of the element is being clipped by the nearest scrollable container.
4584 * @return {boolean} Part of the element is being clipped
4586 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedVertically = function () {
4587 return this.clippedVertically
;
4591 * Set the ideal size. These are the dimensions #$clippable will have when it's not being clipped.
4593 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
4594 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
4596 OO
.ui
.mixin
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
4597 this.idealWidth
= width
;
4598 this.idealHeight
= height
;
4600 if ( !this.clipping
) {
4601 // Update dimensions
4602 this.$clippable
.css( { width
: width
, height
: height
} );
4604 // While clipping, idealWidth and idealHeight are not considered
4608 * Clip element to visible boundaries and allow scrolling when needed. You should call this method
4609 * when the element's natural height changes.
4611 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
4612 * overlapped by, the visible area of the nearest scrollable container.
4614 * Because calling clip() when the natural height changes isn't always possible, we also set
4615 * max-height when the element isn't being clipped. This means that if the element tries to grow
4616 * beyond the edge, something reasonable will happen before clip() is called.
4620 OO
.ui
.mixin
.ClippableElement
.prototype.clip = function () {
4621 var $container
, extraHeight
, extraWidth
, ccOffset
,
4622 $scrollableContainer
, scOffset
, scHeight
, scWidth
,
4623 ccWidth
, scrollerIsWindow
, scrollTop
, scrollLeft
,
4624 desiredWidth
, desiredHeight
, allotedWidth
, allotedHeight
,
4625 naturalWidth
, naturalHeight
, clipWidth
, clipHeight
,
4626 buffer
= 7; // Chosen by fair dice roll
4628 if ( !this.clipping
) {
4629 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
4633 $container
= this.$clippableContainer
|| this.$clippable
;
4634 extraHeight
= $container
.outerHeight() - this.$clippable
.outerHeight();
4635 extraWidth
= $container
.outerWidth() - this.$clippable
.outerWidth();
4636 ccOffset
= $container
.offset();
4637 if ( this.$clippableScrollableContainer
.is( 'html, body' ) ) {
4638 $scrollableContainer
= this.$clippableWindow
;
4639 scOffset
= { top
: 0, left
: 0 };
4641 $scrollableContainer
= this.$clippableScrollableContainer
;
4642 scOffset
= $scrollableContainer
.offset();
4644 scHeight
= $scrollableContainer
.innerHeight() - buffer
;
4645 scWidth
= $scrollableContainer
.innerWidth() - buffer
;
4646 ccWidth
= $container
.outerWidth() + buffer
;
4647 scrollerIsWindow
= this.$clippableScroller
[ 0 ] === this.$clippableWindow
[ 0 ];
4648 scrollTop
= scrollerIsWindow
? this.$clippableScroller
.scrollTop() : 0;
4649 scrollLeft
= scrollerIsWindow
? this.$clippableScroller
.scrollLeft() : 0;
4650 desiredWidth
= ccOffset
.left
< 0 ?
4651 ccWidth
+ ccOffset
.left
:
4652 ( scOffset
.left
+ scrollLeft
+ scWidth
) - ccOffset
.left
;
4653 desiredHeight
= ( scOffset
.top
+ scrollTop
+ scHeight
) - ccOffset
.top
;
4654 // It should never be desirable to exceed the dimensions of the browser viewport... right?
4655 desiredWidth
= Math
.min( desiredWidth
, document
.documentElement
.clientWidth
);
4656 desiredHeight
= Math
.min( desiredHeight
, document
.documentElement
.clientHeight
);
4657 allotedWidth
= Math
.ceil( desiredWidth
- extraWidth
);
4658 allotedHeight
= Math
.ceil( desiredHeight
- extraHeight
);
4659 naturalWidth
= this.$clippable
.prop( 'scrollWidth' );
4660 naturalHeight
= this.$clippable
.prop( 'scrollHeight' );
4661 clipWidth
= allotedWidth
< naturalWidth
;
4662 clipHeight
= allotedHeight
< naturalHeight
;
4665 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. (T157672)
4666 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
4667 this.$clippable
.css( 'overflowX', 'scroll' );
4668 void this.$clippable
[ 0 ].offsetHeight
; // Force reflow
4669 this.$clippable
.css( {
4670 width
: Math
.max( 0, allotedWidth
),
4674 this.$clippable
.css( {
4676 width
: this.idealWidth
|| '',
4677 maxWidth
: Math
.max( 0, allotedWidth
)
4681 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. (T157672)
4682 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
4683 this.$clippable
.css( 'overflowY', 'scroll' );
4684 void this.$clippable
[ 0 ].offsetHeight
; // Force reflow
4685 this.$clippable
.css( {
4686 height
: Math
.max( 0, allotedHeight
),
4690 this.$clippable
.css( {
4692 height
: this.idealHeight
|| '',
4693 maxHeight
: Math
.max( 0, allotedHeight
)
4697 // If we stopped clipping in at least one of the dimensions
4698 if ( ( this.clippedHorizontally
&& !clipWidth
) || ( this.clippedVertically
&& !clipHeight
) ) {
4699 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4702 this.clippedHorizontally
= clipWidth
;
4703 this.clippedVertically
= clipHeight
;
4709 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
4710 * By default, each popup has an anchor that points toward its origin.
4711 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
4713 * Unlike most widgets, PopupWidget is initially hidden and must be shown by calling #toggle.
4716 * // A popup widget.
4717 * var popup = new OO.ui.PopupWidget( {
4718 * $content: $( '<p>Hi there!</p>' ),
4723 * $( 'body' ).append( popup.$element );
4724 * // To display the popup, toggle the visibility to 'true'.
4725 * popup.toggle( true );
4727 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
4730 * @extends OO.ui.Widget
4731 * @mixins OO.ui.mixin.LabelElement
4732 * @mixins OO.ui.mixin.ClippableElement
4733 * @mixins OO.ui.mixin.FloatableElement
4736 * @param {Object} [config] Configuration options
4737 * @cfg {number} [width=320] Width of popup in pixels
4738 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
4739 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
4740 * @cfg {string} [position='below'] Where to position the popup relative to $floatableContainer
4741 * 'above': Put popup above $floatableContainer; anchor points down to the horizontal center
4742 * of $floatableContainer
4743 * 'below': Put popup below $floatableContainer; anchor points up to the horizontal center
4744 * of $floatableContainer
4745 * 'before': Put popup to the left (LTR) / right (RTL) of $floatableContainer; anchor points
4746 * endwards (right/left) to the vertical center of $floatableContainer
4747 * 'after': Put popup to the right (LTR) / left (RTL) of $floatableContainer; anchor points
4748 * startwards (left/right) to the vertical center of $floatableContainer
4749 * @cfg {string} [align='center'] How to align the popup to $floatableContainer
4750 * 'forwards': If position is above/below, move the popup as far endwards (right in LTR, left in RTL)
4751 * as possible while still keeping the anchor within the popup;
4752 * if position is before/after, move the popup as far downwards as possible.
4753 * 'backwards': If position is above/below, move the popup as far startwards (left in LTR, right in RTL)
4754 * as possible while still keeping the anchor within the popup;
4755 * if position in before/after, move the popup as far upwards as possible.
4756 * 'center': Horizontally (if position is above/below) or vertically (before/after) align the center
4757 * of the popup with the center of $floatableContainer.
4758 * 'force-left': Alias for 'forwards' in LTR and 'backwards' in RTL
4759 * 'force-right': Alias for 'backwards' in RTL and 'forwards' in LTR
4760 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
4761 * See the [OOjs UI docs on MediaWiki][3] for an example.
4762 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
4763 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
4764 * @cfg {jQuery} [$content] Content to append to the popup's body
4765 * @cfg {jQuery} [$footer] Content to append to the popup's footer
4766 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
4767 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
4768 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
4770 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
4771 * @cfg {boolean} [head=false] Show a popup header that contains a #label (if specified) and close
4773 * @cfg {boolean} [padded=false] Add padding to the popup's body
4775 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
4776 // Configuration initialization
4777 config
= config
|| {};
4779 // Parent constructor
4780 OO
.ui
.PopupWidget
.parent
.call( this, config
);
4782 // Properties (must be set before ClippableElement constructor call)
4783 this.$body
= $( '<div>' );
4784 this.$popup
= $( '<div>' );
4786 // Mixin constructors
4787 OO
.ui
.mixin
.LabelElement
.call( this, config
);
4788 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, {
4789 $clippable
: this.$body
,
4790 $clippableContainer
: this.$popup
4792 OO
.ui
.mixin
.FloatableElement
.call( this, config
);
4795 this.$anchor
= $( '<div>' );
4796 // If undefined, will be computed lazily in updateDimensions()
4797 this.$container
= config
.$container
;
4798 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
4799 this.autoClose
= !!config
.autoClose
;
4800 this.$autoCloseIgnore
= config
.$autoCloseIgnore
;
4801 this.transitionTimeout
= null;
4802 this.anchored
= false;
4803 this.width
= config
.width
!== undefined ? config
.width
: 320;
4804 this.height
= config
.height
!== undefined ? config
.height
: null;
4805 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
4806 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
4809 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
4810 this.setAlignment( config
.align
|| 'center' );
4811 this.setPosition( config
.position
|| 'below' );
4812 this.$body
.addClass( 'oo-ui-popupWidget-body' );
4813 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
4815 .addClass( 'oo-ui-popupWidget-popup' )
4816 .append( this.$body
);
4818 .addClass( 'oo-ui-popupWidget' )
4819 .append( this.$popup
, this.$anchor
);
4820 // Move content, which was added to #$element by OO.ui.Widget, to the body
4821 // FIXME This is gross, we should use '$body' or something for the config
4822 if ( config
.$content
instanceof jQuery
) {
4823 this.$body
.append( config
.$content
);
4826 if ( config
.padded
) {
4827 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
4830 if ( config
.head
) {
4831 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
4832 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
4833 this.$head
= $( '<div>' )
4834 .addClass( 'oo-ui-popupWidget-head' )
4835 .append( this.$label
, this.closeButton
.$element
);
4836 this.$popup
.prepend( this.$head
);
4839 if ( config
.$footer
) {
4840 this.$footer
= $( '<div>' )
4841 .addClass( 'oo-ui-popupWidget-footer' )
4842 .append( config
.$footer
);
4843 this.$popup
.append( this.$footer
);
4846 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
4847 // that reference properties not initialized at that time of parent class construction
4848 // TODO: Find a better way to handle post-constructor setup
4849 this.visible
= false;
4850 this.$element
.addClass( 'oo-ui-element-hidden' );
4855 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
4856 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.LabelElement
);
4857 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.ClippableElement
);
4858 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.FloatableElement
);
4865 * The popup is ready: it is visible and has been positioned and clipped.
4871 * Handles mouse down events.
4874 * @param {MouseEvent} e Mouse down event
4876 OO
.ui
.PopupWidget
.prototype.onMouseDown = function ( e
) {
4879 !OO
.ui
.contains( this.$element
.add( this.$autoCloseIgnore
).get(), e
.target
, true )
4881 this.toggle( false );
4886 * Bind mouse down listener.
4890 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
4891 // Capture clicks outside popup
4892 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler
, true );
4896 * Handles close button click events.
4900 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
4901 if ( this.isVisible() ) {
4902 this.toggle( false );
4907 * Unbind mouse down listener.
4911 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
4912 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler
, true );
4916 * Handles key down events.
4919 * @param {KeyboardEvent} e Key down event
4921 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
4923 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
4926 this.toggle( false );
4928 e
.stopPropagation();
4933 * Bind key down listener.
4937 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
4938 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
4942 * Unbind key down listener.
4946 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
4947 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
4951 * Show, hide, or toggle the visibility of the anchor.
4953 * @param {boolean} [show] Show anchor, omit to toggle
4955 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
4956 show
= show
=== undefined ? !this.anchored
: !!show
;
4958 if ( this.anchored
!== show
) {
4960 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
4961 this.$element
.addClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
4963 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
4964 this.$element
.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
4966 this.anchored
= show
;
4970 * Change which edge the anchor appears on.
4972 * @param {string} edge 'top', 'bottom', 'start' or 'end'
4974 OO
.ui
.PopupWidget
.prototype.setAnchorEdge = function ( edge
) {
4975 if ( [ 'top', 'bottom', 'start', 'end' ].indexOf( edge
) === -1 ) {
4976 throw new Error( 'Invalid value for edge: ' + edge
);
4978 if ( this.anchorEdge
!== null ) {
4979 this.$element
.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
4981 this.anchorEdge
= edge
;
4982 if ( this.anchored
) {
4983 this.$element
.addClass( 'oo-ui-popupWidget-anchored-' + edge
);
4988 * Check if the anchor is visible.
4990 * @return {boolean} Anchor is visible
4992 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
4993 return this.anchored
;
4997 * Toggle visibility of the popup. The popup is initially hidden and must be shown by calling
4998 * `.toggle( true )` after its #$element is attached to the DOM.
5000 * Do not show the popup while it is not attached to the DOM. The calculations required to display
5001 * it in the right place and with the right dimensions only work correctly while it is attached.
5002 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
5003 * strictly enforced, so currently it only generates a warning in the browser console.
5008 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
5010 show
= show
=== undefined ? !this.isVisible() : !!show
;
5012 change
= show
!== this.isVisible();
5014 if ( show
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
5015 OO
.ui
.warnDeprecation( 'PopupWidget#toggle: Before calling this method, the popup must be attached to the DOM.' );
5016 this.warnedUnattached
= true;
5018 if ( show
&& !this.$floatableContainer
&& this.isElementAttached() ) {
5019 // Fall back to the parent node if the floatableContainer is not set
5020 this.setFloatableContainer( this.$element
.parent() );
5024 OO
.ui
.PopupWidget
.parent
.prototype.toggle
.call( this, show
);
5027 this.togglePositioning( show
&& !!this.$floatableContainer
);
5030 if ( this.autoClose
) {
5031 this.bindMouseDownListener();
5032 this.bindKeyDownListener();
5034 this.updateDimensions();
5035 this.toggleClipping( true );
5036 this.emit( 'ready' );
5038 this.toggleClipping( false );
5039 if ( this.autoClose
) {
5040 this.unbindMouseDownListener();
5041 this.unbindKeyDownListener();
5050 * Set the size of the popup.
5052 * Changing the size may also change the popup's position depending on the alignment.
5054 * @param {number} width Width in pixels
5055 * @param {number} height Height in pixels
5056 * @param {boolean} [transition=false] Use a smooth transition
5059 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
5061 this.height
= height
!== undefined ? height
: null;
5062 if ( this.isVisible() ) {
5063 this.updateDimensions( transition
);
5068 * Update the size and position.
5070 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
5071 * be called automatically.
5073 * @param {boolean} [transition=false] Use a smooth transition
5076 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
5079 // Prevent transition from being interrupted
5080 clearTimeout( this.transitionTimeout
);
5082 // Enable transition
5083 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
5089 // Prevent transitioning after transition is complete
5090 this.transitionTimeout
= setTimeout( function () {
5091 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
5094 // Prevent transitioning immediately
5095 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
5102 OO
.ui
.PopupWidget
.prototype.computePosition = function () {
5103 var direction
, align
, vertical
, start
, end
, near
, far
, sizeProp
, popupSize
, anchorSize
, anchorPos
,
5104 anchorOffset
, anchorMargin
, parentPosition
, positionProp
, positionAdjustment
, floatablePos
,
5105 offsetParentPos
, containerPos
,
5107 anchorCss
= { left
: '', right
: '', top
: '', bottom
: '' },
5110 'force-left': 'backwards',
5111 'force-right': 'forwards'
5114 'force-left': 'forwards',
5115 'force-right': 'backwards'
5135 if ( !this.$container
) {
5136 // Lazy-initialize $container if not specified in constructor
5137 this.$container
= $( this.getClosestScrollableElementContainer() );
5139 direction
= this.$container
.css( 'direction' );
5141 // Set height and width before we do anything else, since it might cause our measurements
5142 // to change (e.g. due to scrollbars appearing or disappearing), and it also affects centering
5145 height
: this.height
!== null ? this.height
: 'auto'
5148 align
= alignMap
[ direction
][ this.align
] || this.align
;
5149 // If the popup is positioned before or after, then the anchor positioning is vertical, otherwise horizontal
5150 vertical
= this.popupPosition
=== 'before' || this.popupPosition
=== 'after';
5151 start
= vertical
? 'top' : ( direction
=== 'rtl' ? 'right' : 'left' );
5152 end
= vertical
? 'bottom' : ( direction
=== 'rtl' ? 'left' : 'right' );
5153 near
= vertical
? 'top' : 'left';
5154 far
= vertical
? 'bottom' : 'right';
5155 sizeProp
= vertical
? 'Height' : 'Width';
5156 popupSize
= vertical
? ( this.height
|| this.$popup
.height() ) : this.width
;
5158 this.setAnchorEdge( anchorEdgeMap
[ this.popupPosition
] );
5159 this.horizontalPosition
= vertical
? this.popupPosition
: hPosMap
[ align
];
5160 this.verticalPosition
= vertical
? vPosMap
[ align
] : this.popupPosition
;
5163 parentPosition
= OO
.ui
.mixin
.FloatableElement
.prototype.computePosition
.call( this );
5164 // Find out which property FloatableElement used for positioning, and adjust that value
5165 positionProp
= vertical
?
5166 ( parentPosition
.top
!== '' ? 'top' : 'bottom' ) :
5167 ( parentPosition
.left
!== '' ? 'left' : 'right' );
5169 // Figure out where the near and far edges of the popup and $floatableContainer are
5170 floatablePos
= this.$floatableContainer
.offset();
5171 floatablePos
[ far
] = floatablePos
[ near
] + this.$floatableContainer
[ 'outer' + sizeProp
]();
5172 // Measure where the offsetParent is and compute our position based on that and parentPosition
5173 offsetParentPos
= this.$element
.offsetParent().offset();
5175 if ( positionProp
=== near
) {
5176 popupPos
[ near
] = offsetParentPos
[ near
] + parentPosition
[ near
];
5177 popupPos
[ far
] = popupPos
[ near
] + popupSize
;
5179 popupPos
[ far
] = offsetParentPos
[ near
] +
5180 this.$element
.offsetParent()[ 'inner' + sizeProp
]() - parentPosition
[ far
];
5181 popupPos
[ near
] = popupPos
[ far
] - popupSize
;
5184 // Position the anchor (which is positioned relative to the popup) to point to $floatableContainer
5185 anchorPos
= ( floatablePos
[ start
] + floatablePos
[ end
] ) / 2;
5186 anchorOffset
= ( start
=== far
? -1 : 1 ) * ( anchorPos
- popupPos
[ start
] );
5188 // If the anchor is less than 2*anchorSize from either edge, move the popup to make more space
5189 // this.$anchor.width()/height() returns 0 because of the CSS trickery we use, so use scrollWidth/Height
5190 anchorSize
= this.$anchor
[ 0 ][ 'scroll' + sizeProp
];
5191 anchorMargin
= parseFloat( this.$anchor
.css( 'margin-' + start
) );
5192 if ( anchorOffset
+ anchorMargin
< 2 * anchorSize
) {
5193 // Not enough space for the anchor on the start side; pull the popup startwards
5194 positionAdjustment
= ( positionProp
=== start
? -1 : 1 ) *
5195 ( 2 * anchorSize
- ( anchorOffset
+ anchorMargin
) );
5196 } else if ( anchorOffset
+ anchorMargin
> popupSize
- 2 * anchorSize
) {
5197 // Not enough space for the anchor on the end side; pull the popup endwards
5198 positionAdjustment
= ( positionProp
=== end
? -1 : 1 ) *
5199 ( anchorOffset
+ anchorMargin
- ( popupSize
- 2 * anchorSize
) );
5201 positionAdjustment
= 0;
5204 // Check if the popup will go beyond the edge of this.$container
5205 containerPos
= this.$container
.offset();
5206 containerPos
[ far
] = containerPos
[ near
] + this.$container
[ 'inner' + sizeProp
]();
5207 // Take into account how much the popup will move because of the adjustments we're going to make
5208 popupPos
[ near
] += ( positionProp
=== near
? 1 : -1 ) * positionAdjustment
;
5209 popupPos
[ far
] += ( positionProp
=== near
? 1 : -1 ) * positionAdjustment
;
5210 if ( containerPos
[ near
] + this.containerPadding
> popupPos
[ near
] ) {
5211 // Popup goes beyond the near (left/top) edge, move it to the right/bottom
5212 positionAdjustment
+= ( positionProp
=== near
? 1 : -1 ) *
5213 ( containerPos
[ near
] + this.containerPadding
- popupPos
[ near
] );
5214 } else if ( containerPos
[ far
] - this.containerPadding
< popupPos
[ far
] ) {
5215 // Popup goes beyond the far (right/bottom) edge, move it to the left/top
5216 positionAdjustment
+= ( positionProp
=== far
? 1 : -1 ) *
5217 ( popupPos
[ far
] - ( containerPos
[ far
] - this.containerPadding
) );
5220 // Adjust anchorOffset for positionAdjustment
5221 anchorOffset
+= ( positionProp
=== start
? -1 : 1 ) * positionAdjustment
;
5223 // Position the anchor
5224 anchorCss
[ start
] = anchorOffset
;
5225 this.$anchor
.css( anchorCss
);
5226 // Move the popup if needed
5227 parentPosition
[ positionProp
] += positionAdjustment
;
5229 return parentPosition
;
5233 * Set popup alignment
5235 * @param {string} [align=center] Alignment of the popup, `center`, `force-left`, `force-right`,
5236 * `backwards` or `forwards`.
5238 OO
.ui
.PopupWidget
.prototype.setAlignment = function ( align
) {
5239 // Validate alignment
5240 if ( [ 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align
) > -1 ) {
5243 this.align
= 'center';
5249 * Get popup alignment
5251 * @return {string} Alignment of the popup, `center`, `force-left`, `force-right`,
5252 * `backwards` or `forwards`.
5254 OO
.ui
.PopupWidget
.prototype.getAlignment = function () {
5259 * Change the positioning of the popup.
5261 * @param {string} position 'above', 'below', 'before' or 'after'
5263 OO
.ui
.PopupWidget
.prototype.setPosition = function ( position
) {
5264 if ( [ 'above', 'below', 'before', 'after' ].indexOf( position
) === -1 ) {
5267 this.popupPosition
= position
;
5272 * Get popup positioning.
5274 * @return {string} 'above', 'below', 'before' or 'after'
5276 OO
.ui
.PopupWidget
.prototype.getPosition = function () {
5277 return this.popupPosition
;
5281 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5282 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5283 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5284 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5290 * @param {Object} [config] Configuration options
5291 * @cfg {Object} [popup] Configuration to pass to popup
5292 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5294 OO
.ui
.mixin
.PopupElement
= function OoUiMixinPopupElement( config
) {
5295 // Configuration initialization
5296 config
= config
|| {};
5299 this.popup
= new OO
.ui
.PopupWidget( $.extend(
5302 $floatableContainer
: this.$element
5306 $autoCloseIgnore
: this.$element
.add( config
.popup
&& config
.popup
.$autoCloseIgnore
)
5316 * @return {OO.ui.PopupWidget} Popup widget
5318 OO
.ui
.mixin
.PopupElement
.prototype.getPopup = function () {
5323 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
5324 * which is used to display additional information or options.
5327 * // Example of a popup button.
5328 * var popupButton = new OO.ui.PopupButtonWidget( {
5329 * label: 'Popup button with options',
5332 * $content: $( '<p>Additional options here.</p>' ),
5334 * align: 'force-left'
5337 * // Append the button to the DOM.
5338 * $( 'body' ).append( popupButton.$element );
5341 * @extends OO.ui.ButtonWidget
5342 * @mixins OO.ui.mixin.PopupElement
5345 * @param {Object} [config] Configuration options
5346 * @cfg {jQuery} [$overlay] Render the popup into a separate layer. This configuration is useful in cases where
5347 * the expanded popup is larger than its containing `<div>`. The specified overlay layer is usually on top of the
5348 * containing `<div>` and has a larger area. By default, the popup uses relative positioning.
5349 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
5351 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
5352 // Parent constructor
5353 OO
.ui
.PopupButtonWidget
.parent
.call( this, config
);
5355 // Mixin constructors
5356 OO
.ui
.mixin
.PopupElement
.call( this, config
);
5359 this.$overlay
= config
.$overlay
|| this.$element
;
5362 this.connect( this, { click
: 'onAction' } );
5366 .addClass( 'oo-ui-popupButtonWidget' )
5367 .attr( 'aria-haspopup', 'true' );
5369 .addClass( 'oo-ui-popupButtonWidget-popup' )
5370 .toggleClass( 'oo-ui-popupButtonWidget-framed-popup', this.isFramed() )
5371 .toggleClass( 'oo-ui-popupButtonWidget-frameless-popup', !this.isFramed() );
5372 this.$overlay
.append( this.popup
.$element
);
5377 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
5378 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.mixin
.PopupElement
);
5383 * Handle the button action being triggered.
5387 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
5388 this.popup
.toggle();
5392 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
5394 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
5399 * @mixins OO.ui.mixin.GroupElement
5402 * @param {Object} [config] Configuration options
5404 OO
.ui
.mixin
.GroupWidget
= function OoUiMixinGroupWidget( config
) {
5405 // Mixin constructors
5406 OO
.ui
.mixin
.GroupElement
.call( this, config
);
5411 OO
.mixinClass( OO
.ui
.mixin
.GroupWidget
, OO
.ui
.mixin
.GroupElement
);
5416 * Set the disabled state of the widget.
5418 * This will also update the disabled state of child widgets.
5420 * @param {boolean} disabled Disable widget
5423 OO
.ui
.mixin
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
5427 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
5428 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
5430 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
5432 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5433 this.items
[ i
].updateDisabled();
5441 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
5443 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
5444 * allows bidirectional communication.
5446 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
5454 OO
.ui
.mixin
.ItemWidget
= function OoUiMixinItemWidget() {
5461 * Check if widget is disabled.
5463 * Checks parent if present, making disabled state inheritable.
5465 * @return {boolean} Widget is disabled
5467 OO
.ui
.mixin
.ItemWidget
.prototype.isDisabled = function () {
5468 return this.disabled
||
5469 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
5473 * Set group element is in.
5475 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
5478 OO
.ui
.mixin
.ItemWidget
.prototype.setElementGroup = function ( group
) {
5480 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
5481 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
5483 // Initialize item disabled states
5484 this.updateDisabled();
5490 * OptionWidgets are special elements that can be selected and configured with data. The
5491 * data is often unique for each option, but it does not have to be. OptionWidgets are used
5492 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
5493 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
5495 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5498 * @extends OO.ui.Widget
5499 * @mixins OO.ui.mixin.ItemWidget
5500 * @mixins OO.ui.mixin.LabelElement
5501 * @mixins OO.ui.mixin.FlaggedElement
5502 * @mixins OO.ui.mixin.AccessKeyedElement
5505 * @param {Object} [config] Configuration options
5507 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
5508 // Configuration initialization
5509 config
= config
|| {};
5511 // Parent constructor
5512 OO
.ui
.OptionWidget
.parent
.call( this, config
);
5514 // Mixin constructors
5515 OO
.ui
.mixin
.ItemWidget
.call( this );
5516 OO
.ui
.mixin
.LabelElement
.call( this, config
);
5517 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
5518 OO
.ui
.mixin
.AccessKeyedElement
.call( this, config
);
5521 this.selected
= false;
5522 this.highlighted
= false;
5523 this.pressed
= false;
5527 .data( 'oo-ui-optionWidget', this )
5528 // Allow programmatic focussing (and by accesskey), but not tabbing
5529 .attr( 'tabindex', '-1' )
5530 .attr( 'role', 'option' )
5531 .attr( 'aria-selected', 'false' )
5532 .addClass( 'oo-ui-optionWidget' )
5533 .append( this.$label
);
5538 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
5539 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.ItemWidget
);
5540 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.LabelElement
);
5541 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.FlaggedElement
);
5542 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
5544 /* Static Properties */
5547 * Whether this option can be selected. See #setSelected.
5551 * @property {boolean}
5553 OO
.ui
.OptionWidget
.static.selectable
= true;
5556 * Whether this option can be highlighted. See #setHighlighted.
5560 * @property {boolean}
5562 OO
.ui
.OptionWidget
.static.highlightable
= true;
5565 * Whether this option can be pressed. See #setPressed.
5569 * @property {boolean}
5571 OO
.ui
.OptionWidget
.static.pressable
= true;
5574 * Whether this option will be scrolled into view when it is selected.
5578 * @property {boolean}
5580 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
5585 * Check if the option can be selected.
5587 * @return {boolean} Item is selectable
5589 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
5590 return this.constructor.static.selectable
&& !this.isDisabled() && this.isVisible();
5594 * Check if the option can be highlighted. A highlight indicates that the option
5595 * may be selected when a user presses enter or clicks. Disabled items cannot
5598 * @return {boolean} Item is highlightable
5600 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
5601 return this.constructor.static.highlightable
&& !this.isDisabled() && this.isVisible();
5605 * Check if the option can be pressed. The pressed state occurs when a user mouses
5606 * down on an item, but has not yet let go of the mouse.
5608 * @return {boolean} Item is pressable
5610 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
5611 return this.constructor.static.pressable
&& !this.isDisabled() && this.isVisible();
5615 * Check if the option is selected.
5617 * @return {boolean} Item is selected
5619 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
5620 return this.selected
;
5624 * Check if the option is highlighted. A highlight indicates that the
5625 * item may be selected when a user presses enter or clicks.
5627 * @return {boolean} Item is highlighted
5629 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
5630 return this.highlighted
;
5634 * Check if the option is pressed. The pressed state occurs when a user mouses
5635 * down on an item, but has not yet let go of the mouse. The item may appear
5636 * selected, but it will not be selected until the user releases the mouse.
5638 * @return {boolean} Item is pressed
5640 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
5641 return this.pressed
;
5645 * Set the option’s selected state. In general, all modifications to the selection
5646 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
5647 * method instead of this method.
5649 * @param {boolean} [state=false] Select option
5652 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
5653 if ( this.constructor.static.selectable
) {
5654 this.selected
= !!state
;
5656 .toggleClass( 'oo-ui-optionWidget-selected', state
)
5657 .attr( 'aria-selected', state
.toString() );
5658 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
5659 this.scrollElementIntoView();
5661 this.updateThemeClasses();
5667 * Set the option’s highlighted state. In general, all programmatic
5668 * modifications to the highlight should be handled by the
5669 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
5670 * method instead of this method.
5672 * @param {boolean} [state=false] Highlight option
5675 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
5676 if ( this.constructor.static.highlightable
) {
5677 this.highlighted
= !!state
;
5678 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
5679 this.updateThemeClasses();
5685 * Set the option’s pressed state. In general, all
5686 * programmatic modifications to the pressed state should be handled by the
5687 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
5688 * method instead of this method.
5690 * @param {boolean} [state=false] Press option
5693 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
5694 if ( this.constructor.static.pressable
) {
5695 this.pressed
= !!state
;
5696 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
5697 this.updateThemeClasses();
5703 * Get text to match search strings against.
5705 * The default implementation returns the label text, but subclasses
5706 * can override this to provide more complex behavior.
5708 * @return {string|boolean} String to match search string against
5710 OO
.ui
.OptionWidget
.prototype.getMatchText = function () {
5711 var label
= this.getLabel();
5712 return typeof label
=== 'string' ? label
: this.$label
.text();
5716 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
5717 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
5718 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
5721 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
5722 * information, please see the [OOjs UI documentation on MediaWiki][1].
5725 * // Example of a select widget with three options
5726 * var select = new OO.ui.SelectWidget( {
5728 * new OO.ui.OptionWidget( {
5730 * label: 'Option One',
5732 * new OO.ui.OptionWidget( {
5734 * label: 'Option Two',
5736 * new OO.ui.OptionWidget( {
5738 * label: 'Option Three',
5742 * $( 'body' ).append( select.$element );
5744 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5748 * @extends OO.ui.Widget
5749 * @mixins OO.ui.mixin.GroupWidget
5752 * @param {Object} [config] Configuration options
5753 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
5754 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
5755 * the [OOjs UI documentation on MediaWiki] [2] for examples.
5756 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5758 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
5759 // Configuration initialization
5760 config
= config
|| {};
5762 // Parent constructor
5763 OO
.ui
.SelectWidget
.parent
.call( this, config
);
5765 // Mixin constructors
5766 OO
.ui
.mixin
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
5769 this.pressed
= false;
5770 this.selecting
= null;
5771 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
5772 this.onMouseMoveHandler
= this.onMouseMove
.bind( this );
5773 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
5774 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
5775 this.keyPressBuffer
= '';
5776 this.keyPressBufferTimer
= null;
5777 this.blockMouseOverEvents
= 0;
5780 this.connect( this, {
5784 focusin
: this.onFocus
.bind( this ),
5785 mousedown
: this.onMouseDown
.bind( this ),
5786 mouseover
: this.onMouseOver
.bind( this ),
5787 mouseleave
: this.onMouseLeave
.bind( this )
5792 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
5793 .attr( 'role', 'listbox' );
5794 this.setFocusOwner( this.$element
);
5795 if ( Array
.isArray( config
.items
) ) {
5796 this.addItems( config
.items
);
5802 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
5803 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupWidget
);
5810 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
5812 * @param {OO.ui.OptionWidget|null} item Highlighted item
5818 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
5819 * pressed state of an option.
5821 * @param {OO.ui.OptionWidget|null} item Pressed item
5827 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
5829 * @param {OO.ui.OptionWidget|null} item Selected item
5834 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
5835 * @param {OO.ui.OptionWidget} item Chosen item
5841 * An `add` event is emitted when options are added to the select with the #addItems method.
5843 * @param {OO.ui.OptionWidget[]} items Added items
5844 * @param {number} index Index of insertion point
5850 * A `remove` event is emitted when options are removed from the select with the #clearItems
5851 * or #removeItems methods.
5853 * @param {OO.ui.OptionWidget[]} items Removed items
5859 * Handle focus events
5862 * @param {jQuery.Event} event
5864 OO
.ui
.SelectWidget
.prototype.onFocus = function ( event
) {
5866 if ( event
.target
=== this.$element
[ 0 ] ) {
5867 // This widget was focussed, e.g. by the user tabbing to it.
5868 // The styles for focus state depend on one of the items being selected.
5869 if ( !this.getSelectedItem() ) {
5870 item
= this.getFirstSelectableItem();
5873 // One of the options got focussed (and the event bubbled up here).
5874 // They can't be tabbed to, but they can be activated using accesskeys.
5875 item
= this.getTargetItem( event
);
5879 if ( item
.constructor.static.highlightable
) {
5880 this.highlightItem( item
);
5882 this.selectItem( item
);
5886 if ( event
.target
!== this.$element
[ 0 ] ) {
5887 this.$focusOwner
.focus();
5892 * Handle mouse down events.
5895 * @param {jQuery.Event} e Mouse down event
5897 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
5900 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
5901 this.togglePressed( true );
5902 item
= this.getTargetItem( e
);
5903 if ( item
&& item
.isSelectable() ) {
5904 this.pressItem( item
);
5905 this.selecting
= item
;
5906 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
5907 this.getElementDocument().addEventListener( 'mousemove', this.onMouseMoveHandler
, true );
5914 * Handle mouse up events.
5917 * @param {MouseEvent} e Mouse up event
5919 OO
.ui
.SelectWidget
.prototype.onMouseUp = function ( e
) {
5922 this.togglePressed( false );
5923 if ( !this.selecting
) {
5924 item
= this.getTargetItem( e
);
5925 if ( item
&& item
.isSelectable() ) {
5926 this.selecting
= item
;
5929 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
&& this.selecting
) {
5930 this.pressItem( null );
5931 this.chooseItem( this.selecting
);
5932 this.selecting
= null;
5935 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
5936 this.getElementDocument().removeEventListener( 'mousemove', this.onMouseMoveHandler
, true );
5942 * Handle mouse move events.
5945 * @param {MouseEvent} e Mouse move event
5947 OO
.ui
.SelectWidget
.prototype.onMouseMove = function ( e
) {
5950 if ( !this.isDisabled() && this.pressed
) {
5951 item
= this.getTargetItem( e
);
5952 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
5953 this.pressItem( item
);
5954 this.selecting
= item
;
5960 * Handle mouse over events.
5963 * @param {jQuery.Event} e Mouse over event
5965 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
5967 if ( this.blockMouseOverEvents
) {
5970 if ( !this.isDisabled() ) {
5971 item
= this.getTargetItem( e
);
5972 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
5978 * Handle mouse leave events.
5981 * @param {jQuery.Event} e Mouse over event
5983 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
5984 if ( !this.isDisabled() ) {
5985 this.highlightItem( null );
5991 * Handle key down events.
5994 * @param {KeyboardEvent} e Key down event
5996 OO
.ui
.SelectWidget
.prototype.onKeyDown = function ( e
) {
5999 currentItem
= this.getHighlightedItem() || this.getSelectedItem();
6001 if ( !this.isDisabled() && this.isVisible() ) {
6002 switch ( e
.keyCode
) {
6003 case OO
.ui
.Keys
.ENTER
:
6004 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
6005 // Was only highlighted, now let's select it. No-op if already selected.
6006 this.chooseItem( currentItem
);
6011 case OO
.ui
.Keys
.LEFT
:
6012 this.clearKeyPressBuffer();
6013 nextItem
= this.getRelativeSelectableItem( currentItem
, -1 );
6016 case OO
.ui
.Keys
.DOWN
:
6017 case OO
.ui
.Keys
.RIGHT
:
6018 this.clearKeyPressBuffer();
6019 nextItem
= this.getRelativeSelectableItem( currentItem
, 1 );
6022 case OO
.ui
.Keys
.ESCAPE
:
6023 case OO
.ui
.Keys
.TAB
:
6024 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
6025 currentItem
.setHighlighted( false );
6027 this.unbindKeyDownListener();
6028 this.unbindKeyPressListener();
6029 // Don't prevent tabbing away / defocusing
6035 if ( nextItem
.constructor.static.highlightable
) {
6036 this.highlightItem( nextItem
);
6038 this.chooseItem( nextItem
);
6040 this.scrollItemIntoView( nextItem
);
6045 e
.stopPropagation();
6051 * Bind key down listener.
6055 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
6056 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler
, true );
6060 * Unbind key down listener.
6064 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
6065 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler
, true );
6069 * Scroll item into view, preventing spurious mouse highlight actions from happening.
6071 * @param {OO.ui.OptionWidget} item Item to scroll into view
6073 OO
.ui
.SelectWidget
.prototype.scrollItemIntoView = function ( item
) {
6075 // Chromium's Blink engine will generate spurious 'mouseover' events during programmatic scrolling
6076 // and around 100-150 ms after it is finished.
6077 this.blockMouseOverEvents
++;
6078 item
.scrollElementIntoView().done( function () {
6079 setTimeout( function () {
6080 widget
.blockMouseOverEvents
--;
6086 * Clear the key-press buffer
6090 OO
.ui
.SelectWidget
.prototype.clearKeyPressBuffer = function () {
6091 if ( this.keyPressBufferTimer
) {
6092 clearTimeout( this.keyPressBufferTimer
);
6093 this.keyPressBufferTimer
= null;
6095 this.keyPressBuffer
= '';
6099 * Handle key press events.
6102 * @param {KeyboardEvent} e Key press event
6104 OO
.ui
.SelectWidget
.prototype.onKeyPress = function ( e
) {
6105 var c
, filter
, item
;
6107 if ( !e
.charCode
) {
6108 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.keyPressBuffer
!== '' ) {
6109 this.keyPressBuffer
= this.keyPressBuffer
.substr( 0, this.keyPressBuffer
.length
- 1 );
6114 if ( String
.fromCodePoint
) {
6115 c
= String
.fromCodePoint( e
.charCode
);
6117 c
= String
.fromCharCode( e
.charCode
);
6120 if ( this.keyPressBufferTimer
) {
6121 clearTimeout( this.keyPressBufferTimer
);
6123 this.keyPressBufferTimer
= setTimeout( this.clearKeyPressBuffer
.bind( this ), 1500 );
6125 item
= this.getHighlightedItem() || this.getSelectedItem();
6127 if ( this.keyPressBuffer
=== c
) {
6128 // Common (if weird) special case: typing "xxxx" will cycle through all
6129 // the items beginning with "x".
6131 item
= this.getRelativeSelectableItem( item
, 1 );
6134 this.keyPressBuffer
+= c
;
6137 filter
= this.getItemMatcher( this.keyPressBuffer
, false );
6138 if ( !item
|| !filter( item
) ) {
6139 item
= this.getRelativeSelectableItem( item
, 1, filter
);
6142 if ( this.isVisible() && item
.constructor.static.highlightable
) {
6143 this.highlightItem( item
);
6145 this.chooseItem( item
);
6147 this.scrollItemIntoView( item
);
6151 e
.stopPropagation();
6155 * Get a matcher for the specific string
6158 * @param {string} s String to match against items
6159 * @param {boolean} [exact=false] Only accept exact matches
6160 * @return {Function} function ( OO.ui.OptionWidget ) => boolean
6162 OO
.ui
.SelectWidget
.prototype.getItemMatcher = function ( s
, exact
) {
6165 if ( s
.normalize
) {
6168 s
= exact
? s
.trim() : s
.replace( /^\s+/, '' );
6169 re
= '^\\s*' + s
.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
6173 re
= new RegExp( re
, 'i' );
6174 return function ( item
) {
6175 var matchText
= item
.getMatchText();
6176 if ( matchText
.normalize
) {
6177 matchText
= matchText
.normalize();
6179 return re
.test( matchText
);
6184 * Bind key press listener.
6188 OO
.ui
.SelectWidget
.prototype.bindKeyPressListener = function () {
6189 this.getElementWindow().addEventListener( 'keypress', this.onKeyPressHandler
, true );
6193 * Unbind key down listener.
6195 * If you override this, be sure to call this.clearKeyPressBuffer() from your
6200 OO
.ui
.SelectWidget
.prototype.unbindKeyPressListener = function () {
6201 this.getElementWindow().removeEventListener( 'keypress', this.onKeyPressHandler
, true );
6202 this.clearKeyPressBuffer();
6206 * Visibility change handler
6209 * @param {boolean} visible
6211 OO
.ui
.SelectWidget
.prototype.onToggle = function ( visible
) {
6213 this.clearKeyPressBuffer();
6218 * Get the closest item to a jQuery.Event.
6221 * @param {jQuery.Event} e
6222 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
6224 OO
.ui
.SelectWidget
.prototype.getTargetItem = function ( e
) {
6225 return $( e
.target
).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
6229 * Get selected item.
6231 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
6233 OO
.ui
.SelectWidget
.prototype.getSelectedItem = function () {
6236 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6237 if ( this.items
[ i
].isSelected() ) {
6238 return this.items
[ i
];
6245 * Get highlighted item.
6247 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
6249 OO
.ui
.SelectWidget
.prototype.getHighlightedItem = function () {
6252 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6253 if ( this.items
[ i
].isHighlighted() ) {
6254 return this.items
[ i
];
6261 * Toggle pressed state.
6263 * Press is a state that occurs when a user mouses down on an item, but
6264 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
6265 * until the user releases the mouse.
6267 * @param {boolean} pressed An option is being pressed
6269 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
6270 if ( pressed
=== undefined ) {
6271 pressed
= !this.pressed
;
6273 if ( pressed
!== this.pressed
) {
6275 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
6276 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
6277 this.pressed
= pressed
;
6282 * Highlight an option. If the `item` param is omitted, no options will be highlighted
6283 * and any existing highlight will be removed. The highlight is mutually exclusive.
6285 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
6289 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
6290 var i
, len
, highlighted
,
6293 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6294 highlighted
= this.items
[ i
] === item
;
6295 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
6296 this.items
[ i
].setHighlighted( highlighted
);
6302 this.$focusOwner
.attr( 'aria-activedescendant', item
.getElementId() );
6304 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
6306 this.emit( 'highlight', item
);
6313 * Fetch an item by its label.
6315 * @param {string} label Label of the item to select.
6316 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
6317 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
6319 OO
.ui
.SelectWidget
.prototype.getItemFromLabel = function ( label
, prefix
) {
6321 len
= this.items
.length
,
6322 filter
= this.getItemMatcher( label
, true );
6324 for ( i
= 0; i
< len
; i
++ ) {
6325 item
= this.items
[ i
];
6326 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
6333 filter
= this.getItemMatcher( label
, false );
6334 for ( i
= 0; i
< len
; i
++ ) {
6335 item
= this.items
[ i
];
6336 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
6352 * Programmatically select an option by its label. If the item does not exist,
6353 * all options will be deselected.
6355 * @param {string} [label] Label of the item to select.
6356 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
6360 OO
.ui
.SelectWidget
.prototype.selectItemByLabel = function ( label
, prefix
) {
6361 var itemFromLabel
= this.getItemFromLabel( label
, !!prefix
);
6362 if ( label
=== undefined || !itemFromLabel
) {
6363 return this.selectItem();
6365 return this.selectItem( itemFromLabel
);
6369 * Programmatically select an option by its data. If the `data` parameter is omitted,
6370 * or if the item does not exist, all options will be deselected.
6372 * @param {Object|string} [data] Value of the item to select, omit to deselect all
6376 OO
.ui
.SelectWidget
.prototype.selectItemByData = function ( data
) {
6377 var itemFromData
= this.getItemFromData( data
);
6378 if ( data
=== undefined || !itemFromData
) {
6379 return this.selectItem();
6381 return this.selectItem( itemFromData
);
6385 * Programmatically select an option by its reference. If the `item` parameter is omitted,
6386 * all options will be deselected.
6388 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
6392 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
6393 var i
, len
, selected
,
6396 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6397 selected
= this.items
[ i
] === item
;
6398 if ( this.items
[ i
].isSelected() !== selected
) {
6399 this.items
[ i
].setSelected( selected
);
6404 if ( item
&& !item
.constructor.static.highlightable
) {
6406 this.$focusOwner
.attr( 'aria-activedescendant', item
.getElementId() );
6408 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
6411 this.emit( 'select', item
);
6420 * Press is a state that occurs when a user mouses down on an item, but has not
6421 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
6422 * releases the mouse.
6424 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
6428 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
6429 var i
, len
, pressed
,
6432 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6433 pressed
= this.items
[ i
] === item
;
6434 if ( this.items
[ i
].isPressed() !== pressed
) {
6435 this.items
[ i
].setPressed( pressed
);
6440 this.emit( 'press', item
);
6449 * Note that ‘choose’ should never be modified programmatically. A user can choose
6450 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
6451 * use the #selectItem method.
6453 * This method is identical to #selectItem, but may vary in subclasses that take additional action
6454 * when users choose an item with the keyboard or mouse.
6456 * @param {OO.ui.OptionWidget} item Item to choose
6460 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
6462 this.selectItem( item
);
6463 this.emit( 'choose', item
);
6470 * Get an option by its position relative to the specified item (or to the start of the option array,
6471 * if item is `null`). The direction in which to search through the option array is specified with a
6472 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
6473 * `null` if there are no options in the array.
6475 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
6476 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
6477 * @param {Function} [filter] Only consider items for which this function returns
6478 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
6479 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
6481 OO
.ui
.SelectWidget
.prototype.getRelativeSelectableItem = function ( item
, direction
, filter
) {
6482 var currentIndex
, nextIndex
, i
,
6483 increase
= direction
> 0 ? 1 : -1,
6484 len
= this.items
.length
;
6486 if ( item
instanceof OO
.ui
.OptionWidget
) {
6487 currentIndex
= this.items
.indexOf( item
);
6488 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
6490 // If no item is selected and moving forward, start at the beginning.
6491 // If moving backward, start at the end.
6492 nextIndex
= direction
> 0 ? 0 : len
- 1;
6495 for ( i
= 0; i
< len
; i
++ ) {
6496 item
= this.items
[ nextIndex
];
6498 item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() &&
6499 ( !filter
|| filter( item
) )
6503 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
6509 * Get the next selectable item or `null` if there are no selectable items.
6510 * Disabled options and menu-section markers and breaks are not selectable.
6512 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
6514 OO
.ui
.SelectWidget
.prototype.getFirstSelectableItem = function () {
6515 return this.getRelativeSelectableItem( null, 1 );
6519 * Add an array of options to the select. Optionally, an index number can be used to
6520 * specify an insertion point.
6522 * @param {OO.ui.OptionWidget[]} items Items to add
6523 * @param {number} [index] Index to insert items after
6527 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
6529 OO
.ui
.mixin
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
6531 // Always provide an index, even if it was omitted
6532 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
6538 * Remove the specified array of options from the select. Options will be detached
6539 * from the DOM, not removed, so they can be reused later. To remove all options from
6540 * the select, you may wish to use the #clearItems method instead.
6542 * @param {OO.ui.OptionWidget[]} items Items to remove
6546 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
6549 // Deselect items being removed
6550 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
6552 if ( item
.isSelected() ) {
6553 this.selectItem( null );
6558 OO
.ui
.mixin
.GroupWidget
.prototype.removeItems
.call( this, items
);
6560 this.emit( 'remove', items
);
6566 * Clear all options from the select. Options will be detached from the DOM, not removed,
6567 * so that they can be reused later. To remove a subset of options from the select, use
6568 * the #removeItems method.
6573 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
6574 var items
= this.items
.slice();
6577 OO
.ui
.mixin
.GroupWidget
.prototype.clearItems
.call( this );
6580 this.selectItem( null );
6582 this.emit( 'remove', items
);
6588 * Set the DOM element which has focus while the user is interacting with this SelectWidget.
6590 * Currently this is just used to set `aria-activedescendant` on it.
6593 * @param {jQuery} $focusOwner
6595 OO
.ui
.SelectWidget
.prototype.setFocusOwner = function ( $focusOwner
) {
6596 this.$focusOwner
= $focusOwner
;
6600 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
6601 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
6602 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
6603 * options. For more information about options and selects, please see the
6604 * [OOjs UI documentation on MediaWiki][1].
6607 * // Decorated options in a select widget
6608 * var select = new OO.ui.SelectWidget( {
6610 * new OO.ui.DecoratedOptionWidget( {
6612 * label: 'Option with icon',
6615 * new OO.ui.DecoratedOptionWidget( {
6617 * label: 'Option with indicator',
6622 * $( 'body' ).append( select.$element );
6624 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
6627 * @extends OO.ui.OptionWidget
6628 * @mixins OO.ui.mixin.IconElement
6629 * @mixins OO.ui.mixin.IndicatorElement
6632 * @param {Object} [config] Configuration options
6634 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
6635 // Parent constructor
6636 OO
.ui
.DecoratedOptionWidget
.parent
.call( this, config
);
6638 // Mixin constructors
6639 OO
.ui
.mixin
.IconElement
.call( this, config
);
6640 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
6644 .addClass( 'oo-ui-decoratedOptionWidget' )
6645 .prepend( this.$icon
)
6646 .append( this.$indicator
);
6651 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
6652 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IconElement
);
6653 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IndicatorElement
);
6656 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
6657 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
6658 * the [OOjs UI documentation on MediaWiki] [1] for more information.
6660 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
6663 * @extends OO.ui.DecoratedOptionWidget
6666 * @param {Object} [config] Configuration options
6668 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
6669 // Parent constructor
6670 OO
.ui
.MenuOptionWidget
.parent
.call( this, config
);
6673 this.$element
.addClass( 'oo-ui-menuOptionWidget' );
6678 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
6680 /* Static Properties */
6686 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
6689 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
6690 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
6693 * var myDropdown = new OO.ui.DropdownWidget( {
6696 * new OO.ui.MenuSectionOptionWidget( {
6699 * new OO.ui.MenuOptionWidget( {
6701 * label: 'Welsh Corgi'
6703 * new OO.ui.MenuOptionWidget( {
6705 * label: 'Standard Poodle'
6707 * new OO.ui.MenuSectionOptionWidget( {
6710 * new OO.ui.MenuOptionWidget( {
6717 * $( 'body' ).append( myDropdown.$element );
6720 * @extends OO.ui.DecoratedOptionWidget
6723 * @param {Object} [config] Configuration options
6725 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
6726 // Parent constructor
6727 OO
.ui
.MenuSectionOptionWidget
.parent
.call( this, config
);
6730 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' )
6731 .removeAttr( 'role aria-selected' );
6736 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
6738 /* Static Properties */
6744 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
6750 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
6753 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
6754 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
6755 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
6756 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
6757 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
6758 * and customized to be opened, closed, and displayed as needed.
6760 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
6761 * mouse outside the menu.
6763 * Menus also have support for keyboard interaction:
6765 * - Enter/Return key: choose and select a menu option
6766 * - Up-arrow key: highlight the previous menu option
6767 * - Down-arrow key: highlight the next menu option
6768 * - Esc key: hide the menu
6770 * Unlike most widgets, MenuSelectWidget is initially hidden and must be shown by calling #toggle.
6772 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
6773 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
6776 * @extends OO.ui.SelectWidget
6777 * @mixins OO.ui.mixin.ClippableElement
6778 * @mixins OO.ui.mixin.FloatableElement
6781 * @param {Object} [config] Configuration options
6782 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
6783 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
6784 * and {@link OO.ui.mixin.LookupElement LookupElement}
6785 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
6786 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiselectWidget CapsuleMultiselectWidget}
6787 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
6788 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
6789 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
6790 * that button, unless the button (or its parent widget) is passed in here.
6791 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
6792 * @cfg {jQuery} [$autoCloseIgnore] If these elements are clicked, don't auto-hide the menu.
6793 * @cfg {boolean} [hideOnChoose=true] Hide the menu when the user chooses an option.
6794 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
6795 * @cfg {boolean} [highlightOnFilter] Highlight the first result when filtering
6796 * @cfg {number} [width] Width of the menu
6798 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
6799 // Configuration initialization
6800 config
= config
|| {};
6802 // Parent constructor
6803 OO
.ui
.MenuSelectWidget
.parent
.call( this, config
);
6805 // Mixin constructors
6806 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
6807 OO
.ui
.mixin
.FloatableElement
.call( this, config
);
6810 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
6811 this.hideOnChoose
= config
.hideOnChoose
=== undefined || !!config
.hideOnChoose
;
6812 this.filterFromInput
= !!config
.filterFromInput
;
6813 this.$input
= config
.$input
? config
.$input
: config
.input
? config
.input
.$input
: null;
6814 this.$widget
= config
.widget
? config
.widget
.$element
: null;
6815 this.$autoCloseIgnore
= config
.$autoCloseIgnore
|| $( [] );
6816 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
6817 this.onInputEditHandler
= OO
.ui
.debounce( this.updateItemVisibility
.bind( this ), 100 );
6818 this.highlightOnFilter
= !!config
.highlightOnFilter
;
6819 this.width
= config
.width
;
6822 this.$element
.addClass( 'oo-ui-menuSelectWidget' );
6823 if ( config
.widget
) {
6824 this.setFocusOwner( config
.widget
.$tabIndexed
);
6827 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
6828 // that reference properties not initialized at that time of parent class construction
6829 // TODO: Find a better way to handle post-constructor setup
6830 this.visible
= false;
6831 this.$element
.addClass( 'oo-ui-element-hidden' );
6836 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
6837 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.ClippableElement
);
6838 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.FloatableElement
);
6845 * The menu is ready: it is visible and has been positioned and clipped.
6851 * Handles document mouse down events.
6854 * @param {MouseEvent} e Mouse down event
6856 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
6860 this.$element
.add( this.$widget
).add( this.$autoCloseIgnore
).get(),
6865 this.toggle( false );
6872 OO
.ui
.MenuSelectWidget
.prototype.onKeyDown = function ( e
) {
6873 var currentItem
= this.getHighlightedItem() || this.getSelectedItem();
6875 if ( !this.isDisabled() && this.isVisible() ) {
6876 switch ( e
.keyCode
) {
6877 case OO
.ui
.Keys
.LEFT
:
6878 case OO
.ui
.Keys
.RIGHT
:
6879 // Do nothing if a text field is associated, arrow keys will be handled natively
6880 if ( !this.$input
) {
6881 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
6884 case OO
.ui
.Keys
.ESCAPE
:
6885 case OO
.ui
.Keys
.TAB
:
6886 if ( currentItem
) {
6887 currentItem
.setHighlighted( false );
6889 this.toggle( false );
6890 // Don't prevent tabbing away, prevent defocusing
6891 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
6893 e
.stopPropagation();
6897 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
6904 * Update menu item visibility after input changes.
6908 OO
.ui
.MenuSelectWidget
.prototype.updateItemVisibility = function () {
6909 var i
, item
, visible
, section
, sectionEmpty
,
6910 firstItemFound
= false,
6912 len
= this.items
.length
,
6913 showAll
= !this.isVisible(),
6914 filter
= showAll
? null : this.getItemMatcher( this.$input
.val() ),
6915 exactFilter
= this.getItemMatcher( this.$input
.val(), true ),
6918 // Hide non-matching options, and also hide section headers if all options
6919 // in their section are hidden.
6920 for ( i
= 0; i
< len
; i
++ ) {
6921 item
= this.items
[ i
];
6922 if ( item
instanceof OO
.ui
.MenuSectionOptionWidget
) {
6924 // If the previous section was empty, hide its header
6925 section
.toggle( showAll
|| !sectionEmpty
);
6928 sectionEmpty
= true;
6929 } else if ( item
instanceof OO
.ui
.OptionWidget
) {
6930 visible
= showAll
|| filter( item
);
6931 exactMatch
= exactMatch
|| exactFilter( item
);
6932 anyVisible
= anyVisible
|| visible
;
6933 sectionEmpty
= sectionEmpty
&& !visible
;
6934 item
.toggle( visible
);
6935 if ( this.highlightOnFilter
&& visible
&& !firstItemFound
) {
6936 // Highlight the first item in the list
6937 this.highlightItem( item
);
6938 firstItemFound
= true;
6942 // Process the final section
6944 section
.toggle( showAll
|| !sectionEmpty
);
6947 if ( anyVisible
&& this.items
.length
&& !exactMatch
) {
6948 this.scrollItemIntoView( this.items
[ 0 ] );
6951 this.$element
.toggleClass( 'oo-ui-menuSelectWidget-invisible', !anyVisible
);
6953 // Reevaluate clipping
6960 OO
.ui
.MenuSelectWidget
.prototype.bindKeyDownListener = function () {
6961 if ( this.$input
) {
6962 this.$input
.on( 'keydown', this.onKeyDownHandler
);
6964 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyDownListener
.call( this );
6971 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyDownListener = function () {
6972 if ( this.$input
) {
6973 this.$input
.off( 'keydown', this.onKeyDownHandler
);
6975 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyDownListener
.call( this );
6982 OO
.ui
.MenuSelectWidget
.prototype.bindKeyPressListener = function () {
6983 if ( this.$input
) {
6984 if ( this.filterFromInput
) {
6985 this.$input
.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
6986 this.updateItemVisibility();
6989 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyPressListener
.call( this );
6996 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyPressListener = function () {
6997 if ( this.$input
) {
6998 if ( this.filterFromInput
) {
6999 this.$input
.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
7000 this.updateItemVisibility();
7003 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyPressListener
.call( this );
7010 * When a user chooses an item, the menu is closed, unless the hideOnChoose config option is set to false.
7012 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
7013 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
7015 * @param {OO.ui.OptionWidget} item Item to choose
7018 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
7019 OO
.ui
.MenuSelectWidget
.parent
.prototype.chooseItem
.call( this, item
);
7020 if ( this.hideOnChoose
) {
7021 this.toggle( false );
7029 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
7031 OO
.ui
.MenuSelectWidget
.parent
.prototype.addItems
.call( this, items
, index
);
7033 // Reevaluate clipping
7042 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
7044 OO
.ui
.MenuSelectWidget
.parent
.prototype.removeItems
.call( this, items
);
7046 // Reevaluate clipping
7055 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
7057 OO
.ui
.MenuSelectWidget
.parent
.prototype.clearItems
.call( this );
7059 // Reevaluate clipping
7066 * Toggle visibility of the menu. The menu is initially hidden and must be shown by calling
7067 * `.toggle( true )` after its #$element is attached to the DOM.
7069 * Do not show the menu while it is not attached to the DOM. The calculations required to display
7070 * it in the right place and with the right dimensions only work correctly while it is attached.
7071 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
7072 * strictly enforced, so currently it only generates a warning in the browser console.
7077 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
7080 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
7081 change
= visible
!== this.isVisible();
7083 if ( visible
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
7084 OO
.ui
.warnDeprecation( 'MenuSelectWidget#toggle: Before calling this method, the menu must be attached to the DOM.' );
7085 this.warnedUnattached
= true;
7088 if ( change
&& visible
&& ( this.width
|| this.$floatableContainer
) ) {
7089 this.setIdealSize( this.width
|| this.$floatableContainer
.width() );
7093 OO
.ui
.MenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
7097 this.bindKeyDownListener();
7098 this.bindKeyPressListener();
7100 this.togglePositioning( !!this.$floatableContainer
);
7101 this.toggleClipping( true );
7103 if ( this.getSelectedItem() ) {
7104 this.$focusOwner
.attr( 'aria-activedescendant', this.getSelectedItem().getElementId() );
7105 this.getSelectedItem().scrollElementIntoView( { duration
: 0 } );
7109 if ( this.autoHide
) {
7110 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
7113 this.emit( 'ready' );
7115 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
7116 this.unbindKeyDownListener();
7117 this.unbindKeyPressListener();
7118 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
7119 this.togglePositioning( false );
7120 this.toggleClipping( false );
7128 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
7129 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
7130 * users can interact with it.
7132 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7133 * OO.ui.DropdownInputWidget instead.
7136 * // Example: A DropdownWidget with a menu that contains three options
7137 * var dropDown = new OO.ui.DropdownWidget( {
7138 * label: 'Dropdown menu: Select a menu option',
7141 * new OO.ui.MenuOptionWidget( {
7145 * new OO.ui.MenuOptionWidget( {
7149 * new OO.ui.MenuOptionWidget( {
7157 * $( 'body' ).append( dropDown.$element );
7159 * dropDown.getMenu().selectItemByData( 'b' );
7161 * dropDown.getMenu().getSelectedItem().getData(); // returns 'b'
7163 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
7165 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
7168 * @extends OO.ui.Widget
7169 * @mixins OO.ui.mixin.IconElement
7170 * @mixins OO.ui.mixin.IndicatorElement
7171 * @mixins OO.ui.mixin.LabelElement
7172 * @mixins OO.ui.mixin.TitledElement
7173 * @mixins OO.ui.mixin.TabIndexedElement
7176 * @param {Object} [config] Configuration options
7177 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.MenuSelectWidget menu select widget}
7178 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
7179 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
7180 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
7181 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
7183 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
7184 // Configuration initialization
7185 config
= $.extend( { indicator
: 'down' }, config
);
7187 // Parent constructor
7188 OO
.ui
.DropdownWidget
.parent
.call( this, config
);
7190 // Properties (must be set before TabIndexedElement constructor call)
7191 this.$handle
= this.$( '<span>' );
7192 this.$overlay
= config
.$overlay
|| this.$element
;
7194 // Mixin constructors
7195 OO
.ui
.mixin
.IconElement
.call( this, config
);
7196 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
7197 OO
.ui
.mixin
.LabelElement
.call( this, config
);
7198 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
7199 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
7202 this.menu
= new OO
.ui
.MenuSelectWidget( $.extend( {
7204 $floatableContainer
: this.$element
7209 click
: this.onClick
.bind( this ),
7210 keydown
: this.onKeyDown
.bind( this ),
7211 // Hack? Handle type-to-search when menu is not expanded and not handling its own events
7212 keypress
: this.menu
.onKeyPressHandler
,
7213 blur
: this.menu
.clearKeyPressBuffer
.bind( this.menu
)
7215 this.menu
.connect( this, {
7216 select
: 'onMenuSelect',
7217 toggle
: 'onMenuToggle'
7222 .addClass( 'oo-ui-dropdownWidget-handle' )
7225 'aria-owns': this.menu
.getElementId(),
7226 'aria-autocomplete': 'list'
7228 .append( this.$icon
, this.$label
, this.$indicator
);
7230 .addClass( 'oo-ui-dropdownWidget' )
7231 .append( this.$handle
);
7232 this.$overlay
.append( this.menu
.$element
);
7237 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
7238 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IconElement
);
7239 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IndicatorElement
);
7240 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.LabelElement
);
7241 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TitledElement
);
7242 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TabIndexedElement
);
7249 * @return {OO.ui.MenuSelectWidget} Menu of widget
7251 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
7256 * Handles menu select events.
7259 * @param {OO.ui.MenuOptionWidget} item Selected menu item
7261 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
7265 this.setLabel( null );
7269 selectedLabel
= item
.getLabel();
7271 // If the label is a DOM element, clone it, because setLabel will append() it
7272 if ( selectedLabel
instanceof jQuery
) {
7273 selectedLabel
= selectedLabel
.clone();
7276 this.setLabel( selectedLabel
);
7280 * Handle menu toggle events.
7283 * @param {boolean} isVisible Menu toggle event
7285 OO
.ui
.DropdownWidget
.prototype.onMenuToggle = function ( isVisible
) {
7286 this.$element
.toggleClass( 'oo-ui-dropdownWidget-open', isVisible
);
7290 * Handle mouse click events.
7293 * @param {jQuery.Event} e Mouse click event
7295 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
7296 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
7303 * Handle key down events.
7306 * @param {jQuery.Event} e Key down event
7308 OO
.ui
.DropdownWidget
.prototype.onKeyDown = function ( e
) {
7310 !this.isDisabled() &&
7312 e
.which
=== OO
.ui
.Keys
.ENTER
||
7314 !this.menu
.isVisible() &&
7316 e
.which
=== OO
.ui
.Keys
.SPACE
||
7317 e
.which
=== OO
.ui
.Keys
.UP
||
7318 e
.which
=== OO
.ui
.Keys
.DOWN
7329 * RadioOptionWidget is an option widget that looks like a radio button.
7330 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
7331 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
7333 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
7336 * @extends OO.ui.OptionWidget
7339 * @param {Object} [config] Configuration options
7341 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
7342 // Configuration initialization
7343 config
= config
|| {};
7345 // Properties (must be done before parent constructor which calls #setDisabled)
7346 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
7348 // Parent constructor
7349 OO
.ui
.RadioOptionWidget
.parent
.call( this, config
);
7352 // Remove implicit role, we're handling it ourselves
7353 this.radio
.$input
.attr( 'role', 'presentation' );
7355 .addClass( 'oo-ui-radioOptionWidget' )
7356 .attr( 'role', 'radio' )
7357 .attr( 'aria-checked', 'false' )
7358 .removeAttr( 'aria-selected' )
7359 .prepend( this.radio
.$element
);
7364 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
7366 /* Static Properties */
7372 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
7378 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
7384 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
7390 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
7397 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
7398 OO
.ui
.RadioOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
7400 this.radio
.setSelected( state
);
7402 .attr( 'aria-checked', state
.toString() )
7403 .removeAttr( 'aria-selected' );
7411 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
7412 OO
.ui
.RadioOptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
7414 this.radio
.setDisabled( this.isDisabled() );
7420 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
7421 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
7422 * an interface for adding, removing and selecting options.
7423 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
7425 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7426 * OO.ui.RadioSelectInputWidget instead.
7429 * // A RadioSelectWidget with RadioOptions.
7430 * var option1 = new OO.ui.RadioOptionWidget( {
7432 * label: 'Selected radio option'
7435 * var option2 = new OO.ui.RadioOptionWidget( {
7437 * label: 'Unselected radio option'
7440 * var radioSelect=new OO.ui.RadioSelectWidget( {
7441 * items: [ option1, option2 ]
7444 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
7445 * radioSelect.selectItem( option1 );
7447 * $( 'body' ).append( radioSelect.$element );
7449 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
7453 * @extends OO.ui.SelectWidget
7454 * @mixins OO.ui.mixin.TabIndexedElement
7457 * @param {Object} [config] Configuration options
7459 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
7460 // Parent constructor
7461 OO
.ui
.RadioSelectWidget
.parent
.call( this, config
);
7463 // Mixin constructors
7464 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
7468 focus
: this.bindKeyDownListener
.bind( this ),
7469 blur
: this.unbindKeyDownListener
.bind( this )
7474 .addClass( 'oo-ui-radioSelectWidget' )
7475 .attr( 'role', 'radiogroup' );
7480 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
7481 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
7484 * MultioptionWidgets are special elements that can be selected and configured with data. The
7485 * data is often unique for each option, but it does not have to be. MultioptionWidgets are used
7486 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
7487 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
7489 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Multioptions
7492 * @extends OO.ui.Widget
7493 * @mixins OO.ui.mixin.ItemWidget
7494 * @mixins OO.ui.mixin.LabelElement
7497 * @param {Object} [config] Configuration options
7498 * @cfg {boolean} [selected=false] Whether the option is initially selected
7500 OO
.ui
.MultioptionWidget
= function OoUiMultioptionWidget( config
) {
7501 // Configuration initialization
7502 config
= config
|| {};
7504 // Parent constructor
7505 OO
.ui
.MultioptionWidget
.parent
.call( this, config
);
7507 // Mixin constructors
7508 OO
.ui
.mixin
.ItemWidget
.call( this );
7509 OO
.ui
.mixin
.LabelElement
.call( this, config
);
7512 this.selected
= null;
7516 .addClass( 'oo-ui-multioptionWidget' )
7517 .append( this.$label
);
7518 this.setSelected( config
.selected
);
7523 OO
.inheritClass( OO
.ui
.MultioptionWidget
, OO
.ui
.Widget
);
7524 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.ItemWidget
);
7525 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.LabelElement
);
7532 * A change event is emitted when the selected state of the option changes.
7534 * @param {boolean} selected Whether the option is now selected
7540 * Check if the option is selected.
7542 * @return {boolean} Item is selected
7544 OO
.ui
.MultioptionWidget
.prototype.isSelected = function () {
7545 return this.selected
;
7549 * Set the option’s selected state. In general, all modifications to the selection
7550 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
7551 * method instead of this method.
7553 * @param {boolean} [state=false] Select option
7556 OO
.ui
.MultioptionWidget
.prototype.setSelected = function ( state
) {
7558 if ( this.selected
!== state
) {
7559 this.selected
= state
;
7560 this.emit( 'change', state
);
7561 this.$element
.toggleClass( 'oo-ui-multioptionWidget-selected', state
);
7567 * MultiselectWidget allows selecting multiple options from a list.
7569 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
7571 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
7575 * @extends OO.ui.Widget
7576 * @mixins OO.ui.mixin.GroupWidget
7579 * @param {Object} [config] Configuration options
7580 * @cfg {OO.ui.MultioptionWidget[]} [items] An array of options to add to the multiselect.
7582 OO
.ui
.MultiselectWidget
= function OoUiMultiselectWidget( config
) {
7583 // Parent constructor
7584 OO
.ui
.MultiselectWidget
.parent
.call( this, config
);
7586 // Configuration initialization
7587 config
= config
|| {};
7589 // Mixin constructors
7590 OO
.ui
.mixin
.GroupWidget
.call( this, config
);
7593 this.aggregate( { change
: 'select' } );
7594 // This is mostly for compatibility with CapsuleMultiselectWidget... normally, 'change' is emitted
7595 // by GroupElement only when items are added/removed
7596 this.connect( this, { select
: [ 'emit', 'change' ] } );
7599 if ( config
.items
) {
7600 this.addItems( config
.items
);
7602 this.$group
.addClass( 'oo-ui-multiselectWidget-group' );
7603 this.$element
.addClass( 'oo-ui-multiselectWidget' )
7604 .append( this.$group
);
7609 OO
.inheritClass( OO
.ui
.MultiselectWidget
, OO
.ui
.Widget
);
7610 OO
.mixinClass( OO
.ui
.MultiselectWidget
, OO
.ui
.mixin
.GroupWidget
);
7617 * A change event is emitted when the set of items changes, or an item is selected or deselected.
7623 * A select event is emitted when an item is selected or deselected.
7629 * Get options that are selected.
7631 * @return {OO.ui.MultioptionWidget[]} Selected options
7633 OO
.ui
.MultiselectWidget
.prototype.getSelectedItems = function () {
7634 return this.items
.filter( function ( item
) {
7635 return item
.isSelected();
7640 * Get the data of options that are selected.
7642 * @return {Object[]|string[]} Values of selected options
7644 OO
.ui
.MultiselectWidget
.prototype.getSelectedItemsData = function () {
7645 return this.getSelectedItems().map( function ( item
) {
7651 * Select options by reference. Options not mentioned in the `items` array will be deselected.
7653 * @param {OO.ui.MultioptionWidget[]} items Items to select
7656 OO
.ui
.MultiselectWidget
.prototype.selectItems = function ( items
) {
7657 this.items
.forEach( function ( item
) {
7658 var selected
= items
.indexOf( item
) !== -1;
7659 item
.setSelected( selected
);
7665 * Select items by their data. Options not mentioned in the `datas` array will be deselected.
7667 * @param {Object[]|string[]} datas Values of items to select
7670 OO
.ui
.MultiselectWidget
.prototype.selectItemsByData = function ( datas
) {
7673 items
= datas
.map( function ( data
) {
7674 return widget
.getItemFromData( data
);
7676 this.selectItems( items
);
7681 * CheckboxMultioptionWidget is an option widget that looks like a checkbox.
7682 * The class is used with OO.ui.CheckboxMultiselectWidget to create a selection of checkbox options.
7683 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
7685 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
7688 * @extends OO.ui.MultioptionWidget
7691 * @param {Object} [config] Configuration options
7693 OO
.ui
.CheckboxMultioptionWidget
= function OoUiCheckboxMultioptionWidget( config
) {
7694 // Configuration initialization
7695 config
= config
|| {};
7697 // Properties (must be done before parent constructor which calls #setDisabled)
7698 this.checkbox
= new OO
.ui
.CheckboxInputWidget();
7700 // Parent constructor
7701 OO
.ui
.CheckboxMultioptionWidget
.parent
.call( this, config
);
7704 this.checkbox
.on( 'change', this.onCheckboxChange
.bind( this ) );
7705 this.$element
.on( 'keydown', this.onKeyDown
.bind( this ) );
7709 .addClass( 'oo-ui-checkboxMultioptionWidget' )
7710 .prepend( this.checkbox
.$element
);
7715 OO
.inheritClass( OO
.ui
.CheckboxMultioptionWidget
, OO
.ui
.MultioptionWidget
);
7717 /* Static Properties */
7723 OO
.ui
.CheckboxMultioptionWidget
.static.tagName
= 'label';
7728 * Handle checkbox selected state change.
7732 OO
.ui
.CheckboxMultioptionWidget
.prototype.onCheckboxChange = function () {
7733 this.setSelected( this.checkbox
.isSelected() );
7739 OO
.ui
.CheckboxMultioptionWidget
.prototype.setSelected = function ( state
) {
7740 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setSelected
.call( this, state
);
7741 this.checkbox
.setSelected( state
);
7748 OO
.ui
.CheckboxMultioptionWidget
.prototype.setDisabled = function ( disabled
) {
7749 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
7750 this.checkbox
.setDisabled( this.isDisabled() );
7757 OO
.ui
.CheckboxMultioptionWidget
.prototype.focus = function () {
7758 this.checkbox
.focus();
7762 * Handle key down events.
7765 * @param {jQuery.Event} e
7767 OO
.ui
.CheckboxMultioptionWidget
.prototype.onKeyDown = function ( e
) {
7769 element
= this.getElementGroup(),
7772 if ( e
.keyCode
=== OO
.ui
.Keys
.LEFT
|| e
.keyCode
=== OO
.ui
.Keys
.UP
) {
7773 nextItem
= element
.getRelativeFocusableItem( this, -1 );
7774 } else if ( e
.keyCode
=== OO
.ui
.Keys
.RIGHT
|| e
.keyCode
=== OO
.ui
.Keys
.DOWN
) {
7775 nextItem
= element
.getRelativeFocusableItem( this, 1 );
7785 * CheckboxMultiselectWidget is a {@link OO.ui.MultiselectWidget multiselect widget} that contains
7786 * checkboxes and is used together with OO.ui.CheckboxMultioptionWidget. The
7787 * CheckboxMultiselectWidget provides an interface for adding, removing and selecting options.
7788 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
7790 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7791 * OO.ui.CheckboxMultiselectInputWidget instead.
7794 * // A CheckboxMultiselectWidget with CheckboxMultioptions.
7795 * var option1 = new OO.ui.CheckboxMultioptionWidget( {
7798 * label: 'Selected checkbox'
7801 * var option2 = new OO.ui.CheckboxMultioptionWidget( {
7803 * label: 'Unselected checkbox'
7806 * var multiselect=new OO.ui.CheckboxMultiselectWidget( {
7807 * items: [ option1, option2 ]
7810 * $( 'body' ).append( multiselect.$element );
7812 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
7815 * @extends OO.ui.MultiselectWidget
7818 * @param {Object} [config] Configuration options
7820 OO
.ui
.CheckboxMultiselectWidget
= function OoUiCheckboxMultiselectWidget( config
) {
7821 // Parent constructor
7822 OO
.ui
.CheckboxMultiselectWidget
.parent
.call( this, config
);
7825 this.$lastClicked
= null;
7828 this.$group
.on( 'click', this.onClick
.bind( this ) );
7832 .addClass( 'oo-ui-checkboxMultiselectWidget' );
7837 OO
.inheritClass( OO
.ui
.CheckboxMultiselectWidget
, OO
.ui
.MultiselectWidget
);
7842 * Get an option by its position relative to the specified item (or to the start of the option array,
7843 * if item is `null`). The direction in which to search through the option array is specified with a
7844 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
7845 * `null` if there are no options in the array.
7847 * @param {OO.ui.CheckboxMultioptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
7848 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
7849 * @return {OO.ui.CheckboxMultioptionWidget|null} Item at position, `null` if there are no items in the select
7851 OO
.ui
.CheckboxMultiselectWidget
.prototype.getRelativeFocusableItem = function ( item
, direction
) {
7852 var currentIndex
, nextIndex
, i
,
7853 increase
= direction
> 0 ? 1 : -1,
7854 len
= this.items
.length
;
7857 currentIndex
= this.items
.indexOf( item
);
7858 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
7860 // If no item is selected and moving forward, start at the beginning.
7861 // If moving backward, start at the end.
7862 nextIndex
= direction
> 0 ? 0 : len
- 1;
7865 for ( i
= 0; i
< len
; i
++ ) {
7866 item
= this.items
[ nextIndex
];
7867 if ( item
&& !item
.isDisabled() ) {
7870 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
7876 * Handle click events on checkboxes.
7878 * @param {jQuery.Event} e
7880 OO
.ui
.CheckboxMultiselectWidget
.prototype.onClick = function ( e
) {
7881 var $options
, lastClickedIndex
, nowClickedIndex
, i
, direction
, wasSelected
, items
,
7882 $lastClicked
= this.$lastClicked
,
7883 $nowClicked
= $( e
.target
).closest( '.oo-ui-checkboxMultioptionWidget' )
7884 .not( '.oo-ui-widget-disabled' );
7886 // Allow selecting multiple options at once by Shift-clicking them
7887 if ( $lastClicked
&& $nowClicked
.length
&& e
.shiftKey
) {
7888 $options
= this.$group
.find( '.oo-ui-checkboxMultioptionWidget' );
7889 lastClickedIndex
= $options
.index( $lastClicked
);
7890 nowClickedIndex
= $options
.index( $nowClicked
);
7891 // If it's the same item, either the user is being silly, or it's a fake event generated by the
7892 // browser. In either case we don't need custom handling.
7893 if ( nowClickedIndex
!== lastClickedIndex
) {
7895 wasSelected
= items
[ nowClickedIndex
].isSelected();
7896 direction
= nowClickedIndex
> lastClickedIndex
? 1 : -1;
7898 // This depends on the DOM order of the items and the order of the .items array being the same.
7899 for ( i
= lastClickedIndex
; i
!== nowClickedIndex
; i
+= direction
) {
7900 if ( !items
[ i
].isDisabled() ) {
7901 items
[ i
].setSelected( !wasSelected
);
7904 // For the now-clicked element, use immediate timeout to allow the browser to do its own
7905 // handling first, then set our value. The order in which events happen is different for
7906 // clicks on the <input> and on the <label> and there are additional fake clicks fired for
7907 // non-click actions that change the checkboxes.
7909 setTimeout( function () {
7910 if ( !items
[ nowClickedIndex
].isDisabled() ) {
7911 items
[ nowClickedIndex
].setSelected( !wasSelected
);
7917 if ( $nowClicked
.length
) {
7918 this.$lastClicked
= $nowClicked
;
7923 * FloatingMenuSelectWidget was a menu that would stick under a specified
7924 * container, even when it is inserted elsewhere in the document.
7925 * This functionality is now included in MenuSelectWidget, and FloatingMenuSelectWidget
7926 * is preserved for backwards-compatibility.
7929 * @extends OO.ui.MenuSelectWidget
7930 * @deprecated since v0.21.3, use MenuSelectWidget instead.
7933 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
7934 * Deprecated, omit this parameter and specify `$container` instead.
7935 * @param {Object} [config] Configuration options
7936 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
7938 OO
.ui
.FloatingMenuSelectWidget
= function OoUiFloatingMenuSelectWidget( inputWidget
, config
) {
7939 OO
.ui
.warnDeprecation( 'FloatingMenuSelectWidget is deprecated. Use the MenuSelectWidget instead.' );
7941 // Allow 'inputWidget' parameter and config for backwards compatibility
7942 if ( OO
.isPlainObject( inputWidget
) && config
=== undefined ) {
7943 config
= inputWidget
;
7944 inputWidget
= config
.inputWidget
;
7947 // Configuration initialization
7948 config
= config
|| {};
7951 this.inputWidget
= inputWidget
; // For backwards compatibility
7952 this.$container
= config
.$floatableContainer
|| config
.$container
|| this.inputWidget
.$element
;
7954 // Parent constructor
7955 OO
.ui
.FloatingMenuSelectWidget
.parent
.call( this, $.extend( {}, config
, { $floatableContainer
: this.$container
} ) );
7958 this.$element
.addClass( 'oo-ui-floatingMenuSelectWidget' );
7959 // For backwards compatibility
7960 this.$element
.addClass( 'oo-ui-textInputMenuSelectWidget' );
7965 OO
.inheritClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.MenuSelectWidget
);
7968 * Progress bars visually display the status of an operation, such as a download,
7969 * and can be either determinate or indeterminate:
7971 * - **determinate** process bars show the percent of an operation that is complete.
7973 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
7974 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
7975 * not use percentages.
7977 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
7980 * // Examples of determinate and indeterminate progress bars.
7981 * var progressBar1 = new OO.ui.ProgressBarWidget( {
7984 * var progressBar2 = new OO.ui.ProgressBarWidget();
7986 * // Create a FieldsetLayout to layout progress bars
7987 * var fieldset = new OO.ui.FieldsetLayout;
7988 * fieldset.addItems( [
7989 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
7990 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
7992 * $( 'body' ).append( fieldset.$element );
7995 * @extends OO.ui.Widget
7998 * @param {Object} [config] Configuration options
7999 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
8000 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
8001 * By default, the progress bar is indeterminate.
8003 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
8004 // Configuration initialization
8005 config
= config
|| {};
8007 // Parent constructor
8008 OO
.ui
.ProgressBarWidget
.parent
.call( this, config
);
8011 this.$bar
= $( '<div>' );
8012 this.progress
= null;
8015 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
8016 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
8019 role
: 'progressbar',
8021 'aria-valuemax': 100
8023 .addClass( 'oo-ui-progressBarWidget' )
8024 .append( this.$bar
);
8029 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
8031 /* Static Properties */
8037 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
8042 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
8044 * @return {number|boolean} Progress percent
8046 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
8047 return this.progress
;
8051 * Set the percent of the process completed or `false` for an indeterminate process.
8053 * @param {number|boolean} progress Progress percent or `false` for indeterminate
8055 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
8056 this.progress
= progress
;
8058 if ( progress
!== false ) {
8059 this.$bar
.css( 'width', this.progress
+ '%' );
8060 this.$element
.attr( 'aria-valuenow', this.progress
);
8062 this.$bar
.css( 'width', '' );
8063 this.$element
.removeAttr( 'aria-valuenow' );
8065 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', progress
=== false );
8069 * InputWidget is the base class for all input widgets, which
8070 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
8071 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
8072 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
8074 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8078 * @extends OO.ui.Widget
8079 * @mixins OO.ui.mixin.FlaggedElement
8080 * @mixins OO.ui.mixin.TabIndexedElement
8081 * @mixins OO.ui.mixin.TitledElement
8082 * @mixins OO.ui.mixin.AccessKeyedElement
8085 * @param {Object} [config] Configuration options
8086 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
8087 * @cfg {string} [value=''] The value of the input.
8088 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
8089 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
8090 * before it is accepted.
8092 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
8093 // Configuration initialization
8094 config
= config
|| {};
8096 // Parent constructor
8097 OO
.ui
.InputWidget
.parent
.call( this, config
);
8100 // See #reusePreInfuseDOM about config.$input
8101 this.$input
= config
.$input
|| this.getInputElement( config
);
8103 this.inputFilter
= config
.inputFilter
;
8105 // Mixin constructors
8106 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
8107 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
8108 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
8109 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$input
} ) );
8112 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
8116 .addClass( 'oo-ui-inputWidget-input' )
8117 .attr( 'name', config
.name
)
8118 .prop( 'disabled', this.isDisabled() );
8120 .addClass( 'oo-ui-inputWidget' )
8121 .append( this.$input
);
8122 this.setValue( config
.value
);
8124 this.setDir( config
.dir
);
8130 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
8131 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.FlaggedElement
);
8132 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TabIndexedElement
);
8133 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TitledElement
);
8134 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
8136 /* Static Properties */
8142 OO
.ui
.InputWidget
.static.supportsSimpleLabel
= true;
8144 /* Static Methods */
8149 OO
.ui
.InputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
8150 config
= OO
.ui
.InputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
8151 // Reusing $input lets browsers preserve inputted values across page reloads (T114134)
8152 config
.$input
= $( node
).find( '.oo-ui-inputWidget-input' );
8159 OO
.ui
.InputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8160 var state
= OO
.ui
.InputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8161 if ( config
.$input
&& config
.$input
.length
) {
8162 state
.value
= config
.$input
.val();
8163 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
8164 state
.focus
= config
.$input
.is( ':focus' );
8174 * A change event is emitted when the value of the input changes.
8176 * @param {string} value
8182 * Get input element.
8184 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
8185 * different circumstances. The element must have a `value` property (like form elements).
8188 * @param {Object} config Configuration options
8189 * @return {jQuery} Input element
8191 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
8192 return $( '<input>' );
8196 * Get input element's ID.
8198 * If the element already has an ID then that is returned, otherwise unique ID is
8199 * generated, set on the element, and returned.
8201 * @return {string} The ID of the element
8203 OO
.ui
.InputWidget
.prototype.getInputId = function () {
8204 var id
= this.$input
.attr( 'id' );
8206 if ( id
=== undefined ) {
8207 id
= OO
.ui
.generateElementId();
8208 this.$input
.attr( 'id', id
);
8215 * Handle potentially value-changing events.
8218 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
8220 OO
.ui
.InputWidget
.prototype.onEdit = function () {
8222 if ( !this.isDisabled() ) {
8223 // Allow the stack to clear so the value will be updated
8224 setTimeout( function () {
8225 widget
.setValue( widget
.$input
.val() );
8231 * Get the value of the input.
8233 * @return {string} Input value
8235 OO
.ui
.InputWidget
.prototype.getValue = function () {
8236 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
8237 // it, and we won't know unless they're kind enough to trigger a 'change' event.
8238 var value
= this.$input
.val();
8239 if ( this.value
!== value
) {
8240 this.setValue( value
);
8246 * Set the directionality of the input.
8248 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
8251 OO
.ui
.InputWidget
.prototype.setDir = function ( dir
) {
8252 this.$input
.prop( 'dir', dir
);
8257 * Set the value of the input.
8259 * @param {string} value New value
8263 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
8264 value
= this.cleanUpValue( value
);
8265 // Update the DOM if it has changed. Note that with cleanUpValue, it
8266 // is possible for the DOM value to change without this.value changing.
8267 if ( this.$input
.val() !== value
) {
8268 this.$input
.val( value
);
8270 if ( this.value
!== value
) {
8272 this.emit( 'change', this.value
);
8278 * Clean up incoming value.
8280 * Ensures value is a string, and converts undefined and null to empty string.
8283 * @param {string} value Original value
8284 * @return {string} Cleaned up value
8286 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
8287 if ( value
=== undefined || value
=== null ) {
8289 } else if ( this.inputFilter
) {
8290 return this.inputFilter( String( value
) );
8292 return String( value
);
8297 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
8298 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
8301 OO
.ui
.InputWidget
.prototype.simulateLabelClick = function () {
8302 OO
.ui
.warnDeprecation( 'InputWidget: simulateLabelClick() is deprecated.' );
8303 if ( !this.isDisabled() ) {
8304 if ( this.$input
.is( ':checkbox, :radio' ) ) {
8305 this.$input
.click();
8307 if ( this.$input
.is( ':input' ) ) {
8308 this.$input
[ 0 ].focus();
8316 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
8317 OO
.ui
.InputWidget
.parent
.prototype.setDisabled
.call( this, state
);
8318 if ( this.$input
) {
8319 this.$input
.prop( 'disabled', this.isDisabled() );
8329 OO
.ui
.InputWidget
.prototype.focus = function () {
8330 this.$input
[ 0 ].focus();
8339 OO
.ui
.InputWidget
.prototype.blur = function () {
8340 this.$input
[ 0 ].blur();
8347 OO
.ui
.InputWidget
.prototype.restorePreInfuseState = function ( state
) {
8348 OO
.ui
.InputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
8349 if ( state
.value
!== undefined && state
.value
!== this.getValue() ) {
8350 this.setValue( state
.value
);
8352 if ( state
.focus
) {
8358 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
8359 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
8360 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
8361 * HTML `<button>` (the default) or an HTML `<input>` tags. See the
8362 * [OOjs UI documentation on MediaWiki] [1] for more information.
8365 * // A ButtonInputWidget rendered as an HTML button, the default.
8366 * var button = new OO.ui.ButtonInputWidget( {
8367 * label: 'Input button',
8371 * $( 'body' ).append( button.$element );
8373 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
8376 * @extends OO.ui.InputWidget
8377 * @mixins OO.ui.mixin.ButtonElement
8378 * @mixins OO.ui.mixin.IconElement
8379 * @mixins OO.ui.mixin.IndicatorElement
8380 * @mixins OO.ui.mixin.LabelElement
8381 * @mixins OO.ui.mixin.TitledElement
8384 * @param {Object} [config] Configuration options
8385 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
8386 * @cfg {boolean} [useInputTag=false] Use an `<input>` tag instead of a `<button>` tag, the default.
8387 * Widgets configured to be an `<input>` do not support {@link #icon icons} and {@link #indicator indicators},
8388 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
8389 * be set to `true` when there’s need to support IE 6 in a form with multiple buttons.
8391 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
8392 // Configuration initialization
8393 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
8395 // See InputWidget#reusePreInfuseDOM about config.$input
8396 if ( config
.$input
) {
8397 config
.$input
.empty();
8400 // Properties (must be set before parent constructor, which calls #setValue)
8401 this.useInputTag
= config
.useInputTag
;
8403 // Parent constructor
8404 OO
.ui
.ButtonInputWidget
.parent
.call( this, config
);
8406 // Mixin constructors
8407 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
8408 OO
.ui
.mixin
.IconElement
.call( this, config
);
8409 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
8410 OO
.ui
.mixin
.LabelElement
.call( this, config
);
8411 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
8414 if ( !config
.useInputTag
) {
8415 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
8417 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
8422 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
8423 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.ButtonElement
);
8424 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IconElement
);
8425 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
8426 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.LabelElement
);
8427 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.TitledElement
);
8429 /* Static Properties */
8432 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
8433 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
8438 OO
.ui
.ButtonInputWidget
.static.supportsSimpleLabel
= false;
8444 OO
.ui
.ButtonInputWidget
.static.tagName
= 'span';
8452 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
8454 type
= [ 'button', 'submit', 'reset' ].indexOf( config
.type
) !== -1 ? config
.type
: 'button';
8455 return $( '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + type
+ '">' );
8461 * If #useInputTag is `true`, the label is set as the `value` of the `<input>` tag.
8463 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
8464 * text, or `null` for no label
8467 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
8468 if ( typeof label
=== 'function' ) {
8469 label
= OO
.ui
.resolveMsg( label
);
8472 if ( this.useInputTag
) {
8473 // Discard non-plaintext labels
8474 if ( typeof label
!== 'string' ) {
8478 this.$input
.val( label
);
8481 return OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.call( this, label
);
8485 * Set the value of the input.
8487 * This method is disabled for button inputs configured as {@link #useInputTag <input> tags}, as
8488 * they do not support {@link #value values}.
8490 * @param {string} value New value
8493 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
8494 if ( !this.useInputTag
) {
8495 OO
.ui
.ButtonInputWidget
.parent
.prototype.setValue
.call( this, value
);
8501 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
8502 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
8503 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
8504 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
8506 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
8509 * // An example of selected, unselected, and disabled checkbox inputs
8510 * var checkbox1=new OO.ui.CheckboxInputWidget( {
8514 * var checkbox2=new OO.ui.CheckboxInputWidget( {
8517 * var checkbox3=new OO.ui.CheckboxInputWidget( {
8521 * // Create a fieldset layout with fields for each checkbox.
8522 * var fieldset = new OO.ui.FieldsetLayout( {
8523 * label: 'Checkboxes'
8525 * fieldset.addItems( [
8526 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
8527 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
8528 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
8530 * $( 'body' ).append( fieldset.$element );
8532 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8535 * @extends OO.ui.InputWidget
8538 * @param {Object} [config] Configuration options
8539 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
8541 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
8542 // Configuration initialization
8543 config
= config
|| {};
8545 // Parent constructor
8546 OO
.ui
.CheckboxInputWidget
.parent
.call( this, config
);
8550 .addClass( 'oo-ui-checkboxInputWidget' )
8551 // Required for pretty styling in MediaWiki theme
8552 .append( $( '<span>' ) );
8553 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
8558 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
8560 /* Static Properties */
8566 OO
.ui
.CheckboxInputWidget
.static.tagName
= 'span';
8568 /* Static Methods */
8573 OO
.ui
.CheckboxInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8574 var state
= OO
.ui
.CheckboxInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8575 state
.checked
= config
.$input
.prop( 'checked' );
8585 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
8586 return $( '<input>' ).attr( 'type', 'checkbox' );
8592 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
8594 if ( !this.isDisabled() ) {
8595 // Allow the stack to clear so the value will be updated
8596 setTimeout( function () {
8597 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
8603 * Set selection state of this checkbox.
8605 * @param {boolean} state `true` for selected
8608 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
8610 if ( this.selected
!== state
) {
8611 this.selected
= state
;
8612 this.$input
.prop( 'checked', this.selected
);
8613 this.emit( 'change', this.selected
);
8619 * Check if this checkbox is selected.
8621 * @return {boolean} Checkbox is selected
8623 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
8624 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
8625 // it, and we won't know unless they're kind enough to trigger a 'change' event.
8626 var selected
= this.$input
.prop( 'checked' );
8627 if ( this.selected
!== selected
) {
8628 this.setSelected( selected
);
8630 return this.selected
;
8636 OO
.ui
.CheckboxInputWidget
.prototype.restorePreInfuseState = function ( state
) {
8637 OO
.ui
.CheckboxInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
8638 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
8639 this.setSelected( state
.checked
);
8644 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
8645 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
8646 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
8647 * more information about input widgets.
8649 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
8650 * are no options. If no `value` configuration option is provided, the first option is selected.
8651 * If you need a state representing no value (no option being selected), use a DropdownWidget.
8653 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
8656 * // Example: A DropdownInputWidget with three options
8657 * var dropdownInput = new OO.ui.DropdownInputWidget( {
8659 * { data: 'a', label: 'First' },
8660 * { data: 'b', label: 'Second'},
8661 * { data: 'c', label: 'Third' }
8664 * $( 'body' ).append( dropdownInput.$element );
8666 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8669 * @extends OO.ui.InputWidget
8670 * @mixins OO.ui.mixin.TitledElement
8673 * @param {Object} [config] Configuration options
8674 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
8675 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
8677 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
8678 // Configuration initialization
8679 config
= config
|| {};
8681 // See InputWidget#reusePreInfuseDOM about config.$input
8682 if ( config
.$input
) {
8683 config
.$input
.addClass( 'oo-ui-element-hidden' );
8686 // Properties (must be done before parent constructor which calls #setDisabled)
8687 this.dropdownWidget
= new OO
.ui
.DropdownWidget( config
.dropdown
);
8689 // Parent constructor
8690 OO
.ui
.DropdownInputWidget
.parent
.call( this, config
);
8692 // Mixin constructors
8693 OO
.ui
.mixin
.TitledElement
.call( this, config
);
8696 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
8699 this.setOptions( config
.options
|| [] );
8701 .addClass( 'oo-ui-dropdownInputWidget' )
8702 .append( this.dropdownWidget
.$element
);
8703 this.setTabIndexedElement( null );
8708 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
8709 OO
.mixinClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.mixin
.TitledElement
);
8717 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
8718 return $( '<input>' ).attr( 'type', 'hidden' );
8722 * Handles menu select events.
8725 * @param {OO.ui.MenuOptionWidget} item Selected menu item
8727 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
8728 this.setValue( item
.getData() );
8734 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
8736 value
= this.cleanUpValue( value
);
8737 this.dropdownWidget
.getMenu().selectItemByData( value
);
8738 // Only allow setting values that are actually present in the dropdown
8739 selected
= this.dropdownWidget
.getMenu().getSelectedItem();
8740 value
= selected
? selected
.getData() : '';
8741 OO
.ui
.DropdownInputWidget
.parent
.prototype.setValue
.call( this, value
);
8748 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
8749 this.dropdownWidget
.setDisabled( state
);
8750 OO
.ui
.DropdownInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
8755 * Set the options available for this input.
8757 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
8760 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
8762 value
= this.getValue(),
8765 // Rebuild the dropdown menu
8766 this.dropdownWidget
.getMenu()
8768 .addItems( options
.map( function ( opt
) {
8769 var optValue
= widget
.cleanUpValue( opt
.data
);
8771 if ( opt
.optgroup
=== undefined ) {
8772 return new OO
.ui
.MenuOptionWidget( {
8774 label
: opt
.label
!== undefined ? opt
.label
: optValue
8777 return new OO
.ui
.MenuSectionOptionWidget( {
8783 // Restore the previous value, or reset to something sensible
8784 if ( this.dropdownWidget
.getMenu().getItemFromData( value
) ) {
8785 // Previous value is still available, ensure consistency with the dropdown
8786 this.setValue( value
);
8788 // No longer valid, reset
8789 if ( options
.length
) {
8790 this.setValue( options
[ 0 ].data
);
8800 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
8801 this.dropdownWidget
.getMenu().toggle( true );
8808 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
8809 this.dropdownWidget
.getMenu().toggle( false );
8814 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
8815 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
8816 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
8817 * please see the [OOjs UI documentation on MediaWiki][1].
8819 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
8822 * // An example of selected, unselected, and disabled radio inputs
8823 * var radio1 = new OO.ui.RadioInputWidget( {
8827 * var radio2 = new OO.ui.RadioInputWidget( {
8830 * var radio3 = new OO.ui.RadioInputWidget( {
8834 * // Create a fieldset layout with fields for each radio button.
8835 * var fieldset = new OO.ui.FieldsetLayout( {
8836 * label: 'Radio inputs'
8838 * fieldset.addItems( [
8839 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
8840 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
8841 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
8843 * $( 'body' ).append( fieldset.$element );
8845 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8848 * @extends OO.ui.InputWidget
8851 * @param {Object} [config] Configuration options
8852 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
8854 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
8855 // Configuration initialization
8856 config
= config
|| {};
8858 // Parent constructor
8859 OO
.ui
.RadioInputWidget
.parent
.call( this, config
);
8863 .addClass( 'oo-ui-radioInputWidget' )
8864 // Required for pretty styling in MediaWiki theme
8865 .append( $( '<span>' ) );
8866 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
8871 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
8873 /* Static Properties */
8879 OO
.ui
.RadioInputWidget
.static.tagName
= 'span';
8881 /* Static Methods */
8886 OO
.ui
.RadioInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8887 var state
= OO
.ui
.RadioInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8888 state
.checked
= config
.$input
.prop( 'checked' );
8898 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
8899 return $( '<input>' ).attr( 'type', 'radio' );
8905 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
8906 // RadioInputWidget doesn't track its state.
8910 * Set selection state of this radio button.
8912 * @param {boolean} state `true` for selected
8915 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
8916 // RadioInputWidget doesn't track its state.
8917 this.$input
.prop( 'checked', state
);
8922 * Check if this radio button is selected.
8924 * @return {boolean} Radio is selected
8926 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
8927 return this.$input
.prop( 'checked' );
8933 OO
.ui
.RadioInputWidget
.prototype.restorePreInfuseState = function ( state
) {
8934 OO
.ui
.RadioInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
8935 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
8936 this.setSelected( state
.checked
);
8941 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
8942 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
8943 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
8944 * more information about input widgets.
8946 * This and OO.ui.DropdownInputWidget support the same configuration options.
8949 * // Example: A RadioSelectInputWidget with three options
8950 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
8952 * { data: 'a', label: 'First' },
8953 * { data: 'b', label: 'Second'},
8954 * { data: 'c', label: 'Third' }
8957 * $( 'body' ).append( radioSelectInput.$element );
8959 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8962 * @extends OO.ui.InputWidget
8965 * @param {Object} [config] Configuration options
8966 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
8968 OO
.ui
.RadioSelectInputWidget
= function OoUiRadioSelectInputWidget( config
) {
8969 // Configuration initialization
8970 config
= config
|| {};
8972 // Properties (must be done before parent constructor which calls #setDisabled)
8973 this.radioSelectWidget
= new OO
.ui
.RadioSelectWidget();
8975 // Parent constructor
8976 OO
.ui
.RadioSelectInputWidget
.parent
.call( this, config
);
8979 this.radioSelectWidget
.connect( this, { select
: 'onMenuSelect' } );
8982 this.setOptions( config
.options
|| [] );
8984 .addClass( 'oo-ui-radioSelectInputWidget' )
8985 .append( this.radioSelectWidget
.$element
);
8986 this.setTabIndexedElement( null );
8991 OO
.inheritClass( OO
.ui
.RadioSelectInputWidget
, OO
.ui
.InputWidget
);
8993 /* Static Properties */
8999 OO
.ui
.RadioSelectInputWidget
.static.supportsSimpleLabel
= false;
9001 /* Static Methods */
9006 OO
.ui
.RadioSelectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9007 var state
= OO
.ui
.RadioSelectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9008 state
.value
= $( node
).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
9015 OO
.ui
.RadioSelectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
9016 config
= OO
.ui
.RadioSelectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
9017 // Cannot reuse the `<input type=radio>` set
9018 delete config
.$input
;
9028 OO
.ui
.RadioSelectInputWidget
.prototype.getInputElement = function () {
9029 return $( '<input>' ).attr( 'type', 'hidden' );
9033 * Handles menu select events.
9036 * @param {OO.ui.RadioOptionWidget} item Selected menu item
9038 OO
.ui
.RadioSelectInputWidget
.prototype.onMenuSelect = function ( item
) {
9039 this.setValue( item
.getData() );
9045 OO
.ui
.RadioSelectInputWidget
.prototype.setValue = function ( value
) {
9046 value
= this.cleanUpValue( value
);
9047 this.radioSelectWidget
.selectItemByData( value
);
9048 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setValue
.call( this, value
);
9055 OO
.ui
.RadioSelectInputWidget
.prototype.setDisabled = function ( state
) {
9056 this.radioSelectWidget
.setDisabled( state
);
9057 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
9062 * Set the options available for this input.
9064 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9067 OO
.ui
.RadioSelectInputWidget
.prototype.setOptions = function ( options
) {
9069 value
= this.getValue(),
9072 // Rebuild the radioSelect menu
9073 this.radioSelectWidget
9075 .addItems( options
.map( function ( opt
) {
9076 var optValue
= widget
.cleanUpValue( opt
.data
);
9077 return new OO
.ui
.RadioOptionWidget( {
9079 label
: opt
.label
!== undefined ? opt
.label
: optValue
9083 // Restore the previous value, or reset to something sensible
9084 if ( this.radioSelectWidget
.getItemFromData( value
) ) {
9085 // Previous value is still available, ensure consistency with the radioSelect
9086 this.setValue( value
);
9088 // No longer valid, reset
9089 if ( options
.length
) {
9090 this.setValue( options
[ 0 ].data
);
9098 * CheckboxMultiselectInputWidget is a
9099 * {@link OO.ui.CheckboxMultiselectWidget CheckboxMultiselectWidget} intended to be used within a
9100 * HTML form, such as a OO.ui.FormLayout. The selected values are synchronized with the value of
9101 * HTML `<input type=checkbox>` tags. Please see the [OOjs UI documentation on MediaWiki][1] for
9102 * more information about input widgets.
9105 * // Example: A CheckboxMultiselectInputWidget with three options
9106 * var multiselectInput = new OO.ui.CheckboxMultiselectInputWidget( {
9108 * { data: 'a', label: 'First' },
9109 * { data: 'b', label: 'Second'},
9110 * { data: 'c', label: 'Third' }
9113 * $( 'body' ).append( multiselectInput.$element );
9115 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9118 * @extends OO.ui.InputWidget
9121 * @param {Object} [config] Configuration options
9122 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: …, disabled: … }`
9124 OO
.ui
.CheckboxMultiselectInputWidget
= function OoUiCheckboxMultiselectInputWidget( config
) {
9125 // Configuration initialization
9126 config
= config
|| {};
9128 // Properties (must be done before parent constructor which calls #setDisabled)
9129 this.checkboxMultiselectWidget
= new OO
.ui
.CheckboxMultiselectWidget();
9131 // Parent constructor
9132 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.call( this, config
);
9135 this.inputName
= config
.name
;
9139 .addClass( 'oo-ui-checkboxMultiselectInputWidget' )
9140 .append( this.checkboxMultiselectWidget
.$element
);
9141 // We don't use this.$input, but rather the CheckboxInputWidgets inside each option
9142 this.$input
.detach();
9143 this.setOptions( config
.options
|| [] );
9144 // Have to repeat this from parent, as we need options to be set up for this to make sense
9145 this.setValue( config
.value
);
9150 OO
.inheritClass( OO
.ui
.CheckboxMultiselectInputWidget
, OO
.ui
.InputWidget
);
9152 /* Static Properties */
9158 OO
.ui
.CheckboxMultiselectInputWidget
.static.supportsSimpleLabel
= false;
9160 /* Static Methods */
9165 OO
.ui
.CheckboxMultiselectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9166 var state
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9167 state
.value
= $( node
).find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
9168 .toArray().map( function ( el
) { return el
.value
; } );
9175 OO
.ui
.CheckboxMultiselectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
9176 config
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
9177 // Cannot reuse the `<input type=checkbox>` set
9178 delete config
.$input
;
9188 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getInputElement = function () {
9190 return $( '<div>' );
9196 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getValue = function () {
9197 var value
= this.$element
.find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
9198 .toArray().map( function ( el
) { return el
.value
; } );
9199 if ( this.value
!== value
) {
9200 this.setValue( value
);
9208 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setValue = function ( value
) {
9209 value
= this.cleanUpValue( value
);
9210 this.checkboxMultiselectWidget
.selectItemsByData( value
);
9211 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setValue
.call( this, value
);
9216 * Clean up incoming value.
9218 * @param {string[]} value Original value
9219 * @return {string[]} Cleaned up value
9221 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.cleanUpValue = function ( value
) {
9224 if ( !Array
.isArray( value
) ) {
9227 for ( i
= 0; i
< value
.length
; i
++ ) {
9229 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
.call( this, value
[ i
] );
9230 // Remove options that we don't have here
9231 if ( !this.checkboxMultiselectWidget
.getItemFromData( singleValue
) ) {
9234 cleanValue
.push( singleValue
);
9242 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setDisabled = function ( state
) {
9243 this.checkboxMultiselectWidget
.setDisabled( state
);
9244 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
9249 * Set the options available for this input.
9251 * @param {Object[]} options Array of menu options in the format `{ data: …, label: …, disabled: … }`
9254 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setOptions = function ( options
) {
9257 // Rebuild the checkboxMultiselectWidget menu
9258 this.checkboxMultiselectWidget
9260 .addItems( options
.map( function ( opt
) {
9261 var optValue
, item
, optDisabled
;
9263 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
.call( widget
, opt
.data
);
9264 optDisabled
= opt
.disabled
!== undefined ? opt
.disabled
: false;
9265 item
= new OO
.ui
.CheckboxMultioptionWidget( {
9267 label
: opt
.label
!== undefined ? opt
.label
: optValue
,
9268 disabled
: optDisabled
9270 // Set the 'name' and 'value' for form submission
9271 item
.checkbox
.$input
.attr( 'name', widget
.inputName
);
9272 item
.checkbox
.setValue( optValue
);
9276 // Re-set the value, checking the checkboxes as needed.
9277 // This will also get rid of any stale options that we just removed.
9278 this.setValue( this.getValue() );
9284 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
9285 * size of the field as well as its presentation. In addition, these widgets can be configured
9286 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
9287 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
9288 * which modifies incoming values rather than validating them.
9289 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9291 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9294 * // Example of a text input widget
9295 * var textInput = new OO.ui.TextInputWidget( {
9296 * value: 'Text input'
9298 * $( 'body' ).append( textInput.$element );
9300 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9303 * @extends OO.ui.InputWidget
9304 * @mixins OO.ui.mixin.IconElement
9305 * @mixins OO.ui.mixin.IndicatorElement
9306 * @mixins OO.ui.mixin.PendingElement
9307 * @mixins OO.ui.mixin.LabelElement
9310 * @param {Object} [config] Configuration options
9311 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
9312 * 'email', 'url' or 'number'. Ignored if `multiline` is true.
9314 * Some values of `type` result in additional behaviors:
9316 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
9317 * empties the text field
9318 * @cfg {string} [placeholder] Placeholder text
9319 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
9320 * instruct the browser to focus this widget.
9321 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
9322 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
9323 * @cfg {boolean} [multiline=false] Allow multiple lines of text
9324 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
9325 * specifies minimum number of rows to display.
9326 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
9327 * Use the #maxRows config to specify a maximum number of displayed rows.
9328 * @cfg {number} [maxRows] Maximum number of rows to display when #autosize is set to true.
9329 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
9330 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
9331 * the value or placeholder text: `'before'` or `'after'`
9332 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
9333 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
9334 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
9335 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
9336 * (the value must contain only numbers); when RegExp, a regular expression that must match the
9337 * value for it to be considered valid; when Function, a function receiving the value as parameter
9338 * that must return true, or promise resolving to true, for it to be considered valid.
9340 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
9341 // Configuration initialization
9342 config
= $.extend( {
9344 labelPosition
: 'after'
9347 if ( config
.type
=== 'search' ) {
9348 OO
.ui
.warnDeprecation( 'TextInputWidget: config.type=\'search\' is deprecated. Use the SearchInputWidget instead. See T148471 for details.' );
9349 if ( config
.icon
=== undefined ) {
9350 config
.icon
= 'search';
9352 // indicator: 'clear' is set dynamically later, depending on value
9355 // Parent constructor
9356 OO
.ui
.TextInputWidget
.parent
.call( this, config
);
9358 // Mixin constructors
9359 OO
.ui
.mixin
.IconElement
.call( this, config
);
9360 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
9361 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$input
} ) );
9362 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9365 this.type
= this.getSaneType( config
);
9366 this.readOnly
= false;
9367 this.required
= false;
9368 this.multiline
= !!config
.multiline
;
9369 this.autosize
= !!config
.autosize
;
9370 this.minRows
= config
.rows
!== undefined ? config
.rows
: '';
9371 this.maxRows
= config
.maxRows
|| Math
.max( 2 * ( this.minRows
|| 0 ), 10 );
9372 this.validate
= null;
9373 this.styleHeight
= null;
9374 this.scrollWidth
= null;
9376 // Clone for resizing
9377 if ( this.autosize
) {
9378 this.$clone
= this.$input
9380 .insertAfter( this.$input
)
9381 .attr( 'aria-hidden', 'true' )
9382 .addClass( 'oo-ui-element-hidden' );
9385 this.setValidation( config
.validate
);
9386 this.setLabelPosition( config
.labelPosition
);
9390 keypress
: this.onKeyPress
.bind( this ),
9391 blur
: this.onBlur
.bind( this ),
9392 focus
: this.onFocus
.bind( this )
9394 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
9395 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
9396 this.on( 'labelChange', this.updatePosition
.bind( this ) );
9397 this.connect( this, {
9399 disable
: 'onDisable'
9401 this.on( 'change', OO
.ui
.debounce( this.onDebouncedChange
.bind( this ), 250 ) );
9405 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type
)
9406 .append( this.$icon
, this.$indicator
);
9407 this.setReadOnly( !!config
.readOnly
);
9408 this.setRequired( !!config
.required
);
9409 this.updateSearchIndicator();
9410 if ( config
.placeholder
!== undefined ) {
9411 this.$input
.attr( 'placeholder', config
.placeholder
);
9413 if ( config
.maxLength
!== undefined ) {
9414 this.$input
.attr( 'maxlength', config
.maxLength
);
9416 if ( config
.autofocus
) {
9417 this.$input
.attr( 'autofocus', 'autofocus' );
9419 if ( config
.autocomplete
=== false ) {
9420 this.$input
.attr( 'autocomplete', 'off' );
9421 // Turning off autocompletion also disables "form caching" when the user navigates to a
9422 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
9424 beforeunload: function () {
9425 this.$input
.removeAttr( 'autocomplete' );
9427 pageshow: function () {
9428 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
9429 // whole page... it shouldn't hurt, though.
9430 this.$input
.attr( 'autocomplete', 'off' );
9434 if ( this.multiline
&& config
.rows
) {
9435 this.$input
.attr( 'rows', config
.rows
);
9437 if ( this.label
|| config
.autosize
) {
9438 this.isWaitingToBeAttached
= true;
9439 this.installParentChangeDetector();
9445 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
9446 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IconElement
);
9447 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
9448 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.PendingElement
);
9449 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.LabelElement
);
9451 /* Static Properties */
9453 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
9458 /* Static Methods */
9463 OO
.ui
.TextInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9464 var state
= OO
.ui
.TextInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9465 if ( config
.multiline
) {
9466 state
.scrollTop
= config
.$input
.scrollTop();
9474 * An `enter` event is emitted when the user presses 'enter' inside the text box.
9476 * Not emitted if the input is multiline.
9482 * A `resize` event is emitted when autosize is set and the widget resizes
9490 * Handle icon mouse down events.
9493 * @param {jQuery.Event} e Mouse down event
9495 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
9496 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
9497 this.$input
[ 0 ].focus();
9503 * Handle indicator mouse down events.
9506 * @param {jQuery.Event} e Mouse down event
9508 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
9509 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
9510 if ( this.type
=== 'search' ) {
9511 // Clear the text field
9512 this.setValue( '' );
9514 this.$input
[ 0 ].focus();
9520 * Handle key press events.
9523 * @param {jQuery.Event} e Key press event
9524 * @fires enter If enter key is pressed and input is not multiline
9526 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
9527 if ( e
.which
=== OO
.ui
.Keys
.ENTER
&& !this.multiline
) {
9528 this.emit( 'enter', e
);
9533 * Handle blur events.
9536 * @param {jQuery.Event} e Blur event
9538 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
9539 this.setValidityFlag();
9543 * Handle focus events.
9546 * @param {jQuery.Event} e Focus event
9548 OO
.ui
.TextInputWidget
.prototype.onFocus = function () {
9549 if ( this.isWaitingToBeAttached
) {
9550 // If we've received focus, then we must be attached to the document, and if
9551 // isWaitingToBeAttached is still true, that means the handler never fired. Fire it now.
9552 this.onElementAttach();
9554 this.setValidityFlag( true );
9558 * Handle element attach events.
9561 * @param {jQuery.Event} e Element attach event
9563 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
9564 this.isWaitingToBeAttached
= false;
9565 // Any previously calculated size is now probably invalid if we reattached elsewhere
9566 this.valCache
= null;
9568 this.positionLabel();
9572 * Handle change events.
9574 * @param {string} value
9577 OO
.ui
.TextInputWidget
.prototype.onChange = function () {
9578 this.updateSearchIndicator();
9583 * Handle debounced change events.
9585 * @param {string} value
9588 OO
.ui
.TextInputWidget
.prototype.onDebouncedChange = function () {
9589 this.setValidityFlag();
9593 * Handle disable events.
9595 * @param {boolean} disabled Element is disabled
9598 OO
.ui
.TextInputWidget
.prototype.onDisable = function () {
9599 this.updateSearchIndicator();
9603 * Check if the input is {@link #readOnly read-only}.
9607 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
9608 return this.readOnly
;
9612 * Set the {@link #readOnly read-only} state of the input.
9614 * @param {boolean} state Make input read-only
9617 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
9618 this.readOnly
= !!state
;
9619 this.$input
.prop( 'readOnly', this.readOnly
);
9620 this.updateSearchIndicator();
9625 * Check if the input is {@link #required required}.
9629 OO
.ui
.TextInputWidget
.prototype.isRequired = function () {
9630 return this.required
;
9634 * Set the {@link #required required} state of the input.
9636 * @param {boolean} state Make input required
9639 OO
.ui
.TextInputWidget
.prototype.setRequired = function ( state
) {
9640 this.required
= !!state
;
9641 if ( this.required
) {
9643 .prop( 'required', true )
9644 .attr( 'aria-required', 'true' );
9645 if ( this.getIndicator() === null ) {
9646 this.setIndicator( 'required' );
9650 .prop( 'required', false )
9651 .removeAttr( 'aria-required' );
9652 if ( this.getIndicator() === 'required' ) {
9653 this.setIndicator( null );
9656 this.updateSearchIndicator();
9661 * Support function for making #onElementAttach work across browsers.
9663 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
9664 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
9666 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
9667 * first time that the element gets attached to the documented.
9669 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
9670 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
9671 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
9674 if ( MutationObserver
) {
9675 // The new way. If only it wasn't so ugly.
9677 if ( this.isElementAttached() ) {
9678 // Widget is attached already, do nothing. This breaks the functionality of this function when
9679 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
9680 // would require observation of the whole document, which would hurt performance of other,
9681 // more important code.
9685 // Find topmost node in the tree
9686 topmostNode
= this.$element
[ 0 ];
9687 while ( topmostNode
.parentNode
) {
9688 topmostNode
= topmostNode
.parentNode
;
9691 // We have no way to detect the $element being attached somewhere without observing the entire
9692 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
9693 // parent node of $element, and instead detect when $element is removed from it (and thus
9694 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
9695 // doesn't get attached, we end up back here and create the parent.
9697 mutationObserver
= new MutationObserver( function ( mutations
) {
9698 var i
, j
, removedNodes
;
9699 for ( i
= 0; i
< mutations
.length
; i
++ ) {
9700 removedNodes
= mutations
[ i
].removedNodes
;
9701 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
9702 if ( removedNodes
[ j
] === topmostNode
) {
9703 setTimeout( onRemove
, 0 );
9710 onRemove = function () {
9711 // If the node was attached somewhere else, report it
9712 if ( widget
.isElementAttached() ) {
9713 widget
.onElementAttach();
9715 mutationObserver
.disconnect();
9716 widget
.installParentChangeDetector();
9719 // Create a fake parent and observe it
9720 fakeParentNode
= $( '<div>' ).append( topmostNode
)[ 0 ];
9721 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
9723 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
9724 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
9725 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
9730 * Automatically adjust the size of the text input.
9732 * This only affects #multiline inputs that are {@link #autosize autosized}.
9737 OO
.ui
.TextInputWidget
.prototype.adjustSize = function () {
9738 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
,
9739 idealHeight
, newHeight
, scrollWidth
, property
;
9741 if ( this.isWaitingToBeAttached
) {
9742 // #onElementAttach will be called soon, which calls this method
9746 if ( this.multiline
&& this.$input
.val() !== this.valCache
) {
9747 if ( this.autosize
) {
9749 .val( this.$input
.val() )
9750 .attr( 'rows', this.minRows
)
9751 // Set inline height property to 0 to measure scroll height
9752 .css( 'height', 0 );
9754 this.$clone
.removeClass( 'oo-ui-element-hidden' );
9756 this.valCache
= this.$input
.val();
9758 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
9760 // Remove inline height property to measure natural heights
9761 this.$clone
.css( 'height', '' );
9762 innerHeight
= this.$clone
.innerHeight();
9763 outerHeight
= this.$clone
.outerHeight();
9765 // Measure max rows height
9767 .attr( 'rows', this.maxRows
)
9768 .css( 'height', 'auto' )
9770 maxInnerHeight
= this.$clone
.innerHeight();
9772 // Difference between reported innerHeight and scrollHeight with no scrollbars present.
9773 // This is sometimes non-zero on Blink-based browsers, depending on zoom level.
9774 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
9775 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
9777 this.$clone
.addClass( 'oo-ui-element-hidden' );
9779 // Only apply inline height when expansion beyond natural height is needed
9780 // Use the difference between the inner and outer height as a buffer
9781 newHeight
= idealHeight
> innerHeight
? idealHeight
+ ( outerHeight
- innerHeight
) : '';
9782 if ( newHeight
!== this.styleHeight
) {
9783 this.$input
.css( 'height', newHeight
);
9784 this.styleHeight
= newHeight
;
9785 this.emit( 'resize' );
9788 scrollWidth
= this.$input
[ 0 ].offsetWidth
- this.$input
[ 0 ].clientWidth
;
9789 if ( scrollWidth
!== this.scrollWidth
) {
9790 property
= this.$element
.css( 'direction' ) === 'rtl' ? 'left' : 'right';
9792 this.$label
.css( { right
: '', left
: '' } );
9793 this.$indicator
.css( { right
: '', left
: '' } );
9795 if ( scrollWidth
) {
9796 this.$indicator
.css( property
, scrollWidth
);
9797 if ( this.labelPosition
=== 'after' ) {
9798 this.$label
.css( property
, scrollWidth
);
9802 this.scrollWidth
= scrollWidth
;
9803 this.positionLabel();
9813 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
9814 if ( config
.multiline
) {
9815 return $( '<textarea>' );
9816 } else if ( this.getSaneType( config
) === 'number' ) {
9817 return $( '<input>' )
9818 .attr( 'step', 'any' )
9819 .attr( 'type', 'number' );
9821 return $( '<input>' ).attr( 'type', this.getSaneType( config
) );
9826 * Get sanitized value for 'type' for given config.
9828 * @param {Object} config Configuration options
9829 * @return {string|null}
9832 OO
.ui
.TextInputWidget
.prototype.getSaneType = function ( config
) {
9833 var allowedTypes
= [
9841 return allowedTypes
.indexOf( config
.type
) !== -1 ? config
.type
: 'text';
9845 * Check if the input supports multiple lines.
9849 OO
.ui
.TextInputWidget
.prototype.isMultiline = function () {
9850 return !!this.multiline
;
9854 * Check if the input automatically adjusts its size.
9858 OO
.ui
.TextInputWidget
.prototype.isAutosizing = function () {
9859 return !!this.autosize
;
9863 * Focus the input and select a specified range within the text.
9865 * @param {number} from Select from offset
9866 * @param {number} [to] Select to offset, defaults to from
9869 OO
.ui
.TextInputWidget
.prototype.selectRange = function ( from, to
) {
9870 var isBackwards
, start
, end
,
9871 input
= this.$input
[ 0 ];
9875 isBackwards
= to
< from;
9876 start
= isBackwards
? to
: from;
9877 end
= isBackwards
? from : to
;
9882 input
.setSelectionRange( start
, end
, isBackwards
? 'backward' : 'forward' );
9884 // IE throws an exception if you call setSelectionRange on a unattached DOM node.
9885 // Rather than expensively check if the input is attached every time, just check
9886 // if it was the cause of an error being thrown. If not, rethrow the error.
9887 if ( this.getElementDocument().body
.contains( input
) ) {
9895 * Get an object describing the current selection range in a directional manner
9897 * @return {Object} Object containing 'from' and 'to' offsets
9899 OO
.ui
.TextInputWidget
.prototype.getRange = function () {
9900 var input
= this.$input
[ 0 ],
9901 start
= input
.selectionStart
,
9902 end
= input
.selectionEnd
,
9903 isBackwards
= input
.selectionDirection
=== 'backward';
9906 from: isBackwards
? end
: start
,
9907 to
: isBackwards
? start
: end
9912 * Get the length of the text input value.
9914 * This could differ from the length of #getValue if the
9915 * value gets filtered
9917 * @return {number} Input length
9919 OO
.ui
.TextInputWidget
.prototype.getInputLength = function () {
9920 return this.$input
[ 0 ].value
.length
;
9924 * Focus the input and select the entire text.
9928 OO
.ui
.TextInputWidget
.prototype.select = function () {
9929 return this.selectRange( 0, this.getInputLength() );
9933 * Focus the input and move the cursor to the start.
9937 OO
.ui
.TextInputWidget
.prototype.moveCursorToStart = function () {
9938 return this.selectRange( 0 );
9942 * Focus the input and move the cursor to the end.
9946 OO
.ui
.TextInputWidget
.prototype.moveCursorToEnd = function () {
9947 return this.selectRange( this.getInputLength() );
9951 * Insert new content into the input.
9953 * @param {string} content Content to be inserted
9956 OO
.ui
.TextInputWidget
.prototype.insertContent = function ( content
) {
9958 range
= this.getRange(),
9959 value
= this.getValue();
9961 start
= Math
.min( range
.from, range
.to
);
9962 end
= Math
.max( range
.from, range
.to
);
9964 this.setValue( value
.slice( 0, start
) + content
+ value
.slice( end
) );
9965 this.selectRange( start
+ content
.length
);
9970 * Insert new content either side of a selection.
9972 * @param {string} pre Content to be inserted before the selection
9973 * @param {string} post Content to be inserted after the selection
9976 OO
.ui
.TextInputWidget
.prototype.encapsulateContent = function ( pre
, post
) {
9978 range
= this.getRange(),
9979 offset
= pre
.length
;
9981 start
= Math
.min( range
.from, range
.to
);
9982 end
= Math
.max( range
.from, range
.to
);
9984 this.selectRange( start
).insertContent( pre
);
9985 this.selectRange( offset
+ end
).insertContent( post
);
9987 this.selectRange( offset
+ start
, offset
+ end
);
9992 * Set the validation pattern.
9994 * The validation pattern is either a regular expression, a function, or the symbolic name of a
9995 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
9996 * value must contain only numbers).
9998 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
9999 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
10001 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
10002 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
10003 this.validate
= validate
;
10005 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
10010 * Sets the 'invalid' flag appropriately.
10012 * @param {boolean} [isValid] Optionally override validation result
10014 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
10016 setFlag = function ( valid
) {
10018 widget
.$input
.attr( 'aria-invalid', 'true' );
10020 widget
.$input
.removeAttr( 'aria-invalid' );
10022 widget
.setFlags( { invalid
: !valid
} );
10025 if ( isValid
!== undefined ) {
10026 setFlag( isValid
);
10028 this.getValidity().then( function () {
10037 * Get the validity of current value.
10039 * This method returns a promise that resolves if the value is valid and rejects if
10040 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
10042 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
10044 OO
.ui
.TextInputWidget
.prototype.getValidity = function () {
10047 function rejectOrResolve( valid
) {
10049 return $.Deferred().resolve().promise();
10051 return $.Deferred().reject().promise();
10055 // Check browser validity and reject if it is invalid
10057 this.$input
[ 0 ].checkValidity
!== undefined &&
10058 this.$input
[ 0 ].checkValidity() === false
10060 return rejectOrResolve( false );
10063 // Run our checks if the browser thinks the field is valid
10064 if ( this.validate
instanceof Function
) {
10065 result
= this.validate( this.getValue() );
10066 if ( result
&& $.isFunction( result
.promise
) ) {
10067 return result
.promise().then( function ( valid
) {
10068 return rejectOrResolve( valid
);
10071 return rejectOrResolve( result
);
10074 return rejectOrResolve( this.getValue().match( this.validate
) );
10079 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
10081 * @param {string} labelPosition Label position, 'before' or 'after'
10084 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
10085 this.labelPosition
= labelPosition
;
10086 if ( this.label
) {
10087 // If there is no label and we only change the position, #updatePosition is a no-op,
10088 // but it takes really a lot of work to do nothing.
10089 this.updatePosition();
10095 * Update the position of the inline label.
10097 * This method is called by #setLabelPosition, and can also be called on its own if
10098 * something causes the label to be mispositioned.
10102 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
10103 var after
= this.labelPosition
=== 'after';
10106 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
10107 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
10109 this.valCache
= null;
10110 this.scrollWidth
= null;
10112 this.positionLabel();
10118 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
10119 * already empty or when it's not editable.
10121 OO
.ui
.TextInputWidget
.prototype.updateSearchIndicator = function () {
10122 if ( this.type
=== 'search' ) {
10123 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
10124 this.setIndicator( null );
10126 this.setIndicator( 'clear' );
10132 * Position the label by setting the correct padding on the input.
10137 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
10138 var after
, rtl
, property
;
10140 if ( this.isWaitingToBeAttached
) {
10141 // #onElementAttach will be called soon, which calls this method
10145 // Clear old values
10147 // Clear old values if present
10149 'padding-right': '',
10153 if ( this.label
) {
10154 this.$element
.append( this.$label
);
10156 this.$label
.detach();
10160 after
= this.labelPosition
=== 'after';
10161 rtl
= this.$element
.css( 'direction' ) === 'rtl';
10162 property
= after
=== rtl
? 'padding-left' : 'padding-right';
10164 this.$input
.css( property
, this.$label
.outerWidth( true ) + ( after
? this.scrollWidth
: 0 ) );
10172 OO
.ui
.TextInputWidget
.prototype.restorePreInfuseState = function ( state
) {
10173 OO
.ui
.TextInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
10174 if ( state
.scrollTop
!== undefined ) {
10175 this.$input
.scrollTop( state
.scrollTop
);
10181 * @extends OO.ui.TextInputWidget
10184 * @param {Object} [config] Configuration options
10186 OO
.ui
.SearchInputWidget
= function OoUiSearchInputWidget( config
) {
10187 config
= $.extend( {
10191 // Set type to text so that TextInputWidget doesn't
10192 // get stuck in an infinite loop.
10193 config
.type
= 'text';
10195 // Parent constructor
10196 OO
.ui
.SearchInputWidget
.parent
.call( this, config
);
10199 this.$element
.addClass( 'oo-ui-textInputWidget-type-search' );
10200 this.updateSearchIndicator();
10201 this.connect( this, {
10202 disable
: 'onDisable'
10208 OO
.inheritClass( OO
.ui
.SearchInputWidget
, OO
.ui
.TextInputWidget
);
10216 OO
.ui
.SearchInputWidget
.prototype.getInputElement = function () {
10217 return $( '<input>' ).attr( 'type', 'search' );
10223 OO
.ui
.SearchInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
10224 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
10225 // Clear the text field
10226 this.setValue( '' );
10227 this.$input
[ 0 ].focus();
10233 * Update the 'clear' indicator displayed on type: 'search' text
10234 * fields, hiding it when the field is already empty or when it's not
10237 OO
.ui
.SearchInputWidget
.prototype.updateSearchIndicator = function () {
10238 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
10239 this.setIndicator( null );
10241 this.setIndicator( 'clear' );
10248 OO
.ui
.SearchInputWidget
.prototype.onChange = function () {
10249 OO
.ui
.SearchInputWidget
.parent
.prototype.onChange
.call( this );
10250 this.updateSearchIndicator();
10254 * Handle disable events.
10256 * @param {boolean} disabled Element is disabled
10259 OO
.ui
.SearchInputWidget
.prototype.onDisable = function () {
10260 this.updateSearchIndicator();
10266 OO
.ui
.SearchInputWidget
.prototype.setReadOnly = function ( state
) {
10267 OO
.ui
.SearchInputWidget
.parent
.prototype.setReadOnly
.call( this, state
);
10268 this.updateSearchIndicator();
10273 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
10274 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
10275 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
10277 * - by typing a value in the text input field. If the value exactly matches the value of a menu
10278 * option, that option will appear to be selected.
10279 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
10282 * After the user chooses an option, its `data` will be used as a new value for the widget.
10283 * A `label` also can be specified for each option: if given, it will be shown instead of the
10284 * `data` in the dropdown menu.
10286 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
10288 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
10291 * // Example: A ComboBoxInputWidget.
10292 * var comboBox = new OO.ui.ComboBoxInputWidget( {
10293 * value: 'Option 1',
10295 * { data: 'Option 1' },
10296 * { data: 'Option 2' },
10297 * { data: 'Option 3' }
10300 * $( 'body' ).append( comboBox.$element );
10303 * // Example: A ComboBoxInputWidget with additional option labels.
10304 * var comboBox = new OO.ui.ComboBoxInputWidget( {
10305 * value: 'Option 1',
10308 * data: 'Option 1',
10309 * label: 'Option One'
10312 * data: 'Option 2',
10313 * label: 'Option Two'
10316 * data: 'Option 3',
10317 * label: 'Option Three'
10321 * $( 'body' ).append( comboBox.$element );
10323 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
10326 * @extends OO.ui.TextInputWidget
10329 * @param {Object} [config] Configuration options
10330 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
10331 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
10332 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
10333 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
10334 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
10335 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
10337 OO
.ui
.ComboBoxInputWidget
= function OoUiComboBoxInputWidget( config
) {
10338 // Configuration initialization
10339 config
= $.extend( {
10340 autocomplete
: false
10343 // ComboBoxInputWidget shouldn't support `multiline`
10344 config
.multiline
= false;
10346 // See InputWidget#reusePreInfuseDOM about `config.$input`
10347 if ( config
.$input
) {
10348 config
.$input
.removeAttr( 'list' );
10351 // Parent constructor
10352 OO
.ui
.ComboBoxInputWidget
.parent
.call( this, config
);
10355 this.$overlay
= config
.$overlay
|| this.$element
;
10356 this.dropdownButton
= new OO
.ui
.ButtonWidget( {
10357 classes
: [ 'oo-ui-comboBoxInputWidget-dropdownButton' ],
10359 disabled
: this.disabled
10361 this.menu
= new OO
.ui
.MenuSelectWidget( $.extend(
10365 $floatableContainer
: this.$element
,
10366 disabled
: this.isDisabled()
10372 this.connect( this, {
10373 change
: 'onInputChange',
10374 enter
: 'onInputEnter'
10376 this.dropdownButton
.connect( this, {
10377 click
: 'onDropdownButtonClick'
10379 this.menu
.connect( this, {
10380 choose
: 'onMenuChoose',
10381 add
: 'onMenuItemsChange',
10382 remove
: 'onMenuItemsChange'
10386 this.$input
.attr( {
10388 'aria-owns': this.menu
.getElementId(),
10389 'aria-autocomplete': 'list'
10391 // Do not override options set via config.menu.items
10392 if ( config
.options
!== undefined ) {
10393 this.setOptions( config
.options
);
10395 this.$field
= $( '<div>' )
10396 .addClass( 'oo-ui-comboBoxInputWidget-field' )
10397 .append( this.$input
, this.dropdownButton
.$element
);
10399 .addClass( 'oo-ui-comboBoxInputWidget' )
10400 .append( this.$field
);
10401 this.$overlay
.append( this.menu
.$element
);
10402 this.onMenuItemsChange();
10407 OO
.inheritClass( OO
.ui
.ComboBoxInputWidget
, OO
.ui
.TextInputWidget
);
10412 * Get the combobox's menu.
10414 * @return {OO.ui.MenuSelectWidget} Menu widget
10416 OO
.ui
.ComboBoxInputWidget
.prototype.getMenu = function () {
10421 * Get the combobox's text input widget.
10423 * @return {OO.ui.TextInputWidget} Text input widget
10425 OO
.ui
.ComboBoxInputWidget
.prototype.getInput = function () {
10430 * Handle input change events.
10433 * @param {string} value New value
10435 OO
.ui
.ComboBoxInputWidget
.prototype.onInputChange = function ( value
) {
10436 var match
= this.menu
.getItemFromData( value
);
10438 this.menu
.selectItem( match
);
10439 if ( this.menu
.getHighlightedItem() ) {
10440 this.menu
.highlightItem( match
);
10443 if ( !this.isDisabled() ) {
10444 this.menu
.toggle( true );
10449 * Handle input enter events.
10453 OO
.ui
.ComboBoxInputWidget
.prototype.onInputEnter = function () {
10454 if ( !this.isDisabled() ) {
10455 this.menu
.toggle( false );
10460 * Handle button click events.
10464 OO
.ui
.ComboBoxInputWidget
.prototype.onDropdownButtonClick = function () {
10465 this.menu
.toggle();
10466 this.$input
[ 0 ].focus();
10470 * Handle menu choose events.
10473 * @param {OO.ui.OptionWidget} item Chosen item
10475 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuChoose = function ( item
) {
10476 this.setValue( item
.getData() );
10480 * Handle menu item change events.
10484 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuItemsChange = function () {
10485 var match
= this.menu
.getItemFromData( this.getValue() );
10486 this.menu
.selectItem( match
);
10487 if ( this.menu
.getHighlightedItem() ) {
10488 this.menu
.highlightItem( match
);
10490 this.$element
.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu
.isEmpty() );
10496 OO
.ui
.ComboBoxInputWidget
.prototype.setDisabled = function ( disabled
) {
10498 OO
.ui
.ComboBoxInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
10500 if ( this.dropdownButton
) {
10501 this.dropdownButton
.setDisabled( this.isDisabled() );
10504 this.menu
.setDisabled( this.isDisabled() );
10511 * Set the options available for this input.
10513 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10516 OO
.ui
.ComboBoxInputWidget
.prototype.setOptions = function ( options
) {
10519 .addItems( options
.map( function ( opt
) {
10520 return new OO
.ui
.MenuOptionWidget( {
10522 label
: opt
.label
!== undefined ? opt
.label
: opt
.data
10530 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
10531 * which is a widget that is specified by reference before any optional configuration settings.
10533 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
10535 * - **left**: The label is placed before the field-widget and aligned with the left margin.
10536 * A left-alignment is used for forms with many fields.
10537 * - **right**: The label is placed before the field-widget and aligned to the right margin.
10538 * A right-alignment is used for long but familiar forms which users tab through,
10539 * verifying the current field with a quick glance at the label.
10540 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
10541 * that users fill out from top to bottom.
10542 * - **inline**: The label is placed after the field-widget and aligned to the left.
10543 * An inline-alignment is best used with checkboxes or radio buttons.
10545 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
10546 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
10548 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
10551 * @extends OO.ui.Layout
10552 * @mixins OO.ui.mixin.LabelElement
10553 * @mixins OO.ui.mixin.TitledElement
10556 * @param {OO.ui.Widget} fieldWidget Field widget
10557 * @param {Object} [config] Configuration options
10558 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
10559 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
10560 * The array may contain strings or OO.ui.HtmlSnippet instances.
10561 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
10562 * The array may contain strings or OO.ui.HtmlSnippet instances.
10563 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
10564 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
10565 * For important messages, you are advised to use `notices`, as they are always shown.
10566 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
10567 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
10569 * @throws {Error} An error is thrown if no widget is specified
10571 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
10572 // Allow passing positional parameters inside the config object
10573 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
10574 config
= fieldWidget
;
10575 fieldWidget
= config
.fieldWidget
;
10578 // Make sure we have required constructor arguments
10579 if ( fieldWidget
=== undefined ) {
10580 throw new Error( 'Widget not found' );
10583 // Configuration initialization
10584 config
= $.extend( { align
: 'left' }, config
);
10586 // Parent constructor
10587 OO
.ui
.FieldLayout
.parent
.call( this, config
);
10589 // Mixin constructors
10590 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, {
10591 $label
: $( '<label>' )
10593 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
10596 this.fieldWidget
= fieldWidget
;
10599 this.$field
= this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
10600 this.$messages
= $( '<ul>' );
10601 this.$header
= $( '<span>' );
10602 this.$body
= $( '<div>' );
10604 if ( config
.help
) {
10605 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
10606 $overlay
: config
.$overlay
,
10610 classes
: [ 'oo-ui-fieldLayout-help' ],
10614 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
10615 this.popupButtonWidget
.getPopup().$body
.html( config
.help
.toString() );
10617 this.popupButtonWidget
.getPopup().$body
.text( config
.help
);
10619 this.$help
= this.popupButtonWidget
.$element
;
10621 this.$help
= $( [] );
10625 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
10628 if ( fieldWidget
.constructor.static.supportsSimpleLabel
) {
10629 if ( this.fieldWidget
.getInputId() ) {
10630 this.$label
.attr( 'for', this.fieldWidget
.getInputId() );
10632 this.$label
.on( 'click', function () {
10633 this.fieldWidget
.focus();
10639 .addClass( 'oo-ui-fieldLayout' )
10640 .toggleClass( 'oo-ui-fieldLayout-disabled', this.fieldWidget
.isDisabled() )
10641 .append( this.$body
);
10642 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
10643 this.$header
.addClass( 'oo-ui-fieldLayout-header' );
10644 this.$messages
.addClass( 'oo-ui-fieldLayout-messages' );
10646 .addClass( 'oo-ui-fieldLayout-field' )
10647 .append( this.fieldWidget
.$element
);
10649 this.setErrors( config
.errors
|| [] );
10650 this.setNotices( config
.notices
|| [] );
10651 this.setAlignment( config
.align
);
10656 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
10657 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.LabelElement
);
10658 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.TitledElement
);
10663 * Handle field disable events.
10666 * @param {boolean} value Field is disabled
10668 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
10669 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
10673 * Get the widget contained by the field.
10675 * @return {OO.ui.Widget} Field widget
10677 OO
.ui
.FieldLayout
.prototype.getField = function () {
10678 return this.fieldWidget
;
10682 * Return `true` if the given field widget can be used with `'inline'` alignment (see
10683 * #setAlignment). Return `false` if it can't or if this can't be determined.
10685 * @return {boolean}
10687 OO
.ui
.FieldLayout
.prototype.isFieldInline = function () {
10688 // This is very simplistic, but should be good enough.
10689 return this.getField().$element
.prop( 'tagName' ).toLowerCase() === 'span';
10694 * @param {string} kind 'error' or 'notice'
10695 * @param {string|OO.ui.HtmlSnippet} text
10698 OO
.ui
.FieldLayout
.prototype.makeMessage = function ( kind
, text
) {
10699 var $listItem
, $icon
, message
;
10700 $listItem
= $( '<li>' );
10701 if ( kind
=== 'error' ) {
10702 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'warning' ] } ).$element
;
10703 } else if ( kind
=== 'notice' ) {
10704 $icon
= new OO
.ui
.IconWidget( { icon
: 'info' } ).$element
;
10708 message
= new OO
.ui
.LabelWidget( { label
: text
} );
10710 .append( $icon
, message
.$element
)
10711 .addClass( 'oo-ui-fieldLayout-messages-' + kind
);
10716 * Set the field alignment mode.
10719 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
10722 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
10723 if ( value
!== this.align
) {
10724 // Default to 'left'
10725 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
10729 if ( value
=== 'inline' && !this.isFieldInline() ) {
10732 // Reorder elements
10733 if ( value
=== 'top' ) {
10734 this.$header
.append( this.$label
, this.$help
);
10735 this.$body
.append( this.$header
, this.$field
);
10736 } else if ( value
=== 'inline' ) {
10737 this.$header
.append( this.$label
, this.$help
);
10738 this.$body
.append( this.$field
, this.$header
);
10740 this.$header
.append( this.$label
);
10741 this.$body
.append( this.$header
, this.$help
, this.$field
);
10743 // Set classes. The following classes can be used here:
10744 // * oo-ui-fieldLayout-align-left
10745 // * oo-ui-fieldLayout-align-right
10746 // * oo-ui-fieldLayout-align-top
10747 // * oo-ui-fieldLayout-align-inline
10748 if ( this.align
) {
10749 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
10751 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
10752 this.align
= value
;
10759 * Set the list of error messages.
10761 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
10762 * The array may contain strings or OO.ui.HtmlSnippet instances.
10765 OO
.ui
.FieldLayout
.prototype.setErrors = function ( errors
) {
10766 this.errors
= errors
.slice();
10767 this.updateMessages();
10772 * Set the list of notice messages.
10774 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
10775 * The array may contain strings or OO.ui.HtmlSnippet instances.
10778 OO
.ui
.FieldLayout
.prototype.setNotices = function ( notices
) {
10779 this.notices
= notices
.slice();
10780 this.updateMessages();
10785 * Update the rendering of error and notice messages.
10789 OO
.ui
.FieldLayout
.prototype.updateMessages = function () {
10791 this.$messages
.empty();
10793 if ( this.errors
.length
|| this.notices
.length
) {
10794 this.$body
.after( this.$messages
);
10796 this.$messages
.remove();
10800 for ( i
= 0; i
< this.notices
.length
; i
++ ) {
10801 this.$messages
.append( this.makeMessage( 'notice', this.notices
[ i
] ) );
10803 for ( i
= 0; i
< this.errors
.length
; i
++ ) {
10804 this.$messages
.append( this.makeMessage( 'error', this.errors
[ i
] ) );
10809 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
10810 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
10811 * is required and is specified before any optional configuration settings.
10813 * Labels can be aligned in one of four ways:
10815 * - **left**: The label is placed before the field-widget and aligned with the left margin.
10816 * A left-alignment is used for forms with many fields.
10817 * - **right**: The label is placed before the field-widget and aligned to the right margin.
10818 * A right-alignment is used for long but familiar forms which users tab through,
10819 * verifying the current field with a quick glance at the label.
10820 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
10821 * that users fill out from top to bottom.
10822 * - **inline**: The label is placed after the field-widget and aligned to the left.
10823 * An inline-alignment is best used with checkboxes or radio buttons.
10825 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
10826 * text is specified.
10829 * // Example of an ActionFieldLayout
10830 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
10831 * new OO.ui.TextInputWidget( {
10832 * placeholder: 'Field widget'
10834 * new OO.ui.ButtonWidget( {
10838 * label: 'An ActionFieldLayout. This label is aligned top',
10840 * help: 'This is help text'
10844 * $( 'body' ).append( actionFieldLayout.$element );
10847 * @extends OO.ui.FieldLayout
10850 * @param {OO.ui.Widget} fieldWidget Field widget
10851 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
10852 * @param {Object} config
10854 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
10855 // Allow passing positional parameters inside the config object
10856 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
10857 config
= fieldWidget
;
10858 fieldWidget
= config
.fieldWidget
;
10859 buttonWidget
= config
.buttonWidget
;
10862 // Parent constructor
10863 OO
.ui
.ActionFieldLayout
.parent
.call( this, fieldWidget
, config
);
10866 this.buttonWidget
= buttonWidget
;
10867 this.$button
= $( '<span>' );
10868 this.$input
= this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
10872 .addClass( 'oo-ui-actionFieldLayout' );
10874 .addClass( 'oo-ui-actionFieldLayout-button' )
10875 .append( this.buttonWidget
.$element
);
10877 .addClass( 'oo-ui-actionFieldLayout-input' )
10878 .append( this.fieldWidget
.$element
);
10880 .append( this.$input
, this.$button
);
10885 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
10888 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
10889 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
10890 * configured with a label as well. For more information and examples,
10891 * please see the [OOjs UI documentation on MediaWiki][1].
10894 * // Example of a fieldset layout
10895 * var input1 = new OO.ui.TextInputWidget( {
10896 * placeholder: 'A text input field'
10899 * var input2 = new OO.ui.TextInputWidget( {
10900 * placeholder: 'A text input field'
10903 * var fieldset = new OO.ui.FieldsetLayout( {
10904 * label: 'Example of a fieldset layout'
10907 * fieldset.addItems( [
10908 * new OO.ui.FieldLayout( input1, {
10909 * label: 'Field One'
10911 * new OO.ui.FieldLayout( input2, {
10912 * label: 'Field Two'
10915 * $( 'body' ).append( fieldset.$element );
10917 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
10920 * @extends OO.ui.Layout
10921 * @mixins OO.ui.mixin.IconElement
10922 * @mixins OO.ui.mixin.LabelElement
10923 * @mixins OO.ui.mixin.GroupElement
10926 * @param {Object} [config] Configuration options
10927 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
10928 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
10929 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
10930 * For important messages, you are advised to use `notices`, as they are always shown.
10931 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
10932 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
10934 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
10935 // Configuration initialization
10936 config
= config
|| {};
10938 // Parent constructor
10939 OO
.ui
.FieldsetLayout
.parent
.call( this, config
);
10941 // Mixin constructors
10942 OO
.ui
.mixin
.IconElement
.call( this, config
);
10943 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: $( '<div>' ) } ) );
10944 OO
.ui
.mixin
.GroupElement
.call( this, config
);
10947 this.$header
= $( '<div>' );
10948 if ( config
.help
) {
10949 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
10950 $overlay
: config
.$overlay
,
10954 classes
: [ 'oo-ui-fieldsetLayout-help' ],
10958 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
10959 this.popupButtonWidget
.getPopup().$body
.html( config
.help
.toString() );
10961 this.popupButtonWidget
.getPopup().$body
.text( config
.help
);
10963 this.$help
= this.popupButtonWidget
.$element
;
10965 this.$help
= $( [] );
10970 .addClass( 'oo-ui-fieldsetLayout-header' )
10971 .append( this.$icon
, this.$label
, this.$help
);
10972 this.$group
.addClass( 'oo-ui-fieldsetLayout-group' );
10974 .addClass( 'oo-ui-fieldsetLayout' )
10975 .prepend( this.$header
, this.$group
);
10976 if ( Array
.isArray( config
.items
) ) {
10977 this.addItems( config
.items
);
10983 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
10984 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.IconElement
);
10985 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.LabelElement
);
10986 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.GroupElement
);
10988 /* Static Properties */
10994 OO
.ui
.FieldsetLayout
.static.tagName
= 'fieldset';
10997 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
10998 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
10999 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
11000 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
11002 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
11003 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
11004 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
11005 * some fancier controls. Some controls have both regular and InputWidget variants, for example
11006 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
11007 * often have simplified APIs to match the capabilities of HTML forms.
11008 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
11010 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
11011 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11014 * // Example of a form layout that wraps a fieldset layout
11015 * var input1 = new OO.ui.TextInputWidget( {
11016 * placeholder: 'Username'
11018 * var input2 = new OO.ui.TextInputWidget( {
11019 * placeholder: 'Password',
11022 * var submit = new OO.ui.ButtonInputWidget( {
11026 * var fieldset = new OO.ui.FieldsetLayout( {
11027 * label: 'A form layout'
11029 * fieldset.addItems( [
11030 * new OO.ui.FieldLayout( input1, {
11031 * label: 'Username',
11034 * new OO.ui.FieldLayout( input2, {
11035 * label: 'Password',
11038 * new OO.ui.FieldLayout( submit )
11040 * var form = new OO.ui.FormLayout( {
11041 * items: [ fieldset ],
11042 * action: '/api/formhandler',
11045 * $( 'body' ).append( form.$element );
11048 * @extends OO.ui.Layout
11049 * @mixins OO.ui.mixin.GroupElement
11052 * @param {Object} [config] Configuration options
11053 * @cfg {string} [method] HTML form `method` attribute
11054 * @cfg {string} [action] HTML form `action` attribute
11055 * @cfg {string} [enctype] HTML form `enctype` attribute
11056 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
11058 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
11061 // Configuration initialization
11062 config
= config
|| {};
11064 // Parent constructor
11065 OO
.ui
.FormLayout
.parent
.call( this, config
);
11067 // Mixin constructors
11068 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
11071 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
11073 // Make sure the action is safe
11074 action
= config
.action
;
11075 if ( action
!== undefined && !OO
.ui
.isSafeUrl( action
) ) {
11076 action
= './' + action
;
11081 .addClass( 'oo-ui-formLayout' )
11083 method
: config
.method
,
11085 enctype
: config
.enctype
11087 if ( Array
.isArray( config
.items
) ) {
11088 this.addItems( config
.items
);
11094 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
11095 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.mixin
.GroupElement
);
11100 * A 'submit' event is emitted when the form is submitted.
11105 /* Static Properties */
11111 OO
.ui
.FormLayout
.static.tagName
= 'form';
11116 * Handle form submit events.
11119 * @param {jQuery.Event} e Submit event
11122 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
11123 if ( this.emit( 'submit' ) ) {
11129 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
11130 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
11133 * // Example of a panel layout
11134 * var panel = new OO.ui.PanelLayout( {
11138 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
11140 * $( 'body' ).append( panel.$element );
11143 * @extends OO.ui.Layout
11146 * @param {Object} [config] Configuration options
11147 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
11148 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
11149 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
11150 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
11152 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
11153 // Configuration initialization
11154 config
= $.extend( {
11161 // Parent constructor
11162 OO
.ui
.PanelLayout
.parent
.call( this, config
);
11165 this.$element
.addClass( 'oo-ui-panelLayout' );
11166 if ( config
.scrollable
) {
11167 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
11169 if ( config
.padded
) {
11170 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
11172 if ( config
.expanded
) {
11173 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
11175 if ( config
.framed
) {
11176 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
11182 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
11187 * Focus the panel layout
11189 * The default implementation just focuses the first focusable element in the panel
11191 OO
.ui
.PanelLayout
.prototype.focus = function () {
11192 OO
.ui
.findFocusable( this.$element
).focus();
11196 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
11197 * items), with small margins between them. Convenient when you need to put a number of block-level
11198 * widgets on a single line next to each other.
11200 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
11203 * // HorizontalLayout with a text input and a label
11204 * var layout = new OO.ui.HorizontalLayout( {
11206 * new OO.ui.LabelWidget( { label: 'Label' } ),
11207 * new OO.ui.TextInputWidget( { value: 'Text' } )
11210 * $( 'body' ).append( layout.$element );
11213 * @extends OO.ui.Layout
11214 * @mixins OO.ui.mixin.GroupElement
11217 * @param {Object} [config] Configuration options
11218 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
11220 OO
.ui
.HorizontalLayout
= function OoUiHorizontalLayout( config
) {
11221 // Configuration initialization
11222 config
= config
|| {};
11224 // Parent constructor
11225 OO
.ui
.HorizontalLayout
.parent
.call( this, config
);
11227 // Mixin constructors
11228 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
11231 this.$element
.addClass( 'oo-ui-horizontalLayout' );
11232 if ( Array
.isArray( config
.items
) ) {
11233 this.addItems( config
.items
);
11239 OO
.inheritClass( OO
.ui
.HorizontalLayout
, OO
.ui
.Layout
);
11240 OO
.mixinClass( OO
.ui
.HorizontalLayout
, OO
.ui
.mixin
.GroupElement
);
11244 //# sourceMappingURL=oojs-ui-core.js.map