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-04-26T01:05:10Z
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 .attr( 'role', '' );
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
6780 * @param {Object} [config] Configuration options
6781 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
6782 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
6783 * and {@link OO.ui.mixin.LookupElement LookupElement}
6784 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
6785 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiselectWidget CapsuleMultiselectWidget}
6786 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
6787 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
6788 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
6789 * that button, unless the button (or its parent widget) is passed in here.
6790 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
6791 * @cfg {jQuery} [$autoCloseIgnore] If these elements are clicked, don't auto-hide the menu.
6792 * @cfg {boolean} [hideOnChoose=true] Hide the menu when the user chooses an option.
6793 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
6794 * @cfg {boolean} [highlightOnFilter] Highlight the first result when filtering
6796 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
6797 // Configuration initialization
6798 config
= config
|| {};
6800 // Parent constructor
6801 OO
.ui
.MenuSelectWidget
.parent
.call( this, config
);
6803 // Mixin constructors
6804 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
6807 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
6808 this.hideOnChoose
= config
.hideOnChoose
=== undefined || !!config
.hideOnChoose
;
6809 this.filterFromInput
= !!config
.filterFromInput
;
6810 this.$input
= config
.$input
? config
.$input
: config
.input
? config
.input
.$input
: null;
6811 this.$widget
= config
.widget
? config
.widget
.$element
: null;
6812 this.$autoCloseIgnore
= config
.$autoCloseIgnore
|| $( [] );
6813 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
6814 this.onInputEditHandler
= OO
.ui
.debounce( this.updateItemVisibility
.bind( this ), 100 );
6815 this.highlightOnFilter
= !!config
.highlightOnFilter
;
6818 this.$element
.addClass( 'oo-ui-menuSelectWidget' );
6819 if ( config
.widget
) {
6820 this.setFocusOwner( config
.widget
.$tabIndexed
);
6823 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
6824 // that reference properties not initialized at that time of parent class construction
6825 // TODO: Find a better way to handle post-constructor setup
6826 this.visible
= false;
6827 this.$element
.addClass( 'oo-ui-element-hidden' );
6832 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
6833 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.ClippableElement
);
6838 * Handles document mouse down events.
6841 * @param {MouseEvent} e Mouse down event
6843 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
6847 this.$element
.add( this.$widget
).add( this.$autoCloseIgnore
).get(),
6852 this.toggle( false );
6859 OO
.ui
.MenuSelectWidget
.prototype.onKeyDown = function ( e
) {
6860 var currentItem
= this.getHighlightedItem() || this.getSelectedItem();
6862 if ( !this.isDisabled() && this.isVisible() ) {
6863 switch ( e
.keyCode
) {
6864 case OO
.ui
.Keys
.LEFT
:
6865 case OO
.ui
.Keys
.RIGHT
:
6866 // Do nothing if a text field is associated, arrow keys will be handled natively
6867 if ( !this.$input
) {
6868 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
6871 case OO
.ui
.Keys
.ESCAPE
:
6872 case OO
.ui
.Keys
.TAB
:
6873 if ( currentItem
) {
6874 currentItem
.setHighlighted( false );
6876 this.toggle( false );
6877 // Don't prevent tabbing away, prevent defocusing
6878 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
6880 e
.stopPropagation();
6884 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
6891 * Update menu item visibility after input changes.
6895 OO
.ui
.MenuSelectWidget
.prototype.updateItemVisibility = function () {
6896 var i
, item
, visible
, section
, sectionEmpty
,
6897 firstItemFound
= false,
6899 len
= this.items
.length
,
6900 showAll
= !this.isVisible(),
6901 filter
= showAll
? null : this.getItemMatcher( this.$input
.val() );
6903 // Hide non-matching options, and also hide section headers if all options
6904 // in their section are hidden.
6905 for ( i
= 0; i
< len
; i
++ ) {
6906 item
= this.items
[ i
];
6907 if ( item
instanceof OO
.ui
.MenuSectionOptionWidget
) {
6909 // If the previous section was empty, hide its header
6910 section
.toggle( showAll
|| !sectionEmpty
);
6913 sectionEmpty
= true;
6914 } else if ( item
instanceof OO
.ui
.OptionWidget
) {
6915 visible
= showAll
|| filter( item
);
6916 anyVisible
= anyVisible
|| visible
;
6917 sectionEmpty
= sectionEmpty
&& !visible
;
6918 item
.toggle( visible
);
6919 if ( this.highlightOnFilter
&& visible
&& !firstItemFound
) {
6920 // Highlight the first item in the list
6921 this.highlightItem( item
);
6922 firstItemFound
= true;
6926 // Process the final section
6928 section
.toggle( showAll
|| !sectionEmpty
);
6931 this.$element
.toggleClass( 'oo-ui-menuSelectWidget-invisible', !anyVisible
);
6933 // Reevaluate clipping
6940 OO
.ui
.MenuSelectWidget
.prototype.bindKeyDownListener = function () {
6941 if ( this.$input
) {
6942 this.$input
.on( 'keydown', this.onKeyDownHandler
);
6944 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyDownListener
.call( this );
6951 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyDownListener = function () {
6952 if ( this.$input
) {
6953 this.$input
.off( 'keydown', this.onKeyDownHandler
);
6955 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyDownListener
.call( this );
6962 OO
.ui
.MenuSelectWidget
.prototype.bindKeyPressListener = function () {
6963 if ( this.$input
) {
6964 if ( this.filterFromInput
) {
6965 this.$input
.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
6968 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyPressListener
.call( this );
6975 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyPressListener = function () {
6976 if ( this.$input
) {
6977 if ( this.filterFromInput
) {
6978 this.$input
.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
6979 this.updateItemVisibility();
6982 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyPressListener
.call( this );
6989 * When a user chooses an item, the menu is closed, unless the hideOnChoose config option is set to false.
6991 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
6992 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
6994 * @param {OO.ui.OptionWidget} item Item to choose
6997 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
6998 OO
.ui
.MenuSelectWidget
.parent
.prototype.chooseItem
.call( this, item
);
6999 if ( this.hideOnChoose
) {
7000 this.toggle( false );
7008 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
7010 OO
.ui
.MenuSelectWidget
.parent
.prototype.addItems
.call( this, items
, index
);
7012 // Reevaluate clipping
7021 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
7023 OO
.ui
.MenuSelectWidget
.parent
.prototype.removeItems
.call( this, items
);
7025 // Reevaluate clipping
7034 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
7036 OO
.ui
.MenuSelectWidget
.parent
.prototype.clearItems
.call( this );
7038 // Reevaluate clipping
7045 * Toggle visibility of the menu. The menu is initially hidden and must be shown by calling
7046 * `.toggle( true )` after its #$element is attached to the DOM.
7048 * Do not show the menu while it is not attached to the DOM. The calculations required to display
7049 * it in the right place and with the right dimensions only work correctly while it is attached.
7050 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
7051 * strictly enforced, so currently it only generates a warning in the browser console.
7055 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
7058 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
7059 change
= visible
!== this.isVisible();
7061 if ( visible
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
7062 OO
.ui
.warnDeprecation( 'MenuSelectWidget#toggle: Before calling this method, the menu must be attached to the DOM.' );
7063 this.warnedUnattached
= true;
7067 OO
.ui
.MenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
7071 this.bindKeyDownListener();
7072 this.bindKeyPressListener();
7074 this.toggleClipping( true );
7076 if ( this.getSelectedItem() ) {
7077 this.$focusOwner
.attr( 'aria-activedescendant', this.getSelectedItem().getElementId() );
7078 this.getSelectedItem().scrollElementIntoView( { duration
: 0 } );
7082 if ( this.autoHide
) {
7083 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
7086 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
7087 this.unbindKeyDownListener();
7088 this.unbindKeyPressListener();
7089 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
7090 this.toggleClipping( false );
7098 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
7099 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
7100 * users can interact with it.
7102 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7103 * OO.ui.DropdownInputWidget instead.
7106 * // Example: A DropdownWidget with a menu that contains three options
7107 * var dropDown = new OO.ui.DropdownWidget( {
7108 * label: 'Dropdown menu: Select a menu option',
7111 * new OO.ui.MenuOptionWidget( {
7115 * new OO.ui.MenuOptionWidget( {
7119 * new OO.ui.MenuOptionWidget( {
7127 * $( 'body' ).append( dropDown.$element );
7129 * dropDown.getMenu().selectItemByData( 'b' );
7131 * dropDown.getMenu().getSelectedItem().getData(); // returns 'b'
7133 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
7135 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
7138 * @extends OO.ui.Widget
7139 * @mixins OO.ui.mixin.IconElement
7140 * @mixins OO.ui.mixin.IndicatorElement
7141 * @mixins OO.ui.mixin.LabelElement
7142 * @mixins OO.ui.mixin.TitledElement
7143 * @mixins OO.ui.mixin.TabIndexedElement
7146 * @param {Object} [config] Configuration options
7147 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
7148 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
7149 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
7150 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
7151 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
7153 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
7154 // Configuration initialization
7155 config
= $.extend( { indicator
: 'down' }, config
);
7157 // Parent constructor
7158 OO
.ui
.DropdownWidget
.parent
.call( this, config
);
7160 // Properties (must be set before TabIndexedElement constructor call)
7161 this.$handle
= this.$( '<span>' );
7162 this.$overlay
= config
.$overlay
|| this.$element
;
7164 // Mixin constructors
7165 OO
.ui
.mixin
.IconElement
.call( this, config
);
7166 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
7167 OO
.ui
.mixin
.LabelElement
.call( this, config
);
7168 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
7169 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
7172 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend( {
7174 $container
: this.$element
7179 click
: this.onClick
.bind( this ),
7180 keydown
: this.onKeyDown
.bind( this ),
7181 // Hack? Handle type-to-search when menu is not expanded and not handling its own events
7182 keypress
: this.menu
.onKeyPressHandler
,
7183 blur
: this.menu
.clearKeyPressBuffer
.bind( this.menu
)
7185 this.menu
.connect( this, {
7186 select
: 'onMenuSelect',
7187 toggle
: 'onMenuToggle'
7192 .addClass( 'oo-ui-dropdownWidget-handle' )
7195 'aria-owns': this.menu
.getElementId(),
7196 'aria-autocomplete': 'list'
7198 .append( this.$icon
, this.$label
, this.$indicator
);
7200 .addClass( 'oo-ui-dropdownWidget' )
7201 .append( this.$handle
);
7202 this.$overlay
.append( this.menu
.$element
);
7207 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
7208 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IconElement
);
7209 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IndicatorElement
);
7210 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.LabelElement
);
7211 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TitledElement
);
7212 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TabIndexedElement
);
7219 * @return {OO.ui.MenuSelectWidget} Menu of widget
7221 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
7226 * Handles menu select events.
7229 * @param {OO.ui.MenuOptionWidget} item Selected menu item
7231 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
7235 this.setLabel( null );
7239 selectedLabel
= item
.getLabel();
7241 // If the label is a DOM element, clone it, because setLabel will append() it
7242 if ( selectedLabel
instanceof jQuery
) {
7243 selectedLabel
= selectedLabel
.clone();
7246 this.setLabel( selectedLabel
);
7250 * Handle menu toggle events.
7253 * @param {boolean} isVisible Menu toggle event
7255 OO
.ui
.DropdownWidget
.prototype.onMenuToggle = function ( isVisible
) {
7256 this.$element
.toggleClass( 'oo-ui-dropdownWidget-open', isVisible
);
7260 * Handle mouse click events.
7263 * @param {jQuery.Event} e Mouse click event
7265 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
7266 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
7273 * Handle key down events.
7276 * @param {jQuery.Event} e Key down event
7278 OO
.ui
.DropdownWidget
.prototype.onKeyDown = function ( e
) {
7280 !this.isDisabled() &&
7282 e
.which
=== OO
.ui
.Keys
.ENTER
||
7284 !this.menu
.isVisible() &&
7286 e
.which
=== OO
.ui
.Keys
.SPACE
||
7287 e
.which
=== OO
.ui
.Keys
.UP
||
7288 e
.which
=== OO
.ui
.Keys
.DOWN
7299 * RadioOptionWidget is an option widget that looks like a radio button.
7300 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
7301 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
7303 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
7306 * @extends OO.ui.OptionWidget
7309 * @param {Object} [config] Configuration options
7311 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
7312 // Configuration initialization
7313 config
= config
|| {};
7315 // Properties (must be done before parent constructor which calls #setDisabled)
7316 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
7318 // Parent constructor
7319 OO
.ui
.RadioOptionWidget
.parent
.call( this, config
);
7322 // Remove implicit role, we're handling it ourselves
7323 this.radio
.$input
.attr( 'role', 'presentation' );
7325 .addClass( 'oo-ui-radioOptionWidget' )
7326 .attr( 'role', 'radio' )
7327 .attr( 'aria-checked', 'false' )
7328 .removeAttr( 'aria-selected' )
7329 .prepend( this.radio
.$element
);
7334 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
7336 /* Static Properties */
7342 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
7348 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
7354 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
7360 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
7367 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
7368 OO
.ui
.RadioOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
7370 this.radio
.setSelected( state
);
7372 .attr( 'aria-checked', state
.toString() )
7373 .removeAttr( 'aria-selected' );
7381 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
7382 OO
.ui
.RadioOptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
7384 this.radio
.setDisabled( this.isDisabled() );
7390 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
7391 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
7392 * an interface for adding, removing and selecting options.
7393 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
7395 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7396 * OO.ui.RadioSelectInputWidget instead.
7399 * // A RadioSelectWidget with RadioOptions.
7400 * var option1 = new OO.ui.RadioOptionWidget( {
7402 * label: 'Selected radio option'
7405 * var option2 = new OO.ui.RadioOptionWidget( {
7407 * label: 'Unselected radio option'
7410 * var radioSelect=new OO.ui.RadioSelectWidget( {
7411 * items: [ option1, option2 ]
7414 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
7415 * radioSelect.selectItem( option1 );
7417 * $( 'body' ).append( radioSelect.$element );
7419 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
7423 * @extends OO.ui.SelectWidget
7424 * @mixins OO.ui.mixin.TabIndexedElement
7427 * @param {Object} [config] Configuration options
7429 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
7430 // Parent constructor
7431 OO
.ui
.RadioSelectWidget
.parent
.call( this, config
);
7433 // Mixin constructors
7434 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
7438 focus
: this.bindKeyDownListener
.bind( this ),
7439 blur
: this.unbindKeyDownListener
.bind( this )
7444 .addClass( 'oo-ui-radioSelectWidget' )
7445 .attr( 'role', 'radiogroup' );
7450 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
7451 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
7454 * MultioptionWidgets are special elements that can be selected and configured with data. The
7455 * data is often unique for each option, but it does not have to be. MultioptionWidgets are used
7456 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
7457 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
7459 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Multioptions
7462 * @extends OO.ui.Widget
7463 * @mixins OO.ui.mixin.ItemWidget
7464 * @mixins OO.ui.mixin.LabelElement
7467 * @param {Object} [config] Configuration options
7468 * @cfg {boolean} [selected=false] Whether the option is initially selected
7470 OO
.ui
.MultioptionWidget
= function OoUiMultioptionWidget( config
) {
7471 // Configuration initialization
7472 config
= config
|| {};
7474 // Parent constructor
7475 OO
.ui
.MultioptionWidget
.parent
.call( this, config
);
7477 // Mixin constructors
7478 OO
.ui
.mixin
.ItemWidget
.call( this );
7479 OO
.ui
.mixin
.LabelElement
.call( this, config
);
7482 this.selected
= null;
7486 .addClass( 'oo-ui-multioptionWidget' )
7487 .append( this.$label
);
7488 this.setSelected( config
.selected
);
7493 OO
.inheritClass( OO
.ui
.MultioptionWidget
, OO
.ui
.Widget
);
7494 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.ItemWidget
);
7495 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.LabelElement
);
7502 * A change event is emitted when the selected state of the option changes.
7504 * @param {boolean} selected Whether the option is now selected
7510 * Check if the option is selected.
7512 * @return {boolean} Item is selected
7514 OO
.ui
.MultioptionWidget
.prototype.isSelected = function () {
7515 return this.selected
;
7519 * Set the option’s selected state. In general, all modifications to the selection
7520 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
7521 * method instead of this method.
7523 * @param {boolean} [state=false] Select option
7526 OO
.ui
.MultioptionWidget
.prototype.setSelected = function ( state
) {
7528 if ( this.selected
!== state
) {
7529 this.selected
= state
;
7530 this.emit( 'change', state
);
7531 this.$element
.toggleClass( 'oo-ui-multioptionWidget-selected', state
);
7537 * MultiselectWidget allows selecting multiple options from a list.
7539 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
7541 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
7545 * @extends OO.ui.Widget
7546 * @mixins OO.ui.mixin.GroupWidget
7549 * @param {Object} [config] Configuration options
7550 * @cfg {OO.ui.MultioptionWidget[]} [items] An array of options to add to the multiselect.
7552 OO
.ui
.MultiselectWidget
= function OoUiMultiselectWidget( config
) {
7553 // Parent constructor
7554 OO
.ui
.MultiselectWidget
.parent
.call( this, config
);
7556 // Configuration initialization
7557 config
= config
|| {};
7559 // Mixin constructors
7560 OO
.ui
.mixin
.GroupWidget
.call( this, config
);
7563 this.aggregate( { change
: 'select' } );
7564 // This is mostly for compatibility with CapsuleMultiselectWidget... normally, 'change' is emitted
7565 // by GroupElement only when items are added/removed
7566 this.connect( this, { select
: [ 'emit', 'change' ] } );
7569 if ( config
.items
) {
7570 this.addItems( config
.items
);
7572 this.$group
.addClass( 'oo-ui-multiselectWidget-group' );
7573 this.$element
.addClass( 'oo-ui-multiselectWidget' )
7574 .append( this.$group
);
7579 OO
.inheritClass( OO
.ui
.MultiselectWidget
, OO
.ui
.Widget
);
7580 OO
.mixinClass( OO
.ui
.MultiselectWidget
, OO
.ui
.mixin
.GroupWidget
);
7587 * A change event is emitted when the set of items changes, or an item is selected or deselected.
7593 * A select event is emitted when an item is selected or deselected.
7599 * Get options that are selected.
7601 * @return {OO.ui.MultioptionWidget[]} Selected options
7603 OO
.ui
.MultiselectWidget
.prototype.getSelectedItems = function () {
7604 return this.items
.filter( function ( item
) {
7605 return item
.isSelected();
7610 * Get the data of options that are selected.
7612 * @return {Object[]|string[]} Values of selected options
7614 OO
.ui
.MultiselectWidget
.prototype.getSelectedItemsData = function () {
7615 return this.getSelectedItems().map( function ( item
) {
7621 * Select options by reference. Options not mentioned in the `items` array will be deselected.
7623 * @param {OO.ui.MultioptionWidget[]} items Items to select
7626 OO
.ui
.MultiselectWidget
.prototype.selectItems = function ( items
) {
7627 this.items
.forEach( function ( item
) {
7628 var selected
= items
.indexOf( item
) !== -1;
7629 item
.setSelected( selected
);
7635 * Select items by their data. Options not mentioned in the `datas` array will be deselected.
7637 * @param {Object[]|string[]} datas Values of items to select
7640 OO
.ui
.MultiselectWidget
.prototype.selectItemsByData = function ( datas
) {
7643 items
= datas
.map( function ( data
) {
7644 return widget
.getItemFromData( data
);
7646 this.selectItems( items
);
7651 * CheckboxMultioptionWidget is an option widget that looks like a checkbox.
7652 * The class is used with OO.ui.CheckboxMultiselectWidget to create a selection of checkbox options.
7653 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
7655 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
7658 * @extends OO.ui.MultioptionWidget
7661 * @param {Object} [config] Configuration options
7663 OO
.ui
.CheckboxMultioptionWidget
= function OoUiCheckboxMultioptionWidget( config
) {
7664 // Configuration initialization
7665 config
= config
|| {};
7667 // Properties (must be done before parent constructor which calls #setDisabled)
7668 this.checkbox
= new OO
.ui
.CheckboxInputWidget();
7670 // Parent constructor
7671 OO
.ui
.CheckboxMultioptionWidget
.parent
.call( this, config
);
7674 this.checkbox
.on( 'change', this.onCheckboxChange
.bind( this ) );
7675 this.$element
.on( 'keydown', this.onKeyDown
.bind( this ) );
7679 .addClass( 'oo-ui-checkboxMultioptionWidget' )
7680 .prepend( this.checkbox
.$element
);
7685 OO
.inheritClass( OO
.ui
.CheckboxMultioptionWidget
, OO
.ui
.MultioptionWidget
);
7687 /* Static Properties */
7693 OO
.ui
.CheckboxMultioptionWidget
.static.tagName
= 'label';
7698 * Handle checkbox selected state change.
7702 OO
.ui
.CheckboxMultioptionWidget
.prototype.onCheckboxChange = function () {
7703 this.setSelected( this.checkbox
.isSelected() );
7709 OO
.ui
.CheckboxMultioptionWidget
.prototype.setSelected = function ( state
) {
7710 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setSelected
.call( this, state
);
7711 this.checkbox
.setSelected( state
);
7718 OO
.ui
.CheckboxMultioptionWidget
.prototype.setDisabled = function ( disabled
) {
7719 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
7720 this.checkbox
.setDisabled( this.isDisabled() );
7727 OO
.ui
.CheckboxMultioptionWidget
.prototype.focus = function () {
7728 this.checkbox
.focus();
7732 * Handle key down events.
7735 * @param {jQuery.Event} e
7737 OO
.ui
.CheckboxMultioptionWidget
.prototype.onKeyDown = function ( e
) {
7739 element
= this.getElementGroup(),
7742 if ( e
.keyCode
=== OO
.ui
.Keys
.LEFT
|| e
.keyCode
=== OO
.ui
.Keys
.UP
) {
7743 nextItem
= element
.getRelativeFocusableItem( this, -1 );
7744 } else if ( e
.keyCode
=== OO
.ui
.Keys
.RIGHT
|| e
.keyCode
=== OO
.ui
.Keys
.DOWN
) {
7745 nextItem
= element
.getRelativeFocusableItem( this, 1 );
7755 * CheckboxMultiselectWidget is a {@link OO.ui.MultiselectWidget multiselect widget} that contains
7756 * checkboxes and is used together with OO.ui.CheckboxMultioptionWidget. The
7757 * CheckboxMultiselectWidget provides an interface for adding, removing and selecting options.
7758 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
7760 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7761 * OO.ui.CheckboxMultiselectInputWidget instead.
7764 * // A CheckboxMultiselectWidget with CheckboxMultioptions.
7765 * var option1 = new OO.ui.CheckboxMultioptionWidget( {
7768 * label: 'Selected checkbox'
7771 * var option2 = new OO.ui.CheckboxMultioptionWidget( {
7773 * label: 'Unselected checkbox'
7776 * var multiselect=new OO.ui.CheckboxMultiselectWidget( {
7777 * items: [ option1, option2 ]
7780 * $( 'body' ).append( multiselect.$element );
7782 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
7785 * @extends OO.ui.MultiselectWidget
7788 * @param {Object} [config] Configuration options
7790 OO
.ui
.CheckboxMultiselectWidget
= function OoUiCheckboxMultiselectWidget( config
) {
7791 // Parent constructor
7792 OO
.ui
.CheckboxMultiselectWidget
.parent
.call( this, config
);
7795 this.$lastClicked
= null;
7798 this.$group
.on( 'click', this.onClick
.bind( this ) );
7802 .addClass( 'oo-ui-checkboxMultiselectWidget' );
7807 OO
.inheritClass( OO
.ui
.CheckboxMultiselectWidget
, OO
.ui
.MultiselectWidget
);
7812 * Get an option by its position relative to the specified item (or to the start of the option array,
7813 * if item is `null`). The direction in which to search through the option array is specified with a
7814 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
7815 * `null` if there are no options in the array.
7817 * @param {OO.ui.CheckboxMultioptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
7818 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
7819 * @return {OO.ui.CheckboxMultioptionWidget|null} Item at position, `null` if there are no items in the select
7821 OO
.ui
.CheckboxMultiselectWidget
.prototype.getRelativeFocusableItem = function ( item
, direction
) {
7822 var currentIndex
, nextIndex
, i
,
7823 increase
= direction
> 0 ? 1 : -1,
7824 len
= this.items
.length
;
7827 currentIndex
= this.items
.indexOf( item
);
7828 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
7830 // If no item is selected and moving forward, start at the beginning.
7831 // If moving backward, start at the end.
7832 nextIndex
= direction
> 0 ? 0 : len
- 1;
7835 for ( i
= 0; i
< len
; i
++ ) {
7836 item
= this.items
[ nextIndex
];
7837 if ( item
&& !item
.isDisabled() ) {
7840 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
7846 * Handle click events on checkboxes.
7848 * @param {jQuery.Event} e
7850 OO
.ui
.CheckboxMultiselectWidget
.prototype.onClick = function ( e
) {
7851 var $options
, lastClickedIndex
, nowClickedIndex
, i
, direction
, wasSelected
, items
,
7852 $lastClicked
= this.$lastClicked
,
7853 $nowClicked
= $( e
.target
).closest( '.oo-ui-checkboxMultioptionWidget' )
7854 .not( '.oo-ui-widget-disabled' );
7856 // Allow selecting multiple options at once by Shift-clicking them
7857 if ( $lastClicked
&& $nowClicked
.length
&& e
.shiftKey
) {
7858 $options
= this.$group
.find( '.oo-ui-checkboxMultioptionWidget' );
7859 lastClickedIndex
= $options
.index( $lastClicked
);
7860 nowClickedIndex
= $options
.index( $nowClicked
);
7861 // If it's the same item, either the user is being silly, or it's a fake event generated by the
7862 // browser. In either case we don't need custom handling.
7863 if ( nowClickedIndex
!== lastClickedIndex
) {
7865 wasSelected
= items
[ nowClickedIndex
].isSelected();
7866 direction
= nowClickedIndex
> lastClickedIndex
? 1 : -1;
7868 // This depends on the DOM order of the items and the order of the .items array being the same.
7869 for ( i
= lastClickedIndex
; i
!== nowClickedIndex
; i
+= direction
) {
7870 if ( !items
[ i
].isDisabled() ) {
7871 items
[ i
].setSelected( !wasSelected
);
7874 // For the now-clicked element, use immediate timeout to allow the browser to do its own
7875 // handling first, then set our value. The order in which events happen is different for
7876 // clicks on the <input> and on the <label> and there are additional fake clicks fired for
7877 // non-click actions that change the checkboxes.
7879 setTimeout( function () {
7880 if ( !items
[ nowClickedIndex
].isDisabled() ) {
7881 items
[ nowClickedIndex
].setSelected( !wasSelected
);
7887 if ( $nowClicked
.length
) {
7888 this.$lastClicked
= $nowClicked
;
7893 * FloatingMenuSelectWidget is a menu that will stick under a specified
7894 * container, even when it is inserted elsewhere in the document (for example,
7895 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
7896 * menu from being clipped too aggresively.
7898 * The menu's position is automatically calculated and maintained when the menu
7899 * is toggled or the window is resized.
7901 * See OO.ui.ComboBoxInputWidget for an example of a widget that uses this class.
7904 * @extends OO.ui.MenuSelectWidget
7905 * @mixins OO.ui.mixin.FloatableElement
7908 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
7909 * Deprecated, omit this parameter and specify `$container` instead.
7910 * @param {Object} [config] Configuration options
7911 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
7912 * @cfg {number} [width] Width of the menu
7914 OO
.ui
.FloatingMenuSelectWidget
= function OoUiFloatingMenuSelectWidget( inputWidget
, config
) {
7915 // Allow 'inputWidget' parameter and config for backwards compatibility
7916 if ( OO
.isPlainObject( inputWidget
) && config
=== undefined ) {
7917 config
= inputWidget
;
7918 inputWidget
= config
.inputWidget
;
7921 // Configuration initialization
7922 config
= config
|| {};
7924 this.width
= config
.width
;
7926 // Parent constructor
7927 OO
.ui
.FloatingMenuSelectWidget
.parent
.call( this, config
);
7929 // Properties (must be set before mixin constructors)
7930 this.inputWidget
= inputWidget
; // For backwards compatibility
7931 this.$container
= config
.$container
|| this.inputWidget
.$element
;
7933 // Mixins constructors
7934 OO
.ui
.mixin
.FloatableElement
.call( this, $.extend( {}, config
, { $floatableContainer
: this.$container
} ) );
7937 this.$element
.addClass( 'oo-ui-floatingMenuSelectWidget' );
7938 // For backwards compatibility
7939 this.$element
.addClass( 'oo-ui-textInputMenuSelectWidget' );
7944 OO
.inheritClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.MenuSelectWidget
);
7945 OO
.mixinClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.mixin
.FloatableElement
);
7952 * The menu is ready: it is visible and has been positioned and clipped.
7961 OO
.ui
.FloatingMenuSelectWidget
.prototype.toggle = function ( visible
) {
7963 visible
= visible
=== undefined ? !this.isVisible() : !!visible
;
7964 change
= visible
!== this.isVisible();
7966 if ( change
&& visible
) {
7967 // Make sure the width is set before the parent method runs.
7968 this.setIdealSize( this.width
|| this.$container
.width() );
7972 // This will call this.clip(), which is nonsensical since we're not positioned yet...
7973 OO
.ui
.FloatingMenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
7976 this.togglePositioning( this.isVisible() );
7978 this.emit( 'ready' );
7986 * Progress bars visually display the status of an operation, such as a download,
7987 * and can be either determinate or indeterminate:
7989 * - **determinate** process bars show the percent of an operation that is complete.
7991 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
7992 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
7993 * not use percentages.
7995 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
7998 * // Examples of determinate and indeterminate progress bars.
7999 * var progressBar1 = new OO.ui.ProgressBarWidget( {
8002 * var progressBar2 = new OO.ui.ProgressBarWidget();
8004 * // Create a FieldsetLayout to layout progress bars
8005 * var fieldset = new OO.ui.FieldsetLayout;
8006 * fieldset.addItems( [
8007 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
8008 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
8010 * $( 'body' ).append( fieldset.$element );
8013 * @extends OO.ui.Widget
8016 * @param {Object} [config] Configuration options
8017 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
8018 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
8019 * By default, the progress bar is indeterminate.
8021 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
8022 // Configuration initialization
8023 config
= config
|| {};
8025 // Parent constructor
8026 OO
.ui
.ProgressBarWidget
.parent
.call( this, config
);
8029 this.$bar
= $( '<div>' );
8030 this.progress
= null;
8033 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
8034 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
8037 role
: 'progressbar',
8039 'aria-valuemax': 100
8041 .addClass( 'oo-ui-progressBarWidget' )
8042 .append( this.$bar
);
8047 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
8049 /* Static Properties */
8055 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
8060 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
8062 * @return {number|boolean} Progress percent
8064 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
8065 return this.progress
;
8069 * Set the percent of the process completed or `false` for an indeterminate process.
8071 * @param {number|boolean} progress Progress percent or `false` for indeterminate
8073 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
8074 this.progress
= progress
;
8076 if ( progress
!== false ) {
8077 this.$bar
.css( 'width', this.progress
+ '%' );
8078 this.$element
.attr( 'aria-valuenow', this.progress
);
8080 this.$bar
.css( 'width', '' );
8081 this.$element
.removeAttr( 'aria-valuenow' );
8083 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', progress
=== false );
8087 * InputWidget is the base class for all input widgets, which
8088 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
8089 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
8090 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
8092 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8096 * @extends OO.ui.Widget
8097 * @mixins OO.ui.mixin.FlaggedElement
8098 * @mixins OO.ui.mixin.TabIndexedElement
8099 * @mixins OO.ui.mixin.TitledElement
8100 * @mixins OO.ui.mixin.AccessKeyedElement
8103 * @param {Object} [config] Configuration options
8104 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
8105 * @cfg {string} [value=''] The value of the input.
8106 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
8107 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
8108 * before it is accepted.
8110 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
8111 // Configuration initialization
8112 config
= config
|| {};
8114 // Parent constructor
8115 OO
.ui
.InputWidget
.parent
.call( this, config
);
8118 // See #reusePreInfuseDOM about config.$input
8119 this.$input
= config
.$input
|| this.getInputElement( config
);
8121 this.inputFilter
= config
.inputFilter
;
8123 // Mixin constructors
8124 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
8125 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
8126 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
8127 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$input
} ) );
8130 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
8134 .addClass( 'oo-ui-inputWidget-input' )
8135 .attr( 'name', config
.name
)
8136 .prop( 'disabled', this.isDisabled() );
8138 .addClass( 'oo-ui-inputWidget' )
8139 .append( this.$input
);
8140 this.setValue( config
.value
);
8142 this.setDir( config
.dir
);
8148 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
8149 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.FlaggedElement
);
8150 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TabIndexedElement
);
8151 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TitledElement
);
8152 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
8154 /* Static Properties */
8160 OO
.ui
.InputWidget
.static.supportsSimpleLabel
= true;
8162 /* Static Methods */
8167 OO
.ui
.InputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
8168 config
= OO
.ui
.InputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
8169 // Reusing $input lets browsers preserve inputted values across page reloads (T114134)
8170 config
.$input
= $( node
).find( '.oo-ui-inputWidget-input' );
8177 OO
.ui
.InputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8178 var state
= OO
.ui
.InputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8179 if ( config
.$input
&& config
.$input
.length
) {
8180 state
.value
= config
.$input
.val();
8181 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
8182 state
.focus
= config
.$input
.is( ':focus' );
8192 * A change event is emitted when the value of the input changes.
8194 * @param {string} value
8200 * Get input element.
8202 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
8203 * different circumstances. The element must have a `value` property (like form elements).
8206 * @param {Object} config Configuration options
8207 * @return {jQuery} Input element
8209 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
8210 return $( '<input>' );
8214 * Get input element's ID.
8216 * If the element already has an ID then that is returned, otherwise unique ID is
8217 * generated, set on the element, and returned.
8219 * @return {string} The ID of the element
8221 OO
.ui
.InputWidget
.prototype.getInputId = function () {
8222 var id
= this.$input
.attr( 'id' );
8224 if ( id
=== undefined ) {
8225 id
= OO
.ui
.generateElementId();
8226 this.$input
.attr( 'id', id
);
8233 * Handle potentially value-changing events.
8236 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
8238 OO
.ui
.InputWidget
.prototype.onEdit = function () {
8240 if ( !this.isDisabled() ) {
8241 // Allow the stack to clear so the value will be updated
8242 setTimeout( function () {
8243 widget
.setValue( widget
.$input
.val() );
8249 * Get the value of the input.
8251 * @return {string} Input value
8253 OO
.ui
.InputWidget
.prototype.getValue = function () {
8254 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
8255 // it, and we won't know unless they're kind enough to trigger a 'change' event.
8256 var value
= this.$input
.val();
8257 if ( this.value
!== value
) {
8258 this.setValue( value
);
8264 * Set the directionality of the input.
8266 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
8269 OO
.ui
.InputWidget
.prototype.setDir = function ( dir
) {
8270 this.$input
.prop( 'dir', dir
);
8275 * Set the value of the input.
8277 * @param {string} value New value
8281 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
8282 value
= this.cleanUpValue( value
);
8283 // Update the DOM if it has changed. Note that with cleanUpValue, it
8284 // is possible for the DOM value to change without this.value changing.
8285 if ( this.$input
.val() !== value
) {
8286 this.$input
.val( value
);
8288 if ( this.value
!== value
) {
8290 this.emit( 'change', this.value
);
8296 * Clean up incoming value.
8298 * Ensures value is a string, and converts undefined and null to empty string.
8301 * @param {string} value Original value
8302 * @return {string} Cleaned up value
8304 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
8305 if ( value
=== undefined || value
=== null ) {
8307 } else if ( this.inputFilter
) {
8308 return this.inputFilter( String( value
) );
8310 return String( value
);
8315 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
8316 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
8319 OO
.ui
.InputWidget
.prototype.simulateLabelClick = function () {
8320 OO
.ui
.warnDeprecation( 'InputWidget: simulateLabelClick() is deprecated.' );
8321 if ( !this.isDisabled() ) {
8322 if ( this.$input
.is( ':checkbox, :radio' ) ) {
8323 this.$input
.click();
8325 if ( this.$input
.is( ':input' ) ) {
8326 this.$input
[ 0 ].focus();
8334 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
8335 OO
.ui
.InputWidget
.parent
.prototype.setDisabled
.call( this, state
);
8336 if ( this.$input
) {
8337 this.$input
.prop( 'disabled', this.isDisabled() );
8347 OO
.ui
.InputWidget
.prototype.focus = function () {
8348 this.$input
[ 0 ].focus();
8357 OO
.ui
.InputWidget
.prototype.blur = function () {
8358 this.$input
[ 0 ].blur();
8365 OO
.ui
.InputWidget
.prototype.restorePreInfuseState = function ( state
) {
8366 OO
.ui
.InputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
8367 if ( state
.value
!== undefined && state
.value
!== this.getValue() ) {
8368 this.setValue( state
.value
);
8370 if ( state
.focus
) {
8376 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
8377 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
8378 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
8379 * HTML `<button>` (the default) or an HTML `<input>` tags. See the
8380 * [OOjs UI documentation on MediaWiki] [1] for more information.
8383 * // A ButtonInputWidget rendered as an HTML button, the default.
8384 * var button = new OO.ui.ButtonInputWidget( {
8385 * label: 'Input button',
8389 * $( 'body' ).append( button.$element );
8391 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
8394 * @extends OO.ui.InputWidget
8395 * @mixins OO.ui.mixin.ButtonElement
8396 * @mixins OO.ui.mixin.IconElement
8397 * @mixins OO.ui.mixin.IndicatorElement
8398 * @mixins OO.ui.mixin.LabelElement
8399 * @mixins OO.ui.mixin.TitledElement
8402 * @param {Object} [config] Configuration options
8403 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
8404 * @cfg {boolean} [useInputTag=false] Use an `<input>` tag instead of a `<button>` tag, the default.
8405 * Widgets configured to be an `<input>` do not support {@link #icon icons} and {@link #indicator indicators},
8406 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
8407 * be set to `true` when there’s need to support IE 6 in a form with multiple buttons.
8409 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
8410 // Configuration initialization
8411 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
8413 // See InputWidget#reusePreInfuseDOM about config.$input
8414 if ( config
.$input
) {
8415 config
.$input
.empty();
8418 // Properties (must be set before parent constructor, which calls #setValue)
8419 this.useInputTag
= config
.useInputTag
;
8421 // Parent constructor
8422 OO
.ui
.ButtonInputWidget
.parent
.call( this, config
);
8424 // Mixin constructors
8425 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
8426 OO
.ui
.mixin
.IconElement
.call( this, config
);
8427 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
8428 OO
.ui
.mixin
.LabelElement
.call( this, config
);
8429 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
8432 if ( !config
.useInputTag
) {
8433 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
8435 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
8440 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
8441 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.ButtonElement
);
8442 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IconElement
);
8443 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
8444 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.LabelElement
);
8445 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.TitledElement
);
8447 /* Static Properties */
8450 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
8451 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
8456 OO
.ui
.ButtonInputWidget
.static.supportsSimpleLabel
= false;
8462 OO
.ui
.ButtonInputWidget
.static.tagName
= 'span';
8470 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
8472 type
= [ 'button', 'submit', 'reset' ].indexOf( config
.type
) !== -1 ? config
.type
: 'button';
8473 return $( '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + type
+ '">' );
8479 * If #useInputTag is `true`, the label is set as the `value` of the `<input>` tag.
8481 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
8482 * text, or `null` for no label
8485 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
8486 if ( typeof label
=== 'function' ) {
8487 label
= OO
.ui
.resolveMsg( label
);
8490 if ( this.useInputTag
) {
8491 // Discard non-plaintext labels
8492 if ( typeof label
!== 'string' ) {
8496 this.$input
.val( label
);
8499 return OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.call( this, label
);
8503 * Set the value of the input.
8505 * This method is disabled for button inputs configured as {@link #useInputTag <input> tags}, as
8506 * they do not support {@link #value values}.
8508 * @param {string} value New value
8511 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
8512 if ( !this.useInputTag
) {
8513 OO
.ui
.ButtonInputWidget
.parent
.prototype.setValue
.call( this, value
);
8519 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
8520 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
8521 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
8522 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
8524 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
8527 * // An example of selected, unselected, and disabled checkbox inputs
8528 * var checkbox1=new OO.ui.CheckboxInputWidget( {
8532 * var checkbox2=new OO.ui.CheckboxInputWidget( {
8535 * var checkbox3=new OO.ui.CheckboxInputWidget( {
8539 * // Create a fieldset layout with fields for each checkbox.
8540 * var fieldset = new OO.ui.FieldsetLayout( {
8541 * label: 'Checkboxes'
8543 * fieldset.addItems( [
8544 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
8545 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
8546 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
8548 * $( 'body' ).append( fieldset.$element );
8550 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8553 * @extends OO.ui.InputWidget
8556 * @param {Object} [config] Configuration options
8557 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
8559 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
8560 // Configuration initialization
8561 config
= config
|| {};
8563 // Parent constructor
8564 OO
.ui
.CheckboxInputWidget
.parent
.call( this, config
);
8568 .addClass( 'oo-ui-checkboxInputWidget' )
8569 // Required for pretty styling in MediaWiki theme
8570 .append( $( '<span>' ) );
8571 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
8576 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
8578 /* Static Properties */
8584 OO
.ui
.CheckboxInputWidget
.static.tagName
= 'span';
8586 /* Static Methods */
8591 OO
.ui
.CheckboxInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8592 var state
= OO
.ui
.CheckboxInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8593 state
.checked
= config
.$input
.prop( 'checked' );
8603 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
8604 return $( '<input>' ).attr( 'type', 'checkbox' );
8610 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
8612 if ( !this.isDisabled() ) {
8613 // Allow the stack to clear so the value will be updated
8614 setTimeout( function () {
8615 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
8621 * Set selection state of this checkbox.
8623 * @param {boolean} state `true` for selected
8626 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
8628 if ( this.selected
!== state
) {
8629 this.selected
= state
;
8630 this.$input
.prop( 'checked', this.selected
);
8631 this.emit( 'change', this.selected
);
8637 * Check if this checkbox is selected.
8639 * @return {boolean} Checkbox is selected
8641 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
8642 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
8643 // it, and we won't know unless they're kind enough to trigger a 'change' event.
8644 var selected
= this.$input
.prop( 'checked' );
8645 if ( this.selected
!== selected
) {
8646 this.setSelected( selected
);
8648 return this.selected
;
8654 OO
.ui
.CheckboxInputWidget
.prototype.restorePreInfuseState = function ( state
) {
8655 OO
.ui
.CheckboxInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
8656 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
8657 this.setSelected( state
.checked
);
8662 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
8663 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
8664 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
8665 * more information about input widgets.
8667 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
8668 * are no options. If no `value` configuration option is provided, the first option is selected.
8669 * If you need a state representing no value (no option being selected), use a DropdownWidget.
8671 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
8674 * // Example: A DropdownInputWidget with three options
8675 * var dropdownInput = new OO.ui.DropdownInputWidget( {
8677 * { data: 'a', label: 'First' },
8678 * { data: 'b', label: 'Second'},
8679 * { data: 'c', label: 'Third' }
8682 * $( 'body' ).append( dropdownInput.$element );
8684 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8687 * @extends OO.ui.InputWidget
8688 * @mixins OO.ui.mixin.TitledElement
8691 * @param {Object} [config] Configuration options
8692 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
8693 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
8695 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
8696 // Configuration initialization
8697 config
= config
|| {};
8699 // See InputWidget#reusePreInfuseDOM about config.$input
8700 if ( config
.$input
) {
8701 config
.$input
.addClass( 'oo-ui-element-hidden' );
8704 // Properties (must be done before parent constructor which calls #setDisabled)
8705 this.dropdownWidget
= new OO
.ui
.DropdownWidget( config
.dropdown
);
8707 // Parent constructor
8708 OO
.ui
.DropdownInputWidget
.parent
.call( this, config
);
8710 // Mixin constructors
8711 OO
.ui
.mixin
.TitledElement
.call( this, config
);
8714 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
8717 this.setOptions( config
.options
|| [] );
8719 .addClass( 'oo-ui-dropdownInputWidget' )
8720 .append( this.dropdownWidget
.$element
);
8721 this.setTabIndexedElement( null );
8726 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
8727 OO
.mixinClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.mixin
.TitledElement
);
8735 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
8736 return $( '<input>' ).attr( 'type', 'hidden' );
8740 * Handles menu select events.
8743 * @param {OO.ui.MenuOptionWidget} item Selected menu item
8745 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
8746 this.setValue( item
.getData() );
8752 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
8754 value
= this.cleanUpValue( value
);
8755 this.dropdownWidget
.getMenu().selectItemByData( value
);
8756 // Only allow setting values that are actually present in the dropdown
8757 selected
= this.dropdownWidget
.getMenu().getSelectedItem();
8758 value
= selected
? selected
.getData() : '';
8759 OO
.ui
.DropdownInputWidget
.parent
.prototype.setValue
.call( this, value
);
8766 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
8767 this.dropdownWidget
.setDisabled( state
);
8768 OO
.ui
.DropdownInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
8773 * Set the options available for this input.
8775 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
8778 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
8780 value
= this.getValue(),
8783 // Rebuild the dropdown menu
8784 this.dropdownWidget
.getMenu()
8786 .addItems( options
.map( function ( opt
) {
8787 var optValue
= widget
.cleanUpValue( opt
.data
);
8789 if ( opt
.optgroup
=== undefined ) {
8790 return new OO
.ui
.MenuOptionWidget( {
8792 label
: opt
.label
!== undefined ? opt
.label
: optValue
8795 return new OO
.ui
.MenuSectionOptionWidget( {
8801 // Restore the previous value, or reset to something sensible
8802 if ( this.dropdownWidget
.getMenu().getItemFromData( value
) ) {
8803 // Previous value is still available, ensure consistency with the dropdown
8804 this.setValue( value
);
8806 // No longer valid, reset
8807 if ( options
.length
) {
8808 this.setValue( options
[ 0 ].data
);
8818 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
8819 this.dropdownWidget
.getMenu().toggle( true );
8826 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
8827 this.dropdownWidget
.getMenu().toggle( false );
8832 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
8833 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
8834 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
8835 * please see the [OOjs UI documentation on MediaWiki][1].
8837 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
8840 * // An example of selected, unselected, and disabled radio inputs
8841 * var radio1 = new OO.ui.RadioInputWidget( {
8845 * var radio2 = new OO.ui.RadioInputWidget( {
8848 * var radio3 = new OO.ui.RadioInputWidget( {
8852 * // Create a fieldset layout with fields for each radio button.
8853 * var fieldset = new OO.ui.FieldsetLayout( {
8854 * label: 'Radio inputs'
8856 * fieldset.addItems( [
8857 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
8858 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
8859 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
8861 * $( 'body' ).append( fieldset.$element );
8863 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8866 * @extends OO.ui.InputWidget
8869 * @param {Object} [config] Configuration options
8870 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
8872 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
8873 // Configuration initialization
8874 config
= config
|| {};
8876 // Parent constructor
8877 OO
.ui
.RadioInputWidget
.parent
.call( this, config
);
8881 .addClass( 'oo-ui-radioInputWidget' )
8882 // Required for pretty styling in MediaWiki theme
8883 .append( $( '<span>' ) );
8884 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
8889 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
8891 /* Static Properties */
8897 OO
.ui
.RadioInputWidget
.static.tagName
= 'span';
8899 /* Static Methods */
8904 OO
.ui
.RadioInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8905 var state
= OO
.ui
.RadioInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8906 state
.checked
= config
.$input
.prop( 'checked' );
8916 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
8917 return $( '<input>' ).attr( 'type', 'radio' );
8923 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
8924 // RadioInputWidget doesn't track its state.
8928 * Set selection state of this radio button.
8930 * @param {boolean} state `true` for selected
8933 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
8934 // RadioInputWidget doesn't track its state.
8935 this.$input
.prop( 'checked', state
);
8940 * Check if this radio button is selected.
8942 * @return {boolean} Radio is selected
8944 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
8945 return this.$input
.prop( 'checked' );
8951 OO
.ui
.RadioInputWidget
.prototype.restorePreInfuseState = function ( state
) {
8952 OO
.ui
.RadioInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
8953 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
8954 this.setSelected( state
.checked
);
8959 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
8960 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
8961 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
8962 * more information about input widgets.
8964 * This and OO.ui.DropdownInputWidget support the same configuration options.
8967 * // Example: A RadioSelectInputWidget with three options
8968 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
8970 * { data: 'a', label: 'First' },
8971 * { data: 'b', label: 'Second'},
8972 * { data: 'c', label: 'Third' }
8975 * $( 'body' ).append( radioSelectInput.$element );
8977 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8980 * @extends OO.ui.InputWidget
8983 * @param {Object} [config] Configuration options
8984 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
8986 OO
.ui
.RadioSelectInputWidget
= function OoUiRadioSelectInputWidget( config
) {
8987 // Configuration initialization
8988 config
= config
|| {};
8990 // Properties (must be done before parent constructor which calls #setDisabled)
8991 this.radioSelectWidget
= new OO
.ui
.RadioSelectWidget();
8993 // Parent constructor
8994 OO
.ui
.RadioSelectInputWidget
.parent
.call( this, config
);
8997 this.radioSelectWidget
.connect( this, { select
: 'onMenuSelect' } );
9000 this.setOptions( config
.options
|| [] );
9002 .addClass( 'oo-ui-radioSelectInputWidget' )
9003 .append( this.radioSelectWidget
.$element
);
9004 this.setTabIndexedElement( null );
9009 OO
.inheritClass( OO
.ui
.RadioSelectInputWidget
, OO
.ui
.InputWidget
);
9011 /* Static Properties */
9017 OO
.ui
.RadioSelectInputWidget
.static.supportsSimpleLabel
= false;
9019 /* Static Methods */
9024 OO
.ui
.RadioSelectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9025 var state
= OO
.ui
.RadioSelectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9026 state
.value
= $( node
).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
9033 OO
.ui
.RadioSelectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
9034 config
= OO
.ui
.RadioSelectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
9035 // Cannot reuse the `<input type=radio>` set
9036 delete config
.$input
;
9046 OO
.ui
.RadioSelectInputWidget
.prototype.getInputElement = function () {
9047 return $( '<input>' ).attr( 'type', 'hidden' );
9051 * Handles menu select events.
9054 * @param {OO.ui.RadioOptionWidget} item Selected menu item
9056 OO
.ui
.RadioSelectInputWidget
.prototype.onMenuSelect = function ( item
) {
9057 this.setValue( item
.getData() );
9063 OO
.ui
.RadioSelectInputWidget
.prototype.setValue = function ( value
) {
9064 value
= this.cleanUpValue( value
);
9065 this.radioSelectWidget
.selectItemByData( value
);
9066 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setValue
.call( this, value
);
9073 OO
.ui
.RadioSelectInputWidget
.prototype.setDisabled = function ( state
) {
9074 this.radioSelectWidget
.setDisabled( state
);
9075 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
9080 * Set the options available for this input.
9082 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9085 OO
.ui
.RadioSelectInputWidget
.prototype.setOptions = function ( options
) {
9087 value
= this.getValue(),
9090 // Rebuild the radioSelect menu
9091 this.radioSelectWidget
9093 .addItems( options
.map( function ( opt
) {
9094 var optValue
= widget
.cleanUpValue( opt
.data
);
9095 return new OO
.ui
.RadioOptionWidget( {
9097 label
: opt
.label
!== undefined ? opt
.label
: optValue
9101 // Restore the previous value, or reset to something sensible
9102 if ( this.radioSelectWidget
.getItemFromData( value
) ) {
9103 // Previous value is still available, ensure consistency with the radioSelect
9104 this.setValue( value
);
9106 // No longer valid, reset
9107 if ( options
.length
) {
9108 this.setValue( options
[ 0 ].data
);
9116 * CheckboxMultiselectInputWidget is a
9117 * {@link OO.ui.CheckboxMultiselectWidget CheckboxMultiselectWidget} intended to be used within a
9118 * HTML form, such as a OO.ui.FormLayout. The selected values are synchronized with the value of
9119 * HTML `<input type=checkbox>` tags. Please see the [OOjs UI documentation on MediaWiki][1] for
9120 * more information about input widgets.
9123 * // Example: A CheckboxMultiselectInputWidget with three options
9124 * var multiselectInput = new OO.ui.CheckboxMultiselectInputWidget( {
9126 * { data: 'a', label: 'First' },
9127 * { data: 'b', label: 'Second'},
9128 * { data: 'c', label: 'Third' }
9131 * $( 'body' ).append( multiselectInput.$element );
9133 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9136 * @extends OO.ui.InputWidget
9139 * @param {Object} [config] Configuration options
9140 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: …, disabled: … }`
9142 OO
.ui
.CheckboxMultiselectInputWidget
= function OoUiCheckboxMultiselectInputWidget( config
) {
9143 // Configuration initialization
9144 config
= config
|| {};
9146 // Properties (must be done before parent constructor which calls #setDisabled)
9147 this.checkboxMultiselectWidget
= new OO
.ui
.CheckboxMultiselectWidget();
9149 // Parent constructor
9150 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.call( this, config
);
9153 this.inputName
= config
.name
;
9157 .addClass( 'oo-ui-checkboxMultiselectInputWidget' )
9158 .append( this.checkboxMultiselectWidget
.$element
);
9159 // We don't use this.$input, but rather the CheckboxInputWidgets inside each option
9160 this.$input
.detach();
9161 this.setOptions( config
.options
|| [] );
9162 // Have to repeat this from parent, as we need options to be set up for this to make sense
9163 this.setValue( config
.value
);
9168 OO
.inheritClass( OO
.ui
.CheckboxMultiselectInputWidget
, OO
.ui
.InputWidget
);
9170 /* Static Properties */
9176 OO
.ui
.CheckboxMultiselectInputWidget
.static.supportsSimpleLabel
= false;
9178 /* Static Methods */
9183 OO
.ui
.CheckboxMultiselectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9184 var state
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9185 state
.value
= $( node
).find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
9186 .toArray().map( function ( el
) { return el
.value
; } );
9193 OO
.ui
.CheckboxMultiselectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
9194 config
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
9195 // Cannot reuse the `<input type=checkbox>` set
9196 delete config
.$input
;
9206 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getInputElement = function () {
9208 return $( '<div>' );
9214 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getValue = function () {
9215 var value
= this.$element
.find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
9216 .toArray().map( function ( el
) { return el
.value
; } );
9217 if ( this.value
!== value
) {
9218 this.setValue( value
);
9226 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setValue = function ( value
) {
9227 value
= this.cleanUpValue( value
);
9228 this.checkboxMultiselectWidget
.selectItemsByData( value
);
9229 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setValue
.call( this, value
);
9234 * Clean up incoming value.
9236 * @param {string[]} value Original value
9237 * @return {string[]} Cleaned up value
9239 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.cleanUpValue = function ( value
) {
9242 if ( !Array
.isArray( value
) ) {
9245 for ( i
= 0; i
< value
.length
; i
++ ) {
9247 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
.call( this, value
[ i
] );
9248 // Remove options that we don't have here
9249 if ( !this.checkboxMultiselectWidget
.getItemFromData( singleValue
) ) {
9252 cleanValue
.push( singleValue
);
9260 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setDisabled = function ( state
) {
9261 this.checkboxMultiselectWidget
.setDisabled( state
);
9262 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
9267 * Set the options available for this input.
9269 * @param {Object[]} options Array of menu options in the format `{ data: …, label: …, disabled: … }`
9272 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setOptions = function ( options
) {
9275 // Rebuild the checkboxMultiselectWidget menu
9276 this.checkboxMultiselectWidget
9278 .addItems( options
.map( function ( opt
) {
9279 var optValue
, item
, optDisabled
;
9281 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
.call( widget
, opt
.data
);
9282 optDisabled
= opt
.disabled
!== undefined ? opt
.disabled
: false;
9283 item
= new OO
.ui
.CheckboxMultioptionWidget( {
9285 label
: opt
.label
!== undefined ? opt
.label
: optValue
,
9286 disabled
: optDisabled
9288 // Set the 'name' and 'value' for form submission
9289 item
.checkbox
.$input
.attr( 'name', widget
.inputName
);
9290 item
.checkbox
.setValue( optValue
);
9294 // Re-set the value, checking the checkboxes as needed.
9295 // This will also get rid of any stale options that we just removed.
9296 this.setValue( this.getValue() );
9302 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
9303 * size of the field as well as its presentation. In addition, these widgets can be configured
9304 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
9305 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
9306 * which modifies incoming values rather than validating them.
9307 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9309 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9312 * // Example of a text input widget
9313 * var textInput = new OO.ui.TextInputWidget( {
9314 * value: 'Text input'
9316 * $( 'body' ).append( textInput.$element );
9318 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9321 * @extends OO.ui.InputWidget
9322 * @mixins OO.ui.mixin.IconElement
9323 * @mixins OO.ui.mixin.IndicatorElement
9324 * @mixins OO.ui.mixin.PendingElement
9325 * @mixins OO.ui.mixin.LabelElement
9328 * @param {Object} [config] Configuration options
9329 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
9330 * 'email', 'url' or 'number'. Ignored if `multiline` is true.
9332 * Some values of `type` result in additional behaviors:
9334 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
9335 * empties the text field
9336 * @cfg {string} [placeholder] Placeholder text
9337 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
9338 * instruct the browser to focus this widget.
9339 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
9340 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
9341 * @cfg {boolean} [multiline=false] Allow multiple lines of text
9342 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
9343 * specifies minimum number of rows to display.
9344 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
9345 * Use the #maxRows config to specify a maximum number of displayed rows.
9346 * @cfg {number} [maxRows] Maximum number of rows to display when #autosize is set to true.
9347 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
9348 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
9349 * the value or placeholder text: `'before'` or `'after'`
9350 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
9351 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
9352 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
9353 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
9354 * (the value must contain only numbers); when RegExp, a regular expression that must match the
9355 * value for it to be considered valid; when Function, a function receiving the value as parameter
9356 * that must return true, or promise resolving to true, for it to be considered valid.
9358 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
9359 // Configuration initialization
9360 config
= $.extend( {
9362 labelPosition
: 'after'
9365 if ( config
.type
=== 'search' ) {
9366 OO
.ui
.warnDeprecation( 'TextInputWidget: config.type=\'search\' is deprecated. Use the SearchInputWidget instead. See T148471 for details.' );
9367 if ( config
.icon
=== undefined ) {
9368 config
.icon
= 'search';
9370 // indicator: 'clear' is set dynamically later, depending on value
9373 // Parent constructor
9374 OO
.ui
.TextInputWidget
.parent
.call( this, config
);
9376 // Mixin constructors
9377 OO
.ui
.mixin
.IconElement
.call( this, config
);
9378 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
9379 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$input
} ) );
9380 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9383 this.type
= this.getSaneType( config
);
9384 this.readOnly
= false;
9385 this.required
= false;
9386 this.multiline
= !!config
.multiline
;
9387 this.autosize
= !!config
.autosize
;
9388 this.minRows
= config
.rows
!== undefined ? config
.rows
: '';
9389 this.maxRows
= config
.maxRows
|| Math
.max( 2 * ( this.minRows
|| 0 ), 10 );
9390 this.validate
= null;
9391 this.styleHeight
= null;
9392 this.scrollWidth
= null;
9394 // Clone for resizing
9395 if ( this.autosize
) {
9396 this.$clone
= this.$input
9398 .insertAfter( this.$input
)
9399 .attr( 'aria-hidden', 'true' )
9400 .addClass( 'oo-ui-element-hidden' );
9403 this.setValidation( config
.validate
);
9404 this.setLabelPosition( config
.labelPosition
);
9408 keypress
: this.onKeyPress
.bind( this ),
9409 blur
: this.onBlur
.bind( this ),
9410 focus
: this.onFocus
.bind( this )
9412 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
9413 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
9414 this.on( 'labelChange', this.updatePosition
.bind( this ) );
9415 this.connect( this, {
9417 disable
: 'onDisable'
9419 this.on( 'change', OO
.ui
.debounce( this.onDebouncedChange
.bind( this ), 250 ) );
9423 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type
)
9424 .append( this.$icon
, this.$indicator
);
9425 this.setReadOnly( !!config
.readOnly
);
9426 this.setRequired( !!config
.required
);
9427 this.updateSearchIndicator();
9428 if ( config
.placeholder
!== undefined ) {
9429 this.$input
.attr( 'placeholder', config
.placeholder
);
9431 if ( config
.maxLength
!== undefined ) {
9432 this.$input
.attr( 'maxlength', config
.maxLength
);
9434 if ( config
.autofocus
) {
9435 this.$input
.attr( 'autofocus', 'autofocus' );
9437 if ( config
.autocomplete
=== false ) {
9438 this.$input
.attr( 'autocomplete', 'off' );
9439 // Turning off autocompletion also disables "form caching" when the user navigates to a
9440 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
9442 beforeunload: function () {
9443 this.$input
.removeAttr( 'autocomplete' );
9445 pageshow: function () {
9446 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
9447 // whole page... it shouldn't hurt, though.
9448 this.$input
.attr( 'autocomplete', 'off' );
9452 if ( this.multiline
&& config
.rows
) {
9453 this.$input
.attr( 'rows', config
.rows
);
9455 if ( this.label
|| config
.autosize
) {
9456 this.isWaitingToBeAttached
= true;
9457 this.installParentChangeDetector();
9463 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
9464 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IconElement
);
9465 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
9466 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.PendingElement
);
9467 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.LabelElement
);
9469 /* Static Properties */
9471 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
9476 /* Static Methods */
9481 OO
.ui
.TextInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9482 var state
= OO
.ui
.TextInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9483 if ( config
.multiline
) {
9484 state
.scrollTop
= config
.$input
.scrollTop();
9492 * An `enter` event is emitted when the user presses 'enter' inside the text box.
9494 * Not emitted if the input is multiline.
9500 * A `resize` event is emitted when autosize is set and the widget resizes
9508 * Handle icon mouse down events.
9511 * @param {jQuery.Event} e Mouse down event
9513 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
9514 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
9515 this.$input
[ 0 ].focus();
9521 * Handle indicator mouse down events.
9524 * @param {jQuery.Event} e Mouse down event
9526 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
9527 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
9528 if ( this.type
=== 'search' ) {
9529 // Clear the text field
9530 this.setValue( '' );
9532 this.$input
[ 0 ].focus();
9538 * Handle key press events.
9541 * @param {jQuery.Event} e Key press event
9542 * @fires enter If enter key is pressed and input is not multiline
9544 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
9545 if ( e
.which
=== OO
.ui
.Keys
.ENTER
&& !this.multiline
) {
9546 this.emit( 'enter', e
);
9551 * Handle blur events.
9554 * @param {jQuery.Event} e Blur event
9556 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
9557 this.setValidityFlag();
9561 * Handle focus events.
9564 * @param {jQuery.Event} e Focus event
9566 OO
.ui
.TextInputWidget
.prototype.onFocus = function () {
9567 if ( this.isWaitingToBeAttached
) {
9568 // If we've received focus, then we must be attached to the document, and if
9569 // isWaitingToBeAttached is still true, that means the handler never fired. Fire it now.
9570 this.onElementAttach();
9572 this.setValidityFlag( true );
9576 * Handle element attach events.
9579 * @param {jQuery.Event} e Element attach event
9581 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
9582 this.isWaitingToBeAttached
= false;
9583 // Any previously calculated size is now probably invalid if we reattached elsewhere
9584 this.valCache
= null;
9586 this.positionLabel();
9590 * Handle change events.
9592 * @param {string} value
9595 OO
.ui
.TextInputWidget
.prototype.onChange = function () {
9596 this.updateSearchIndicator();
9601 * Handle debounced change events.
9603 * @param {string} value
9606 OO
.ui
.TextInputWidget
.prototype.onDebouncedChange = function () {
9607 this.setValidityFlag();
9611 * Handle disable events.
9613 * @param {boolean} disabled Element is disabled
9616 OO
.ui
.TextInputWidget
.prototype.onDisable = function () {
9617 this.updateSearchIndicator();
9621 * Check if the input is {@link #readOnly read-only}.
9625 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
9626 return this.readOnly
;
9630 * Set the {@link #readOnly read-only} state of the input.
9632 * @param {boolean} state Make input read-only
9635 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
9636 this.readOnly
= !!state
;
9637 this.$input
.prop( 'readOnly', this.readOnly
);
9638 this.updateSearchIndicator();
9643 * Check if the input is {@link #required required}.
9647 OO
.ui
.TextInputWidget
.prototype.isRequired = function () {
9648 return this.required
;
9652 * Set the {@link #required required} state of the input.
9654 * @param {boolean} state Make input required
9657 OO
.ui
.TextInputWidget
.prototype.setRequired = function ( state
) {
9658 this.required
= !!state
;
9659 if ( this.required
) {
9661 .prop( 'required', true )
9662 .attr( 'aria-required', 'true' );
9663 if ( this.getIndicator() === null ) {
9664 this.setIndicator( 'required' );
9668 .prop( 'required', false )
9669 .removeAttr( 'aria-required' );
9670 if ( this.getIndicator() === 'required' ) {
9671 this.setIndicator( null );
9674 this.updateSearchIndicator();
9679 * Support function for making #onElementAttach work across browsers.
9681 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
9682 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
9684 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
9685 * first time that the element gets attached to the documented.
9687 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
9688 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
9689 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
9692 if ( MutationObserver
) {
9693 // The new way. If only it wasn't so ugly.
9695 if ( this.isElementAttached() ) {
9696 // Widget is attached already, do nothing. This breaks the functionality of this function when
9697 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
9698 // would require observation of the whole document, which would hurt performance of other,
9699 // more important code.
9703 // Find topmost node in the tree
9704 topmostNode
= this.$element
[ 0 ];
9705 while ( topmostNode
.parentNode
) {
9706 topmostNode
= topmostNode
.parentNode
;
9709 // We have no way to detect the $element being attached somewhere without observing the entire
9710 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
9711 // parent node of $element, and instead detect when $element is removed from it (and thus
9712 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
9713 // doesn't get attached, we end up back here and create the parent.
9715 mutationObserver
= new MutationObserver( function ( mutations
) {
9716 var i
, j
, removedNodes
;
9717 for ( i
= 0; i
< mutations
.length
; i
++ ) {
9718 removedNodes
= mutations
[ i
].removedNodes
;
9719 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
9720 if ( removedNodes
[ j
] === topmostNode
) {
9721 setTimeout( onRemove
, 0 );
9728 onRemove = function () {
9729 // If the node was attached somewhere else, report it
9730 if ( widget
.isElementAttached() ) {
9731 widget
.onElementAttach();
9733 mutationObserver
.disconnect();
9734 widget
.installParentChangeDetector();
9737 // Create a fake parent and observe it
9738 fakeParentNode
= $( '<div>' ).append( topmostNode
)[ 0 ];
9739 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
9741 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
9742 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
9743 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
9748 * Automatically adjust the size of the text input.
9750 * This only affects #multiline inputs that are {@link #autosize autosized}.
9755 OO
.ui
.TextInputWidget
.prototype.adjustSize = function () {
9756 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
,
9757 idealHeight
, newHeight
, scrollWidth
, property
;
9759 if ( this.isWaitingToBeAttached
) {
9760 // #onElementAttach will be called soon, which calls this method
9764 if ( this.multiline
&& this.$input
.val() !== this.valCache
) {
9765 if ( this.autosize
) {
9767 .val( this.$input
.val() )
9768 .attr( 'rows', this.minRows
)
9769 // Set inline height property to 0 to measure scroll height
9770 .css( 'height', 0 );
9772 this.$clone
.removeClass( 'oo-ui-element-hidden' );
9774 this.valCache
= this.$input
.val();
9776 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
9778 // Remove inline height property to measure natural heights
9779 this.$clone
.css( 'height', '' );
9780 innerHeight
= this.$clone
.innerHeight();
9781 outerHeight
= this.$clone
.outerHeight();
9783 // Measure max rows height
9785 .attr( 'rows', this.maxRows
)
9786 .css( 'height', 'auto' )
9788 maxInnerHeight
= this.$clone
.innerHeight();
9790 // Difference between reported innerHeight and scrollHeight with no scrollbars present.
9791 // This is sometimes non-zero on Blink-based browsers, depending on zoom level.
9792 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
9793 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
9795 this.$clone
.addClass( 'oo-ui-element-hidden' );
9797 // Only apply inline height when expansion beyond natural height is needed
9798 // Use the difference between the inner and outer height as a buffer
9799 newHeight
= idealHeight
> innerHeight
? idealHeight
+ ( outerHeight
- innerHeight
) : '';
9800 if ( newHeight
!== this.styleHeight
) {
9801 this.$input
.css( 'height', newHeight
);
9802 this.styleHeight
= newHeight
;
9803 this.emit( 'resize' );
9806 scrollWidth
= this.$input
[ 0 ].offsetWidth
- this.$input
[ 0 ].clientWidth
;
9807 if ( scrollWidth
!== this.scrollWidth
) {
9808 property
= this.$element
.css( 'direction' ) === 'rtl' ? 'left' : 'right';
9810 this.$label
.css( { right
: '', left
: '' } );
9811 this.$indicator
.css( { right
: '', left
: '' } );
9813 if ( scrollWidth
) {
9814 this.$indicator
.css( property
, scrollWidth
);
9815 if ( this.labelPosition
=== 'after' ) {
9816 this.$label
.css( property
, scrollWidth
);
9820 this.scrollWidth
= scrollWidth
;
9821 this.positionLabel();
9831 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
9832 if ( config
.multiline
) {
9833 return $( '<textarea>' );
9834 } else if ( this.getSaneType( config
) === 'number' ) {
9835 return $( '<input>' )
9836 .attr( 'step', 'any' )
9837 .attr( 'type', 'number' );
9839 return $( '<input>' ).attr( 'type', this.getSaneType( config
) );
9844 * Get sanitized value for 'type' for given config.
9846 * @param {Object} config Configuration options
9847 * @return {string|null}
9850 OO
.ui
.TextInputWidget
.prototype.getSaneType = function ( config
) {
9851 var allowedTypes
= [
9859 return allowedTypes
.indexOf( config
.type
) !== -1 ? config
.type
: 'text';
9863 * Check if the input supports multiple lines.
9867 OO
.ui
.TextInputWidget
.prototype.isMultiline = function () {
9868 return !!this.multiline
;
9872 * Check if the input automatically adjusts its size.
9876 OO
.ui
.TextInputWidget
.prototype.isAutosizing = function () {
9877 return !!this.autosize
;
9881 * Focus the input and select a specified range within the text.
9883 * @param {number} from Select from offset
9884 * @param {number} [to] Select to offset, defaults to from
9887 OO
.ui
.TextInputWidget
.prototype.selectRange = function ( from, to
) {
9888 var isBackwards
, start
, end
,
9889 input
= this.$input
[ 0 ];
9893 isBackwards
= to
< from;
9894 start
= isBackwards
? to
: from;
9895 end
= isBackwards
? from : to
;
9900 input
.setSelectionRange( start
, end
, isBackwards
? 'backward' : 'forward' );
9902 // IE throws an exception if you call setSelectionRange on a unattached DOM node.
9903 // Rather than expensively check if the input is attached every time, just check
9904 // if it was the cause of an error being thrown. If not, rethrow the error.
9905 if ( this.getElementDocument().body
.contains( input
) ) {
9913 * Get an object describing the current selection range in a directional manner
9915 * @return {Object} Object containing 'from' and 'to' offsets
9917 OO
.ui
.TextInputWidget
.prototype.getRange = function () {
9918 var input
= this.$input
[ 0 ],
9919 start
= input
.selectionStart
,
9920 end
= input
.selectionEnd
,
9921 isBackwards
= input
.selectionDirection
=== 'backward';
9924 from: isBackwards
? end
: start
,
9925 to
: isBackwards
? start
: end
9930 * Get the length of the text input value.
9932 * This could differ from the length of #getValue if the
9933 * value gets filtered
9935 * @return {number} Input length
9937 OO
.ui
.TextInputWidget
.prototype.getInputLength = function () {
9938 return this.$input
[ 0 ].value
.length
;
9942 * Focus the input and select the entire text.
9946 OO
.ui
.TextInputWidget
.prototype.select = function () {
9947 return this.selectRange( 0, this.getInputLength() );
9951 * Focus the input and move the cursor to the start.
9955 OO
.ui
.TextInputWidget
.prototype.moveCursorToStart = function () {
9956 return this.selectRange( 0 );
9960 * Focus the input and move the cursor to the end.
9964 OO
.ui
.TextInputWidget
.prototype.moveCursorToEnd = function () {
9965 return this.selectRange( this.getInputLength() );
9969 * Insert new content into the input.
9971 * @param {string} content Content to be inserted
9974 OO
.ui
.TextInputWidget
.prototype.insertContent = function ( content
) {
9976 range
= this.getRange(),
9977 value
= this.getValue();
9979 start
= Math
.min( range
.from, range
.to
);
9980 end
= Math
.max( range
.from, range
.to
);
9982 this.setValue( value
.slice( 0, start
) + content
+ value
.slice( end
) );
9983 this.selectRange( start
+ content
.length
);
9988 * Insert new content either side of a selection.
9990 * @param {string} pre Content to be inserted before the selection
9991 * @param {string} post Content to be inserted after the selection
9994 OO
.ui
.TextInputWidget
.prototype.encapsulateContent = function ( pre
, post
) {
9996 range
= this.getRange(),
9997 offset
= pre
.length
;
9999 start
= Math
.min( range
.from, range
.to
);
10000 end
= Math
.max( range
.from, range
.to
);
10002 this.selectRange( start
).insertContent( pre
);
10003 this.selectRange( offset
+ end
).insertContent( post
);
10005 this.selectRange( offset
+ start
, offset
+ end
);
10010 * Set the validation pattern.
10012 * The validation pattern is either a regular expression, a function, or the symbolic name of a
10013 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
10014 * value must contain only numbers).
10016 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
10017 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
10019 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
10020 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
10021 this.validate
= validate
;
10023 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
10028 * Sets the 'invalid' flag appropriately.
10030 * @param {boolean} [isValid] Optionally override validation result
10032 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
10034 setFlag = function ( valid
) {
10036 widget
.$input
.attr( 'aria-invalid', 'true' );
10038 widget
.$input
.removeAttr( 'aria-invalid' );
10040 widget
.setFlags( { invalid
: !valid
} );
10043 if ( isValid
!== undefined ) {
10044 setFlag( isValid
);
10046 this.getValidity().then( function () {
10055 * Get the validity of current value.
10057 * This method returns a promise that resolves if the value is valid and rejects if
10058 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
10060 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
10062 OO
.ui
.TextInputWidget
.prototype.getValidity = function () {
10065 function rejectOrResolve( valid
) {
10067 return $.Deferred().resolve().promise();
10069 return $.Deferred().reject().promise();
10073 // Check browser validity and reject if it is invalid
10075 this.$input
[ 0 ].checkValidity
!== undefined &&
10076 this.$input
[ 0 ].checkValidity() === false
10078 return rejectOrResolve( false );
10081 // Run our checks if the browser thinks the field is valid
10082 if ( this.validate
instanceof Function
) {
10083 result
= this.validate( this.getValue() );
10084 if ( result
&& $.isFunction( result
.promise
) ) {
10085 return result
.promise().then( function ( valid
) {
10086 return rejectOrResolve( valid
);
10089 return rejectOrResolve( result
);
10092 return rejectOrResolve( this.getValue().match( this.validate
) );
10097 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
10099 * @param {string} labelPosition Label position, 'before' or 'after'
10102 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
10103 this.labelPosition
= labelPosition
;
10104 if ( this.label
) {
10105 // If there is no label and we only change the position, #updatePosition is a no-op,
10106 // but it takes really a lot of work to do nothing.
10107 this.updatePosition();
10113 * Update the position of the inline label.
10115 * This method is called by #setLabelPosition, and can also be called on its own if
10116 * something causes the label to be mispositioned.
10120 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
10121 var after
= this.labelPosition
=== 'after';
10124 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
10125 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
10127 this.valCache
= null;
10128 this.scrollWidth
= null;
10130 this.positionLabel();
10136 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
10137 * already empty or when it's not editable.
10139 OO
.ui
.TextInputWidget
.prototype.updateSearchIndicator = function () {
10140 if ( this.type
=== 'search' ) {
10141 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
10142 this.setIndicator( null );
10144 this.setIndicator( 'clear' );
10150 * Position the label by setting the correct padding on the input.
10155 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
10156 var after
, rtl
, property
;
10158 if ( this.isWaitingToBeAttached
) {
10159 // #onElementAttach will be called soon, which calls this method
10163 // Clear old values
10165 // Clear old values if present
10167 'padding-right': '',
10171 if ( this.label
) {
10172 this.$element
.append( this.$label
);
10174 this.$label
.detach();
10178 after
= this.labelPosition
=== 'after';
10179 rtl
= this.$element
.css( 'direction' ) === 'rtl';
10180 property
= after
=== rtl
? 'padding-left' : 'padding-right';
10182 this.$input
.css( property
, this.$label
.outerWidth( true ) + ( after
? this.scrollWidth
: 0 ) );
10190 OO
.ui
.TextInputWidget
.prototype.restorePreInfuseState = function ( state
) {
10191 OO
.ui
.TextInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
10192 if ( state
.scrollTop
!== undefined ) {
10193 this.$input
.scrollTop( state
.scrollTop
);
10199 * @extends OO.ui.TextInputWidget
10202 * @param {Object} [config] Configuration options
10204 OO
.ui
.SearchInputWidget
= function OoUiSearchInputWidget( config
) {
10205 config
= $.extend( {
10209 // Set type to text so that TextInputWidget doesn't
10210 // get stuck in an infinite loop.
10211 config
.type
= 'text';
10213 // Parent constructor
10214 OO
.ui
.SearchInputWidget
.parent
.call( this, config
);
10217 this.$element
.addClass( 'oo-ui-textInputWidget-type-search' );
10218 this.updateSearchIndicator();
10219 this.connect( this, {
10220 disable
: 'onDisable'
10226 OO
.inheritClass( OO
.ui
.SearchInputWidget
, OO
.ui
.TextInputWidget
);
10234 OO
.ui
.SearchInputWidget
.prototype.getInputElement = function () {
10235 return $( '<input>' ).attr( 'type', 'search' );
10241 OO
.ui
.SearchInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
10242 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
10243 // Clear the text field
10244 this.setValue( '' );
10245 this.$input
[ 0 ].focus();
10251 * Update the 'clear' indicator displayed on type: 'search' text
10252 * fields, hiding it when the field is already empty or when it's not
10255 OO
.ui
.SearchInputWidget
.prototype.updateSearchIndicator = function () {
10256 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
10257 this.setIndicator( null );
10259 this.setIndicator( 'clear' );
10266 OO
.ui
.SearchInputWidget
.prototype.onChange = function () {
10267 OO
.ui
.SearchInputWidget
.parent
.prototype.onChange
.call( this );
10268 this.updateSearchIndicator();
10272 * Handle disable events.
10274 * @param {boolean} disabled Element is disabled
10277 OO
.ui
.SearchInputWidget
.prototype.onDisable = function () {
10278 this.updateSearchIndicator();
10284 OO
.ui
.SearchInputWidget
.prototype.setReadOnly = function ( state
) {
10285 OO
.ui
.SearchInputWidget
.parent
.prototype.setReadOnly
.call( this, state
);
10286 this.updateSearchIndicator();
10291 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
10292 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
10293 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
10295 * - by typing a value in the text input field. If the value exactly matches the value of a menu
10296 * option, that option will appear to be selected.
10297 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
10300 * After the user chooses an option, its `data` will be used as a new value for the widget.
10301 * A `label` also can be specified for each option: if given, it will be shown instead of the
10302 * `data` in the dropdown menu.
10304 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
10306 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
10309 * // Example: A ComboBoxInputWidget.
10310 * var comboBox = new OO.ui.ComboBoxInputWidget( {
10311 * value: 'Option 1',
10313 * { data: 'Option 1' },
10314 * { data: 'Option 2' },
10315 * { data: 'Option 3' }
10318 * $( 'body' ).append( comboBox.$element );
10321 * // Example: A ComboBoxInputWidget with additional option labels.
10322 * var comboBox = new OO.ui.ComboBoxInputWidget( {
10323 * value: 'Option 1',
10326 * data: 'Option 1',
10327 * label: 'Option One'
10330 * data: 'Option 2',
10331 * label: 'Option Two'
10334 * data: 'Option 3',
10335 * label: 'Option Three'
10339 * $( 'body' ).append( comboBox.$element );
10341 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
10344 * @extends OO.ui.TextInputWidget
10347 * @param {Object} [config] Configuration options
10348 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
10349 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
10350 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
10351 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
10352 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
10353 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
10355 OO
.ui
.ComboBoxInputWidget
= function OoUiComboBoxInputWidget( config
) {
10356 // Configuration initialization
10357 config
= $.extend( {
10358 autocomplete
: false
10361 // ComboBoxInputWidget shouldn't support `multiline`
10362 config
.multiline
= false;
10364 // See InputWidget#reusePreInfuseDOM about `config.$input`
10365 if ( config
.$input
) {
10366 config
.$input
.removeAttr( 'list' );
10369 // Parent constructor
10370 OO
.ui
.ComboBoxInputWidget
.parent
.call( this, config
);
10373 this.$overlay
= config
.$overlay
|| this.$element
;
10374 this.dropdownButton
= new OO
.ui
.ButtonWidget( {
10375 classes
: [ 'oo-ui-comboBoxInputWidget-dropdownButton' ],
10377 disabled
: this.disabled
10379 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend(
10383 $container
: this.$element
,
10384 disabled
: this.isDisabled()
10390 this.connect( this, {
10391 change
: 'onInputChange',
10392 enter
: 'onInputEnter'
10394 this.dropdownButton
.connect( this, {
10395 click
: 'onDropdownButtonClick'
10397 this.menu
.connect( this, {
10398 choose
: 'onMenuChoose',
10399 add
: 'onMenuItemsChange',
10400 remove
: 'onMenuItemsChange'
10404 this.$input
.attr( {
10406 'aria-owns': this.menu
.getElementId(),
10407 'aria-autocomplete': 'list'
10409 // Do not override options set via config.menu.items
10410 if ( config
.options
!== undefined ) {
10411 this.setOptions( config
.options
);
10413 this.$field
= $( '<div>' )
10414 .addClass( 'oo-ui-comboBoxInputWidget-field' )
10415 .append( this.$input
, this.dropdownButton
.$element
);
10417 .addClass( 'oo-ui-comboBoxInputWidget' )
10418 .append( this.$field
);
10419 this.$overlay
.append( this.menu
.$element
);
10420 this.onMenuItemsChange();
10425 OO
.inheritClass( OO
.ui
.ComboBoxInputWidget
, OO
.ui
.TextInputWidget
);
10430 * Get the combobox's menu.
10432 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
10434 OO
.ui
.ComboBoxInputWidget
.prototype.getMenu = function () {
10439 * Get the combobox's text input widget.
10441 * @return {OO.ui.TextInputWidget} Text input widget
10443 OO
.ui
.ComboBoxInputWidget
.prototype.getInput = function () {
10448 * Handle input change events.
10451 * @param {string} value New value
10453 OO
.ui
.ComboBoxInputWidget
.prototype.onInputChange = function ( value
) {
10454 var match
= this.menu
.getItemFromData( value
);
10456 this.menu
.selectItem( match
);
10457 if ( this.menu
.getHighlightedItem() ) {
10458 this.menu
.highlightItem( match
);
10461 if ( !this.isDisabled() ) {
10462 this.menu
.toggle( true );
10467 * Handle input enter events.
10471 OO
.ui
.ComboBoxInputWidget
.prototype.onInputEnter = function () {
10472 if ( !this.isDisabled() ) {
10473 this.menu
.toggle( false );
10478 * Handle button click events.
10482 OO
.ui
.ComboBoxInputWidget
.prototype.onDropdownButtonClick = function () {
10483 this.menu
.toggle();
10484 this.$input
[ 0 ].focus();
10488 * Handle menu choose events.
10491 * @param {OO.ui.OptionWidget} item Chosen item
10493 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuChoose = function ( item
) {
10494 this.setValue( item
.getData() );
10498 * Handle menu item change events.
10502 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuItemsChange = function () {
10503 var match
= this.menu
.getItemFromData( this.getValue() );
10504 this.menu
.selectItem( match
);
10505 if ( this.menu
.getHighlightedItem() ) {
10506 this.menu
.highlightItem( match
);
10508 this.$element
.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu
.isEmpty() );
10514 OO
.ui
.ComboBoxInputWidget
.prototype.setDisabled = function ( disabled
) {
10516 OO
.ui
.ComboBoxInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
10518 if ( this.dropdownButton
) {
10519 this.dropdownButton
.setDisabled( this.isDisabled() );
10522 this.menu
.setDisabled( this.isDisabled() );
10529 * Set the options available for this input.
10531 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10534 OO
.ui
.ComboBoxInputWidget
.prototype.setOptions = function ( options
) {
10537 .addItems( options
.map( function ( opt
) {
10538 return new OO
.ui
.MenuOptionWidget( {
10540 label
: opt
.label
!== undefined ? opt
.label
: opt
.data
10548 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
10549 * which is a widget that is specified by reference before any optional configuration settings.
10551 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
10553 * - **left**: The label is placed before the field-widget and aligned with the left margin.
10554 * A left-alignment is used for forms with many fields.
10555 * - **right**: The label is placed before the field-widget and aligned to the right margin.
10556 * A right-alignment is used for long but familiar forms which users tab through,
10557 * verifying the current field with a quick glance at the label.
10558 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
10559 * that users fill out from top to bottom.
10560 * - **inline**: The label is placed after the field-widget and aligned to the left.
10561 * An inline-alignment is best used with checkboxes or radio buttons.
10563 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
10564 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
10566 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
10569 * @extends OO.ui.Layout
10570 * @mixins OO.ui.mixin.LabelElement
10571 * @mixins OO.ui.mixin.TitledElement
10574 * @param {OO.ui.Widget} fieldWidget Field widget
10575 * @param {Object} [config] Configuration options
10576 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
10577 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
10578 * The array may contain strings or OO.ui.HtmlSnippet instances.
10579 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
10580 * The array may contain strings or OO.ui.HtmlSnippet instances.
10581 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
10582 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
10583 * For important messages, you are advised to use `notices`, as they are always shown.
10584 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
10585 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
10587 * @throws {Error} An error is thrown if no widget is specified
10589 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
10590 // Allow passing positional parameters inside the config object
10591 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
10592 config
= fieldWidget
;
10593 fieldWidget
= config
.fieldWidget
;
10596 // Make sure we have required constructor arguments
10597 if ( fieldWidget
=== undefined ) {
10598 throw new Error( 'Widget not found' );
10601 // Configuration initialization
10602 config
= $.extend( { align
: 'left' }, config
);
10604 // Parent constructor
10605 OO
.ui
.FieldLayout
.parent
.call( this, config
);
10607 // Mixin constructors
10608 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, {
10609 $label
: $( '<label>' )
10611 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
10614 this.fieldWidget
= fieldWidget
;
10617 this.$field
= this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
10618 this.$messages
= $( '<ul>' );
10619 this.$header
= $( '<span>' );
10620 this.$body
= $( '<div>' );
10622 if ( config
.help
) {
10623 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
10624 $overlay
: config
.$overlay
,
10628 classes
: [ 'oo-ui-fieldLayout-help' ],
10632 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
10633 this.popupButtonWidget
.getPopup().$body
.html( config
.help
.toString() );
10635 this.popupButtonWidget
.getPopup().$body
.text( config
.help
);
10637 this.$help
= this.popupButtonWidget
.$element
;
10639 this.$help
= $( [] );
10643 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
10646 if ( fieldWidget
.constructor.static.supportsSimpleLabel
) {
10647 if ( this.fieldWidget
.getInputId() ) {
10648 this.$label
.attr( 'for', this.fieldWidget
.getInputId() );
10650 this.$label
.on( 'click', function () {
10651 this.fieldWidget
.focus();
10657 .addClass( 'oo-ui-fieldLayout' )
10658 .toggleClass( 'oo-ui-fieldLayout-disabled', this.fieldWidget
.isDisabled() )
10659 .append( this.$body
);
10660 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
10661 this.$header
.addClass( 'oo-ui-fieldLayout-header' );
10662 this.$messages
.addClass( 'oo-ui-fieldLayout-messages' );
10664 .addClass( 'oo-ui-fieldLayout-field' )
10665 .append( this.fieldWidget
.$element
);
10667 this.setErrors( config
.errors
|| [] );
10668 this.setNotices( config
.notices
|| [] );
10669 this.setAlignment( config
.align
);
10674 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
10675 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.LabelElement
);
10676 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.TitledElement
);
10681 * Handle field disable events.
10684 * @param {boolean} value Field is disabled
10686 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
10687 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
10691 * Get the widget contained by the field.
10693 * @return {OO.ui.Widget} Field widget
10695 OO
.ui
.FieldLayout
.prototype.getField = function () {
10696 return this.fieldWidget
;
10700 * Return `true` if the given field widget can be used with `'inline'` alignment (see
10701 * #setAlignment). Return `false` if it can't or if this can't be determined.
10703 * @return {boolean}
10705 OO
.ui
.FieldLayout
.prototype.isFieldInline = function () {
10706 // This is very simplistic, but should be good enough.
10707 return this.getField().$element
.prop( 'tagName' ).toLowerCase() === 'span';
10712 * @param {string} kind 'error' or 'notice'
10713 * @param {string|OO.ui.HtmlSnippet} text
10716 OO
.ui
.FieldLayout
.prototype.makeMessage = function ( kind
, text
) {
10717 var $listItem
, $icon
, message
;
10718 $listItem
= $( '<li>' );
10719 if ( kind
=== 'error' ) {
10720 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'warning' ] } ).$element
;
10721 } else if ( kind
=== 'notice' ) {
10722 $icon
= new OO
.ui
.IconWidget( { icon
: 'info' } ).$element
;
10726 message
= new OO
.ui
.LabelWidget( { label
: text
} );
10728 .append( $icon
, message
.$element
)
10729 .addClass( 'oo-ui-fieldLayout-messages-' + kind
);
10734 * Set the field alignment mode.
10737 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
10740 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
10741 if ( value
!== this.align
) {
10742 // Default to 'left'
10743 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
10747 if ( value
=== 'inline' && !this.isFieldInline() ) {
10750 // Reorder elements
10751 if ( value
=== 'top' ) {
10752 this.$header
.append( this.$label
, this.$help
);
10753 this.$body
.append( this.$header
, this.$field
);
10754 } else if ( value
=== 'inline' ) {
10755 this.$header
.append( this.$label
, this.$help
);
10756 this.$body
.append( this.$field
, this.$header
);
10758 this.$header
.append( this.$label
);
10759 this.$body
.append( this.$header
, this.$help
, this.$field
);
10761 // Set classes. The following classes can be used here:
10762 // * oo-ui-fieldLayout-align-left
10763 // * oo-ui-fieldLayout-align-right
10764 // * oo-ui-fieldLayout-align-top
10765 // * oo-ui-fieldLayout-align-inline
10766 if ( this.align
) {
10767 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
10769 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
10770 this.align
= value
;
10777 * Set the list of error messages.
10779 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
10780 * The array may contain strings or OO.ui.HtmlSnippet instances.
10783 OO
.ui
.FieldLayout
.prototype.setErrors = function ( errors
) {
10784 this.errors
= errors
.slice();
10785 this.updateMessages();
10790 * Set the list of notice messages.
10792 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
10793 * The array may contain strings or OO.ui.HtmlSnippet instances.
10796 OO
.ui
.FieldLayout
.prototype.setNotices = function ( notices
) {
10797 this.notices
= notices
.slice();
10798 this.updateMessages();
10803 * Update the rendering of error and notice messages.
10807 OO
.ui
.FieldLayout
.prototype.updateMessages = function () {
10809 this.$messages
.empty();
10811 if ( this.errors
.length
|| this.notices
.length
) {
10812 this.$body
.after( this.$messages
);
10814 this.$messages
.remove();
10818 for ( i
= 0; i
< this.notices
.length
; i
++ ) {
10819 this.$messages
.append( this.makeMessage( 'notice', this.notices
[ i
] ) );
10821 for ( i
= 0; i
< this.errors
.length
; i
++ ) {
10822 this.$messages
.append( this.makeMessage( 'error', this.errors
[ i
] ) );
10827 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
10828 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
10829 * is required and is specified before any optional configuration settings.
10831 * Labels can be aligned in one of four ways:
10833 * - **left**: The label is placed before the field-widget and aligned with the left margin.
10834 * A left-alignment is used for forms with many fields.
10835 * - **right**: The label is placed before the field-widget and aligned to the right margin.
10836 * A right-alignment is used for long but familiar forms which users tab through,
10837 * verifying the current field with a quick glance at the label.
10838 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
10839 * that users fill out from top to bottom.
10840 * - **inline**: The label is placed after the field-widget and aligned to the left.
10841 * An inline-alignment is best used with checkboxes or radio buttons.
10843 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
10844 * text is specified.
10847 * // Example of an ActionFieldLayout
10848 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
10849 * new OO.ui.TextInputWidget( {
10850 * placeholder: 'Field widget'
10852 * new OO.ui.ButtonWidget( {
10856 * label: 'An ActionFieldLayout. This label is aligned top',
10858 * help: 'This is help text'
10862 * $( 'body' ).append( actionFieldLayout.$element );
10865 * @extends OO.ui.FieldLayout
10868 * @param {OO.ui.Widget} fieldWidget Field widget
10869 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
10870 * @param {Object} config
10872 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
10873 // Allow passing positional parameters inside the config object
10874 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
10875 config
= fieldWidget
;
10876 fieldWidget
= config
.fieldWidget
;
10877 buttonWidget
= config
.buttonWidget
;
10880 // Parent constructor
10881 OO
.ui
.ActionFieldLayout
.parent
.call( this, fieldWidget
, config
);
10884 this.buttonWidget
= buttonWidget
;
10885 this.$button
= $( '<span>' );
10886 this.$input
= this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
10890 .addClass( 'oo-ui-actionFieldLayout' );
10892 .addClass( 'oo-ui-actionFieldLayout-button' )
10893 .append( this.buttonWidget
.$element
);
10895 .addClass( 'oo-ui-actionFieldLayout-input' )
10896 .append( this.fieldWidget
.$element
);
10898 .append( this.$input
, this.$button
);
10903 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
10906 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
10907 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
10908 * configured with a label as well. For more information and examples,
10909 * please see the [OOjs UI documentation on MediaWiki][1].
10912 * // Example of a fieldset layout
10913 * var input1 = new OO.ui.TextInputWidget( {
10914 * placeholder: 'A text input field'
10917 * var input2 = new OO.ui.TextInputWidget( {
10918 * placeholder: 'A text input field'
10921 * var fieldset = new OO.ui.FieldsetLayout( {
10922 * label: 'Example of a fieldset layout'
10925 * fieldset.addItems( [
10926 * new OO.ui.FieldLayout( input1, {
10927 * label: 'Field One'
10929 * new OO.ui.FieldLayout( input2, {
10930 * label: 'Field Two'
10933 * $( 'body' ).append( fieldset.$element );
10935 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
10938 * @extends OO.ui.Layout
10939 * @mixins OO.ui.mixin.IconElement
10940 * @mixins OO.ui.mixin.LabelElement
10941 * @mixins OO.ui.mixin.GroupElement
10944 * @param {Object} [config] Configuration options
10945 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
10946 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
10947 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
10948 * For important messages, you are advised to use `notices`, as they are always shown.
10949 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
10950 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
10952 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
10953 // Configuration initialization
10954 config
= config
|| {};
10956 // Parent constructor
10957 OO
.ui
.FieldsetLayout
.parent
.call( this, config
);
10959 // Mixin constructors
10960 OO
.ui
.mixin
.IconElement
.call( this, config
);
10961 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: $( '<div>' ) } ) );
10962 OO
.ui
.mixin
.GroupElement
.call( this, config
);
10965 this.$header
= $( '<div>' );
10966 if ( config
.help
) {
10967 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
10968 $overlay
: config
.$overlay
,
10972 classes
: [ 'oo-ui-fieldsetLayout-help' ],
10976 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
10977 this.popupButtonWidget
.getPopup().$body
.html( config
.help
.toString() );
10979 this.popupButtonWidget
.getPopup().$body
.text( config
.help
);
10981 this.$help
= this.popupButtonWidget
.$element
;
10983 this.$help
= $( [] );
10988 .addClass( 'oo-ui-fieldsetLayout-header' )
10989 .append( this.$icon
, this.$label
, this.$help
);
10990 this.$group
.addClass( 'oo-ui-fieldsetLayout-group' );
10992 .addClass( 'oo-ui-fieldsetLayout' )
10993 .prepend( this.$header
, this.$group
);
10994 if ( Array
.isArray( config
.items
) ) {
10995 this.addItems( config
.items
);
11001 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
11002 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.IconElement
);
11003 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.LabelElement
);
11004 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.GroupElement
);
11006 /* Static Properties */
11012 OO
.ui
.FieldsetLayout
.static.tagName
= 'fieldset';
11015 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
11016 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
11017 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
11018 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
11020 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
11021 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
11022 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
11023 * some fancier controls. Some controls have both regular and InputWidget variants, for example
11024 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
11025 * often have simplified APIs to match the capabilities of HTML forms.
11026 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
11028 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
11029 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11032 * // Example of a form layout that wraps a fieldset layout
11033 * var input1 = new OO.ui.TextInputWidget( {
11034 * placeholder: 'Username'
11036 * var input2 = new OO.ui.TextInputWidget( {
11037 * placeholder: 'Password',
11040 * var submit = new OO.ui.ButtonInputWidget( {
11044 * var fieldset = new OO.ui.FieldsetLayout( {
11045 * label: 'A form layout'
11047 * fieldset.addItems( [
11048 * new OO.ui.FieldLayout( input1, {
11049 * label: 'Username',
11052 * new OO.ui.FieldLayout( input2, {
11053 * label: 'Password',
11056 * new OO.ui.FieldLayout( submit )
11058 * var form = new OO.ui.FormLayout( {
11059 * items: [ fieldset ],
11060 * action: '/api/formhandler',
11063 * $( 'body' ).append( form.$element );
11066 * @extends OO.ui.Layout
11067 * @mixins OO.ui.mixin.GroupElement
11070 * @param {Object} [config] Configuration options
11071 * @cfg {string} [method] HTML form `method` attribute
11072 * @cfg {string} [action] HTML form `action` attribute
11073 * @cfg {string} [enctype] HTML form `enctype` attribute
11074 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
11076 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
11079 // Configuration initialization
11080 config
= config
|| {};
11082 // Parent constructor
11083 OO
.ui
.FormLayout
.parent
.call( this, config
);
11085 // Mixin constructors
11086 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
11089 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
11091 // Make sure the action is safe
11092 action
= config
.action
;
11093 if ( action
!== undefined && !OO
.ui
.isSafeUrl( action
) ) {
11094 action
= './' + action
;
11099 .addClass( 'oo-ui-formLayout' )
11101 method
: config
.method
,
11103 enctype
: config
.enctype
11105 if ( Array
.isArray( config
.items
) ) {
11106 this.addItems( config
.items
);
11112 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
11113 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.mixin
.GroupElement
);
11118 * A 'submit' event is emitted when the form is submitted.
11123 /* Static Properties */
11129 OO
.ui
.FormLayout
.static.tagName
= 'form';
11134 * Handle form submit events.
11137 * @param {jQuery.Event} e Submit event
11140 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
11141 if ( this.emit( 'submit' ) ) {
11147 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
11148 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
11151 * // Example of a panel layout
11152 * var panel = new OO.ui.PanelLayout( {
11156 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
11158 * $( 'body' ).append( panel.$element );
11161 * @extends OO.ui.Layout
11164 * @param {Object} [config] Configuration options
11165 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
11166 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
11167 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
11168 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
11170 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
11171 // Configuration initialization
11172 config
= $.extend( {
11179 // Parent constructor
11180 OO
.ui
.PanelLayout
.parent
.call( this, config
);
11183 this.$element
.addClass( 'oo-ui-panelLayout' );
11184 if ( config
.scrollable
) {
11185 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
11187 if ( config
.padded
) {
11188 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
11190 if ( config
.expanded
) {
11191 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
11193 if ( config
.framed
) {
11194 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
11200 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
11205 * Focus the panel layout
11207 * The default implementation just focuses the first focusable element in the panel
11209 OO
.ui
.PanelLayout
.prototype.focus = function () {
11210 OO
.ui
.findFocusable( this.$element
).focus();
11214 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
11215 * items), with small margins between them. Convenient when you need to put a number of block-level
11216 * widgets on a single line next to each other.
11218 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
11221 * // HorizontalLayout with a text input and a label
11222 * var layout = new OO.ui.HorizontalLayout( {
11224 * new OO.ui.LabelWidget( { label: 'Label' } ),
11225 * new OO.ui.TextInputWidget( { value: 'Text' } )
11228 * $( 'body' ).append( layout.$element );
11231 * @extends OO.ui.Layout
11232 * @mixins OO.ui.mixin.GroupElement
11235 * @param {Object} [config] Configuration options
11236 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
11238 OO
.ui
.HorizontalLayout
= function OoUiHorizontalLayout( config
) {
11239 // Configuration initialization
11240 config
= config
|| {};
11242 // Parent constructor
11243 OO
.ui
.HorizontalLayout
.parent
.call( this, config
);
11245 // Mixin constructors
11246 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
11249 this.$element
.addClass( 'oo-ui-horizontalLayout' );
11250 if ( Array
.isArray( config
.items
) ) {
11251 this.addItems( config
.items
);
11257 OO
.inheritClass( OO
.ui
.HorizontalLayout
, OO
.ui
.Layout
);
11258 OO
.mixinClass( OO
.ui
.HorizontalLayout
, OO
.ui
.mixin
.GroupElement
);