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-02-28T23:19:40Z
16 * Namespace for all classes, static methods and static properties.
48 * Constants for MouseEvent.which
52 OO
.ui
.MouseButtons
= {
65 * Generate a unique ID for element
69 OO
.ui
.generateElementId = function () {
71 return 'oojsui-' + OO
.ui
.elementId
;
75 * Check if an element is focusable.
76 * Inspired from :focusable in jQueryUI v1.11.4 - 2015-04-14
78 * @param {jQuery} $element Element to test
81 OO
.ui
.isFocusableElement = function ( $element
) {
83 element
= $element
[ 0 ];
85 // Anything disabled is not focusable
86 if ( element
.disabled
) {
90 // Check if the element is visible
92 // This is quicker than calling $element.is( ':visible' )
93 $.expr
.filters
.visible( element
) &&
94 // Check that all parents are visible
95 !$element
.parents().addBack().filter( function () {
96 return $.css( this, 'visibility' ) === 'hidden';
102 // Check if the element is ContentEditable, which is the string 'true'
103 if ( element
.contentEditable
=== 'true' ) {
107 // Anything with a non-negative numeric tabIndex is focusable.
108 // Use .prop to avoid browser bugs
109 if ( $element
.prop( 'tabIndex' ) >= 0 ) {
113 // Some element types are naturally focusable
114 // (indexOf is much faster than regex in Chrome and about the
115 // same in FF: https://jsperf.com/regex-vs-indexof-array2)
116 nodeName
= element
.nodeName
.toLowerCase();
117 if ( [ 'input', 'select', 'textarea', 'button', 'object' ].indexOf( nodeName
) !== -1 ) {
121 // Links and areas are focusable if they have an href
122 if ( ( nodeName
=== 'a' || nodeName
=== 'area' ) && $element
.attr( 'href' ) !== undefined ) {
130 * Find a focusable child
132 * @param {jQuery} $container Container to search in
133 * @param {boolean} [backwards] Search backwards
134 * @return {jQuery} Focusable child, an empty jQuery object if none found
136 OO
.ui
.findFocusable = function ( $container
, backwards
) {
137 var $focusable
= $( [] ),
138 // $focusableCandidates is a superset of things that
139 // could get matched by isFocusableElement
140 $focusableCandidates
= $container
141 .find( 'input, select, textarea, button, object, a, area, [contenteditable], [tabindex]' );
144 $focusableCandidates
= Array
.prototype.reverse
.call( $focusableCandidates
);
147 $focusableCandidates
.each( function () {
148 var $this = $( this );
149 if ( OO
.ui
.isFocusableElement( $this ) ) {
158 * Get the user's language and any fallback languages.
160 * These language codes are used to localize user interface elements in the user's language.
162 * In environments that provide a localization system, this function should be overridden to
163 * return the user's language(s). The default implementation returns English (en) only.
165 * @return {string[]} Language codes, in descending order of priority
167 OO
.ui
.getUserLanguages = function () {
172 * Get a value in an object keyed by language code.
174 * @param {Object.<string,Mixed>} obj Object keyed by language code
175 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
176 * @param {string} [fallback] Fallback code, used if no matching language can be found
177 * @return {Mixed} Local value
179 OO
.ui
.getLocalValue = function ( obj
, lang
, fallback
) {
182 // Requested language
186 // Known user language
187 langs
= OO
.ui
.getUserLanguages();
188 for ( i
= 0, len
= langs
.length
; i
< len
; i
++ ) {
195 if ( obj
[ fallback
] ) {
196 return obj
[ fallback
];
198 // First existing language
199 for ( lang
in obj
) {
207 * Check if a node is contained within another node
209 * Similar to jQuery#contains except a list of containers can be supplied
210 * and a boolean argument allows you to include the container in the match list
212 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
213 * @param {HTMLElement} contained Node to find
214 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
215 * @return {boolean} The node is in the list of target nodes
217 OO
.ui
.contains = function ( containers
, contained
, matchContainers
) {
219 if ( !Array
.isArray( containers
) ) {
220 containers
= [ containers
];
222 for ( i
= containers
.length
- 1; i
>= 0; i
-- ) {
223 if ( ( matchContainers
&& contained
=== containers
[ i
] ) || $.contains( containers
[ i
], contained
) ) {
231 * Return a function, that, as long as it continues to be invoked, will not
232 * be triggered. The function will be called after it stops being called for
233 * N milliseconds. If `immediate` is passed, trigger the function on the
234 * leading edge, instead of the trailing.
236 * Ported from: http://underscorejs.org/underscore.js
238 * @param {Function} func
239 * @param {number} wait
240 * @param {boolean} immediate
243 OO
.ui
.debounce = function ( func
, wait
, immediate
) {
248 later = function () {
251 func
.apply( context
, args
);
254 if ( immediate
&& !timeout
) {
255 func
.apply( context
, args
);
257 if ( !timeout
|| wait
) {
258 clearTimeout( timeout
);
259 timeout
= setTimeout( later
, wait
);
265 * Puts a console warning with provided message.
267 * @param {string} message
269 OO
.ui
.warnDeprecation = function ( message
) {
270 if ( OO
.getProp( window
, 'console', 'warn' ) !== undefined ) {
271 // eslint-disable-next-line no-console
272 console
.warn( message
);
277 * Returns a function, that, when invoked, will only be triggered at most once
278 * during a given window of time. If called again during that window, it will
279 * wait until the window ends and then trigger itself again.
281 * As it's not knowable to the caller whether the function will actually run
282 * when the wrapper is called, return values from the function are entirely
285 * @param {Function} func
286 * @param {number} wait
289 OO
.ui
.throttle = function ( func
, wait
) {
290 var context
, args
, timeout
,
294 previous
= OO
.ui
.now();
295 func
.apply( context
, args
);
298 // Check how long it's been since the last time the function was
299 // called, and whether it's more or less than the requested throttle
300 // period. If it's less, run the function immediately. If it's more,
301 // set a timeout for the remaining time -- but don't replace an
302 // existing timeout, since that'd indefinitely prolong the wait.
303 var remaining
= wait
- ( OO
.ui
.now() - previous
);
306 if ( remaining
<= 0 ) {
307 // Note: unless wait was ridiculously large, this means we'll
308 // automatically run the first time the function was called in a
309 // given period. (If you provide a wait period larger than the
310 // current Unix timestamp, you *deserve* unexpected behavior.)
311 clearTimeout( timeout
);
313 } else if ( !timeout
) {
314 timeout
= setTimeout( run
, remaining
);
320 * A (possibly faster) way to get the current timestamp as an integer
322 * @return {number} Current timestamp
324 OO
.ui
.now
= Date
.now
|| function () {
325 return new Date().getTime();
329 * Reconstitute a JavaScript object corresponding to a widget created by
330 * the PHP implementation.
332 * This is an alias for `OO.ui.Element.static.infuse()`.
334 * @param {string|HTMLElement|jQuery} idOrNode
335 * A DOM id (if a string) or node for the widget to infuse.
336 * @return {OO.ui.Element}
337 * The `OO.ui.Element` corresponding to this (infusable) document node.
339 OO
.ui
.infuse = function ( idOrNode
) {
340 return OO
.ui
.Element
.static.infuse( idOrNode
);
345 * Message store for the default implementation of OO.ui.msg
347 * Environments that provide a localization system should not use this, but should override
348 * OO.ui.msg altogether.
353 // Tool tip for a button that moves items in a list down one place
354 'ooui-outline-control-move-down': 'Move item down',
355 // Tool tip for a button that moves items in a list up one place
356 'ooui-outline-control-move-up': 'Move item up',
357 // Tool tip for a button that removes items from a list
358 'ooui-outline-control-remove': 'Remove item',
359 // Label for the toolbar group that contains a list of all other available tools
360 'ooui-toolbar-more': 'More',
361 // Label for the fake tool that expands the full list of tools in a toolbar group
362 'ooui-toolgroup-expand': 'More',
363 // Label for the fake tool that collapses the full list of tools in a toolbar group
364 'ooui-toolgroup-collapse': 'Fewer',
365 // Default label for the accept button of a confirmation dialog
366 'ooui-dialog-message-accept': 'OK',
367 // Default label for the reject button of a confirmation dialog
368 'ooui-dialog-message-reject': 'Cancel',
369 // Title for process dialog error description
370 'ooui-dialog-process-error': 'Something went wrong',
371 // Label for process dialog dismiss error button, visible when describing errors
372 'ooui-dialog-process-dismiss': 'Dismiss',
373 // Label for process dialog retry action button, visible when describing only recoverable errors
374 'ooui-dialog-process-retry': 'Try again',
375 // Label for process dialog retry action button, visible when describing only warnings
376 'ooui-dialog-process-continue': 'Continue',
377 // Label for the file selection widget's select file button
378 'ooui-selectfile-button-select': 'Select a file',
379 // Label for the file selection widget if file selection is not supported
380 'ooui-selectfile-not-supported': 'File selection is not supported',
381 // Label for the file selection widget when no file is currently selected
382 'ooui-selectfile-placeholder': 'No file is selected',
383 // Label for the file selection widget's drop target
384 'ooui-selectfile-dragdrop-placeholder': 'Drop file here'
388 * Get a localized message.
390 * After the message key, message parameters may optionally be passed. In the default implementation,
391 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
392 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
393 * they support unnamed, ordered message parameters.
395 * In environments that provide a localization system, this function should be overridden to
396 * return the message translated in the user's language. The default implementation always returns
397 * English messages. An example of doing this with [jQuery.i18n](https://github.com/wikimedia/jquery.i18n)
401 * var i, iLen, button,
402 * messagePath = 'oojs-ui/dist/i18n/',
403 * languages = [ $.i18n().locale, 'ur', 'en' ],
406 * for ( i = 0, iLen = languages.length; i < iLen; i++ ) {
407 * languageMap[ languages[ i ] ] = messagePath + languages[ i ].toLowerCase() + '.json';
410 * $.i18n().load( languageMap ).done( function() {
411 * // Replace the built-in `msg` only once we've loaded the internationalization.
412 * // OOjs UI uses `OO.ui.deferMsg` for all initially-loaded messages. So long as
413 * // you put off creating any widgets until this promise is complete, no English
414 * // will be displayed.
415 * OO.ui.msg = $.i18n;
417 * // A button displaying "OK" in the default locale
418 * button = new OO.ui.ButtonWidget( {
419 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
422 * $( 'body' ).append( button.$element );
424 * // A button displaying "OK" in Urdu
425 * $.i18n().locale = 'ur';
426 * button = new OO.ui.ButtonWidget( {
427 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
430 * $( 'body' ).append( button.$element );
433 * @param {string} key Message key
434 * @param {...Mixed} [params] Message parameters
435 * @return {string} Translated message with parameters substituted
437 OO
.ui
.msg = function ( key
) {
438 var message
= messages
[ key
],
439 params
= Array
.prototype.slice
.call( arguments
, 1 );
440 if ( typeof message
=== 'string' ) {
441 // Perform $1 substitution
442 message
= message
.replace( /\$(\d+)/g, function ( unused
, n
) {
443 var i
= parseInt( n
, 10 );
444 return params
[ i
- 1 ] !== undefined ? params
[ i
- 1 ] : '$' + n
;
447 // Return placeholder if message not found
448 message
= '[' + key
+ ']';
455 * Package a message and arguments for deferred resolution.
457 * Use this when you are statically specifying a message and the message may not yet be present.
459 * @param {string} key Message key
460 * @param {...Mixed} [params] Message parameters
461 * @return {Function} Function that returns the resolved message when executed
463 OO
.ui
.deferMsg = function () {
464 var args
= arguments
;
466 return OO
.ui
.msg
.apply( OO
.ui
, args
);
473 * If the message is a function it will be executed, otherwise it will pass through directly.
475 * @param {Function|string} msg Deferred message, or message text
476 * @return {string} Resolved message
478 OO
.ui
.resolveMsg = function ( msg
) {
479 if ( $.isFunction( msg
) ) {
486 * @param {string} url
489 OO
.ui
.isSafeUrl = function ( url
) {
490 // Keep this function in sync with php/Tag.php
491 var i
, protocolWhitelist
;
493 function stringStartsWith( haystack
, needle
) {
494 return haystack
.substr( 0, needle
.length
) === needle
;
497 protocolWhitelist
= [
498 'bitcoin', 'ftp', 'ftps', 'geo', 'git', 'gopher', 'http', 'https', 'irc', 'ircs',
499 'magnet', 'mailto', 'mms', 'news', 'nntp', 'redis', 'sftp', 'sip', 'sips', 'sms', 'ssh',
500 'svn', 'tel', 'telnet', 'urn', 'worldwind', 'xmpp'
507 for ( i
= 0; i
< protocolWhitelist
.length
; i
++ ) {
508 if ( stringStartsWith( url
, protocolWhitelist
[ i
] + ':' ) ) {
513 // This matches '//' too
514 if ( stringStartsWith( url
, '/' ) || stringStartsWith( url
, './' ) ) {
517 if ( stringStartsWith( url
, '?' ) || stringStartsWith( url
, '#' ) ) {
525 * Check if the user has a 'mobile' device.
527 * For our purposes this means the user is primarily using an
528 * on-screen keyboard, touch input instead of a mouse and may
529 * have a physically small display.
531 * It is left up to implementors to decide how to compute this
532 * so the default implementation always returns false.
534 * @return {boolean} Use is on a mobile device
536 OO
.ui
.isMobile = function () {
545 * Namespace for OOjs UI mixins.
547 * Mixins are named according to the type of object they are intended to
548 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
549 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
550 * is intended to be mixed in to an instance of OO.ui.Widget.
558 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
559 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
560 * connected to them and can't be interacted with.
566 * @param {Object} [config] Configuration options
567 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
568 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
570 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
571 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
572 * @cfg {string} [text] Text to insert
573 * @cfg {Array} [content] An array of content elements to append (after #text).
574 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
575 * Instances of OO.ui.Element will have their $element appended.
576 * @cfg {jQuery} [$content] Content elements to append (after #text).
577 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
578 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
579 * Data can also be specified with the #setData method.
581 OO
.ui
.Element
= function OoUiElement( config
) {
582 // Configuration initialization
583 config
= config
|| {};
588 this.data
= config
.data
;
589 this.$element
= config
.$element
||
590 $( document
.createElement( this.getTagName() ) );
591 this.elementGroup
= null;
594 if ( Array
.isArray( config
.classes
) ) {
595 this.$element
.addClass( config
.classes
.join( ' ' ) );
598 this.$element
.attr( 'id', config
.id
);
601 this.$element
.text( config
.text
);
603 if ( config
.content
) {
604 // The `content` property treats plain strings as text; use an
605 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
606 // appropriate $element appended.
607 this.$element
.append( config
.content
.map( function ( v
) {
608 if ( typeof v
=== 'string' ) {
609 // Escape string so it is properly represented in HTML.
610 return document
.createTextNode( v
);
611 } else if ( v
instanceof OO
.ui
.HtmlSnippet
) {
614 } else if ( v
instanceof OO
.ui
.Element
) {
620 if ( config
.$content
) {
621 // The `$content` property treats plain strings as HTML.
622 this.$element
.append( config
.$content
);
628 OO
.initClass( OO
.ui
.Element
);
630 /* Static Properties */
633 * The name of the HTML tag used by the element.
635 * The static value may be ignored if the #getTagName method is overridden.
641 OO
.ui
.Element
.static.tagName
= 'div';
646 * Reconstitute a JavaScript object corresponding to a widget created
647 * by the PHP implementation.
649 * @param {string|HTMLElement|jQuery} idOrNode
650 * A DOM id (if a string) or node for the widget to infuse.
651 * @return {OO.ui.Element}
652 * The `OO.ui.Element` corresponding to this (infusable) document node.
653 * For `Tag` objects emitted on the HTML side (used occasionally for content)
654 * the value returned is a newly-created Element wrapping around the existing
657 OO
.ui
.Element
.static.infuse = function ( idOrNode
) {
658 var obj
= OO
.ui
.Element
.static.unsafeInfuse( idOrNode
, false );
659 // Verify that the type matches up.
660 // FIXME: uncomment after T89721 is fixed (see T90929)
662 if ( !( obj instanceof this['class'] ) ) {
663 throw new Error( 'Infusion type mismatch!' );
670 * Implementation helper for `infuse`; skips the type check and has an
671 * extra property so that only the top-level invocation touches the DOM.
674 * @param {string|HTMLElement|jQuery} idOrNode
675 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
676 * when the top-level widget of this infusion is inserted into DOM,
677 * replacing the original node; or false for top-level invocation.
678 * @return {OO.ui.Element}
680 OO
.ui
.Element
.static.unsafeInfuse = function ( idOrNode
, domPromise
) {
681 // look for a cached result of a previous infusion.
682 var id
, $elem
, data
, cls
, parts
, parent
, obj
, top
, state
, infusedChildren
;
683 if ( typeof idOrNode
=== 'string' ) {
685 $elem
= $( document
.getElementById( id
) );
687 $elem
= $( idOrNode
);
688 id
= $elem
.attr( 'id' );
690 if ( !$elem
.length
) {
691 throw new Error( 'Widget not found: ' + id
);
693 if ( $elem
[ 0 ].oouiInfused
) {
694 $elem
= $elem
[ 0 ].oouiInfused
;
696 data
= $elem
.data( 'ooui-infused' );
699 if ( data
=== true ) {
700 throw new Error( 'Circular dependency! ' + id
);
703 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
704 state
= data
.constructor.static.gatherPreInfuseState( $elem
, data
);
705 // restore dynamic state after the new element is re-inserted into DOM under infused parent
706 domPromise
.done( data
.restorePreInfuseState
.bind( data
, state
) );
707 infusedChildren
= $elem
.data( 'ooui-infused-children' );
708 if ( infusedChildren
&& infusedChildren
.length
) {
709 infusedChildren
.forEach( function ( data
) {
710 var state
= data
.constructor.static.gatherPreInfuseState( $elem
, data
);
711 domPromise
.done( data
.restorePreInfuseState
.bind( data
, state
) );
717 data
= $elem
.attr( 'data-ooui' );
719 throw new Error( 'No infusion data found: ' + id
);
722 data
= $.parseJSON( data
);
726 if ( !( data
&& data
._
) ) {
727 throw new Error( 'No valid infusion data found: ' + id
);
729 if ( data
._
=== 'Tag' ) {
730 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
731 return new OO
.ui
.Element( { $element
: $elem
} );
733 parts
= data
._
.split( '.' );
734 cls
= OO
.getProp
.apply( OO
, [ window
].concat( parts
) );
735 if ( cls
=== undefined ) {
736 // The PHP output might be old and not including the "OO.ui" prefix
737 // TODO: Remove this back-compat after next major release
738 cls
= OO
.getProp
.apply( OO
, [ OO
.ui
].concat( parts
) );
739 if ( cls
=== undefined ) {
740 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
744 // Verify that we're creating an OO.ui.Element instance
747 while ( parent
!== undefined ) {
748 if ( parent
=== OO
.ui
.Element
) {
753 parent
= parent
.parent
;
756 if ( parent
!== OO
.ui
.Element
) {
757 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
760 if ( domPromise
=== false ) {
762 domPromise
= top
.promise();
764 $elem
.data( 'ooui-infused', true ); // prevent loops
765 data
.id
= id
; // implicit
766 infusedChildren
= [];
767 data
= OO
.copy( data
, null, function deserialize( value
) {
769 if ( OO
.isPlainObject( value
) ) {
771 infused
= OO
.ui
.Element
.static.unsafeInfuse( value
.tag
, domPromise
);
772 infusedChildren
.push( infused
);
773 // Flatten the structure
774 infusedChildren
.push
.apply( infusedChildren
, infused
.$element
.data( 'ooui-infused-children' ) || [] );
775 infused
.$element
.removeData( 'ooui-infused-children' );
778 if ( value
.html
!== undefined ) {
779 return new OO
.ui
.HtmlSnippet( value
.html
);
783 // allow widgets to reuse parts of the DOM
784 data
= cls
.static.reusePreInfuseDOM( $elem
[ 0 ], data
);
785 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
786 state
= cls
.static.gatherPreInfuseState( $elem
[ 0 ], data
);
788 // eslint-disable-next-line new-cap
789 obj
= new cls( data
);
790 // now replace old DOM with this new DOM.
792 // An efficient constructor might be able to reuse the entire DOM tree of the original element,
793 // so only mutate the DOM if we need to.
794 if ( $elem
[ 0 ] !== obj
.$element
[ 0 ] ) {
795 $elem
.replaceWith( obj
.$element
);
796 // This element is now gone from the DOM, but if anyone is holding a reference to it,
797 // let's allow them to OO.ui.infuse() it and do what they expect (T105828).
798 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
799 $elem
[ 0 ].oouiInfused
= obj
.$element
;
803 obj
.$element
.data( 'ooui-infused', obj
);
804 obj
.$element
.data( 'ooui-infused-children', infusedChildren
);
805 // set the 'data-ooui' attribute so we can identify infused widgets
806 obj
.$element
.attr( 'data-ooui', '' );
807 // restore dynamic state after the new element is inserted into DOM
808 domPromise
.done( obj
.restorePreInfuseState
.bind( obj
, state
) );
813 * Pick out parts of `node`'s DOM to be reused when infusing a widget.
815 * This method **must not** make any changes to the DOM, only find interesting pieces and add them
816 * to `config` (which should then be returned). Actual DOM juggling should then be done by the
817 * constructor, which will be given the enhanced config.
820 * @param {HTMLElement} node
821 * @param {Object} config
824 OO
.ui
.Element
.static.reusePreInfuseDOM = function ( node
, config
) {
829 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of an HTML DOM node
830 * (and its children) that represent an Element of the same class and the given configuration,
831 * generated by the PHP implementation.
833 * This method is called just before `node` is detached from the DOM. The return value of this
834 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
835 * is inserted into DOM to replace `node`.
838 * @param {HTMLElement} node
839 * @param {Object} config
842 OO
.ui
.Element
.static.gatherPreInfuseState = function () {
847 * Get a jQuery function within a specific document.
850 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
851 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
853 * @return {Function} Bound jQuery function
855 OO
.ui
.Element
.static.getJQuery = function ( context
, $iframe
) {
856 function wrapper( selector
) {
857 return $( selector
, wrapper
.context
);
860 wrapper
.context
= this.getDocument( context
);
863 wrapper
.$iframe
= $iframe
;
870 * Get the document of an element.
873 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
874 * @return {HTMLDocument|null} Document object
876 OO
.ui
.Element
.static.getDocument = function ( obj
) {
877 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
878 return ( obj
[ 0 ] && obj
[ 0 ].ownerDocument
) ||
879 // Empty jQuery selections might have a context
886 ( obj
.nodeType
=== 9 && obj
) ||
891 * Get the window of an element or document.
894 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
895 * @return {Window} Window object
897 OO
.ui
.Element
.static.getWindow = function ( obj
) {
898 var doc
= this.getDocument( obj
);
899 return doc
.defaultView
;
903 * Get the direction of an element or document.
906 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
907 * @return {string} Text direction, either 'ltr' or 'rtl'
909 OO
.ui
.Element
.static.getDir = function ( obj
) {
912 if ( obj
instanceof jQuery
) {
915 isDoc
= obj
.nodeType
=== 9;
916 isWin
= obj
.document
!== undefined;
917 if ( isDoc
|| isWin
) {
923 return $( obj
).css( 'direction' );
927 * Get the offset between two frames.
929 * TODO: Make this function not use recursion.
932 * @param {Window} from Window of the child frame
933 * @param {Window} [to=window] Window of the parent frame
934 * @param {Object} [offset] Offset to start with, used internally
935 * @return {Object} Offset object, containing left and top properties
937 OO
.ui
.Element
.static.getFrameOffset = function ( from, to
, offset
) {
938 var i
, len
, frames
, frame
, rect
;
944 offset
= { top
: 0, left
: 0 };
946 if ( from.parent
=== from ) {
950 // Get iframe element
951 frames
= from.parent
.document
.getElementsByTagName( 'iframe' );
952 for ( i
= 0, len
= frames
.length
; i
< len
; i
++ ) {
953 if ( frames
[ i
].contentWindow
=== from ) {
959 // Recursively accumulate offset values
961 rect
= frame
.getBoundingClientRect();
962 offset
.left
+= rect
.left
;
963 offset
.top
+= rect
.top
;
965 this.getFrameOffset( from.parent
, offset
);
972 * Get the offset between two elements.
974 * The two elements may be in a different frame, but in that case the frame $element is in must
975 * be contained in the frame $anchor is in.
978 * @param {jQuery} $element Element whose position to get
979 * @param {jQuery} $anchor Element to get $element's position relative to
980 * @return {Object} Translated position coordinates, containing top and left properties
982 OO
.ui
.Element
.static.getRelativePosition = function ( $element
, $anchor
) {
983 var iframe
, iframePos
,
984 pos
= $element
.offset(),
985 anchorPos
= $anchor
.offset(),
986 elementDocument
= this.getDocument( $element
),
987 anchorDocument
= this.getDocument( $anchor
);
989 // If $element isn't in the same document as $anchor, traverse up
990 while ( elementDocument
!== anchorDocument
) {
991 iframe
= elementDocument
.defaultView
.frameElement
;
993 throw new Error( '$element frame is not contained in $anchor frame' );
995 iframePos
= $( iframe
).offset();
996 pos
.left
+= iframePos
.left
;
997 pos
.top
+= iframePos
.top
;
998 elementDocument
= iframe
.ownerDocument
;
1000 pos
.left
-= anchorPos
.left
;
1001 pos
.top
-= anchorPos
.top
;
1006 * Get element border sizes.
1009 * @param {HTMLElement} el Element to measure
1010 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1012 OO
.ui
.Element
.static.getBorders = function ( el
) {
1013 var doc
= el
.ownerDocument
,
1014 win
= doc
.defaultView
,
1015 style
= win
.getComputedStyle( el
, null ),
1017 top
= parseFloat( style
? style
.borderTopWidth
: $el
.css( 'borderTopWidth' ) ) || 0,
1018 left
= parseFloat( style
? style
.borderLeftWidth
: $el
.css( 'borderLeftWidth' ) ) || 0,
1019 bottom
= parseFloat( style
? style
.borderBottomWidth
: $el
.css( 'borderBottomWidth' ) ) || 0,
1020 right
= parseFloat( style
? style
.borderRightWidth
: $el
.css( 'borderRightWidth' ) ) || 0;
1031 * Get dimensions of an element or window.
1034 * @param {HTMLElement|Window} el Element to measure
1035 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1037 OO
.ui
.Element
.static.getDimensions = function ( el
) {
1039 doc
= el
.ownerDocument
|| el
.document
,
1040 win
= doc
.defaultView
;
1042 if ( win
=== el
|| el
=== doc
.documentElement
) {
1045 borders
: { top
: 0, left
: 0, bottom
: 0, right
: 0 },
1047 top
: $win
.scrollTop(),
1048 left
: $win
.scrollLeft()
1050 scrollbar
: { right
: 0, bottom
: 0 },
1054 bottom
: $win
.innerHeight(),
1055 right
: $win
.innerWidth()
1061 borders
: this.getBorders( el
),
1063 top
: $el
.scrollTop(),
1064 left
: $el
.scrollLeft()
1067 right
: $el
.innerWidth() - el
.clientWidth
,
1068 bottom
: $el
.innerHeight() - el
.clientHeight
1070 rect
: el
.getBoundingClientRect()
1076 * Get the number of pixels that an element's content is scrolled to the left.
1078 * Adapted from <https://github.com/othree/jquery.rtl-scroll-type>.
1079 * Original code copyright 2012 Wei-Ko Kao, licensed under the MIT License.
1081 * This function smooths out browser inconsistencies (nicely described in the README at
1082 * <https://github.com/othree/jquery.rtl-scroll-type>) and produces a result consistent
1083 * with Firefox's 'scrollLeft', which seems the sanest.
1087 * @param {HTMLElement|Window} el Element to measure
1088 * @return {number} Scroll position from the left.
1089 * If the element's direction is LTR, this is a positive number between `0` (initial scroll position)
1090 * and `el.scrollWidth - el.clientWidth` (furthest possible scroll position).
1091 * If the element's direction is RTL, this is a negative number between `0` (initial scroll position)
1092 * and `-el.scrollWidth + el.clientWidth` (furthest possible scroll position).
1094 OO
.ui
.Element
.static.getScrollLeft
= ( function () {
1095 var rtlScrollType
= null;
1098 var $definer
= $( '<div dir="rtl" style="font-size: 14px; width: 1px; height: 1px; position: absolute; top: -1000px; overflow: scroll">A</div>' ),
1099 definer
= $definer
[ 0 ];
1101 $definer
.appendTo( 'body' );
1102 if ( definer
.scrollLeft
> 0 ) {
1104 rtlScrollType
= 'default';
1106 definer
.scrollLeft
= 1;
1107 if ( definer
.scrollLeft
=== 0 ) {
1108 // Firefox, old Opera
1109 rtlScrollType
= 'negative';
1111 // Internet Explorer, Edge
1112 rtlScrollType
= 'reverse';
1118 return function getScrollLeft( el
) {
1119 var isRoot
= el
.window
=== el
||
1120 el
=== el
.ownerDocument
.body
||
1121 el
=== el
.ownerDocument
.documentElement
,
1122 scrollLeft
= isRoot
? $( window
).scrollLeft() : el
.scrollLeft
,
1123 // All browsers use the correct scroll type ('negative') on the root, so don't
1124 // do any fixups when looking at the root element
1125 direction
= isRoot
? 'ltr' : $( el
).css( 'direction' );
1127 if ( direction
=== 'rtl' ) {
1128 if ( rtlScrollType
=== null ) {
1131 if ( rtlScrollType
=== 'reverse' ) {
1132 scrollLeft
= -scrollLeft
;
1133 } else if ( rtlScrollType
=== 'default' ) {
1134 scrollLeft
= scrollLeft
- el
.scrollWidth
+ el
.clientWidth
;
1143 * Get scrollable object parent
1145 * documentElement can't be used to get or set the scrollTop
1146 * property on Blink. Changing and testing its value lets us
1147 * use 'body' or 'documentElement' based on what is working.
1149 * https://code.google.com/p/chromium/issues/detail?id=303131
1152 * @param {HTMLElement} el Element to find scrollable parent for
1153 * @return {HTMLElement} Scrollable parent
1155 OO
.ui
.Element
.static.getRootScrollableElement = function ( el
) {
1156 var scrollTop
, body
;
1158 if ( OO
.ui
.scrollableElement
=== undefined ) {
1159 body
= el
.ownerDocument
.body
;
1160 scrollTop
= body
.scrollTop
;
1163 if ( body
.scrollTop
=== 1 ) {
1164 body
.scrollTop
= scrollTop
;
1165 OO
.ui
.scrollableElement
= 'body';
1167 OO
.ui
.scrollableElement
= 'documentElement';
1171 return el
.ownerDocument
[ OO
.ui
.scrollableElement
];
1175 * Get closest scrollable container.
1177 * Traverses up until either a scrollable element or the root is reached, in which case the window
1181 * @param {HTMLElement} el Element to find scrollable container for
1182 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1183 * @return {HTMLElement} Closest scrollable container
1185 OO
.ui
.Element
.static.getClosestScrollableContainer = function ( el
, dimension
) {
1187 // Browsers do not correctly return the computed value of 'overflow' when 'overflow-x' and
1188 // 'overflow-y' have different values, so we need to check the separate properties.
1189 props
= [ 'overflow-x', 'overflow-y' ],
1190 $parent
= $( el
).parent();
1192 if ( dimension
=== 'x' || dimension
=== 'y' ) {
1193 props
= [ 'overflow-' + dimension
];
1196 while ( $parent
.length
) {
1197 if ( $parent
[ 0 ] === this.getRootScrollableElement( el
) ) {
1198 return $parent
[ 0 ];
1202 val
= $parent
.css( props
[ i
] );
1203 // We assume that elements with 'overflow' (in any direction) set to 'hidden' will never be
1204 // scrolled in that direction, but they can actually be scrolled programatically. The user can
1205 // unintentionally perform a scroll in such case even if the application doesn't scroll
1206 // programatically, e.g. when jumping to an anchor, or when using built-in find functionality.
1207 // This could cause funny issues...
1208 if ( val
=== 'auto' || val
=== 'scroll' ) {
1209 return $parent
[ 0 ];
1212 $parent
= $parent
.parent();
1214 return this.getDocument( el
).body
;
1218 * Scroll element into view.
1221 * @param {HTMLElement} el Element to scroll into view
1222 * @param {Object} [config] Configuration options
1223 * @param {string} [config.duration='fast'] jQuery animation duration value
1224 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1225 * to scroll in both directions
1226 * @param {Function} [config.complete] Function to call when scrolling completes.
1227 * Deprecated since 0.15.4, use the return promise instead.
1228 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1230 OO
.ui
.Element
.static.scrollIntoView = function ( el
, config
) {
1231 var position
, animations
, callback
, container
, $container
, elementDimensions
, containerDimensions
, $window
,
1232 deferred
= $.Deferred();
1234 // Configuration initialization
1235 config
= config
|| {};
1238 callback
= typeof config
.complete
=== 'function' && config
.complete
;
1240 OO
.ui
.warnDeprecation( 'Element#scrollIntoView: The `complete` callback config option is deprecated. Use the return promise instead.' );
1242 container
= this.getClosestScrollableContainer( el
, config
.direction
);
1243 $container
= $( container
);
1244 elementDimensions
= this.getDimensions( el
);
1245 containerDimensions
= this.getDimensions( container
);
1246 $window
= $( this.getWindow( el
) );
1248 // Compute the element's position relative to the container
1249 if ( $container
.is( 'html, body' ) ) {
1250 // If the scrollable container is the root, this is easy
1252 top
: elementDimensions
.rect
.top
,
1253 bottom
: $window
.innerHeight() - elementDimensions
.rect
.bottom
,
1254 left
: elementDimensions
.rect
.left
,
1255 right
: $window
.innerWidth() - elementDimensions
.rect
.right
1258 // Otherwise, we have to subtract el's coordinates from container's coordinates
1260 top
: elementDimensions
.rect
.top
- ( containerDimensions
.rect
.top
+ containerDimensions
.borders
.top
),
1261 bottom
: containerDimensions
.rect
.bottom
- containerDimensions
.borders
.bottom
- containerDimensions
.scrollbar
.bottom
- elementDimensions
.rect
.bottom
,
1262 left
: elementDimensions
.rect
.left
- ( containerDimensions
.rect
.left
+ containerDimensions
.borders
.left
),
1263 right
: containerDimensions
.rect
.right
- containerDimensions
.borders
.right
- containerDimensions
.scrollbar
.right
- elementDimensions
.rect
.right
1267 if ( !config
.direction
|| config
.direction
=== 'y' ) {
1268 if ( position
.top
< 0 ) {
1269 animations
.scrollTop
= containerDimensions
.scroll
.top
+ position
.top
;
1270 } else if ( position
.top
> 0 && position
.bottom
< 0 ) {
1271 animations
.scrollTop
= containerDimensions
.scroll
.top
+ Math
.min( position
.top
, -position
.bottom
);
1274 if ( !config
.direction
|| config
.direction
=== 'x' ) {
1275 if ( position
.left
< 0 ) {
1276 animations
.scrollLeft
= containerDimensions
.scroll
.left
+ position
.left
;
1277 } else if ( position
.left
> 0 && position
.right
< 0 ) {
1278 animations
.scrollLeft
= containerDimensions
.scroll
.left
+ Math
.min( position
.left
, -position
.right
);
1281 if ( !$.isEmptyObject( animations
) ) {
1282 $container
.stop( true ).animate( animations
, config
.duration
=== undefined ? 'fast' : config
.duration
);
1283 $container
.queue( function ( next
) {
1296 return deferred
.promise();
1300 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1301 * and reserve space for them, because it probably doesn't.
1303 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1304 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1305 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1306 * and then reattach (or show) them back.
1309 * @param {HTMLElement} el Element to reconsider the scrollbars on
1311 OO
.ui
.Element
.static.reconsiderScrollbars = function ( el
) {
1312 var i
, len
, scrollLeft
, scrollTop
, nodes
= [];
1313 // Save scroll position
1314 scrollLeft
= el
.scrollLeft
;
1315 scrollTop
= el
.scrollTop
;
1316 // Detach all children
1317 while ( el
.firstChild
) {
1318 nodes
.push( el
.firstChild
);
1319 el
.removeChild( el
.firstChild
);
1322 void el
.offsetHeight
;
1323 // Reattach all children
1324 for ( i
= 0, len
= nodes
.length
; i
< len
; i
++ ) {
1325 el
.appendChild( nodes
[ i
] );
1327 // Restore scroll position (no-op if scrollbars disappeared)
1328 el
.scrollLeft
= scrollLeft
;
1329 el
.scrollTop
= scrollTop
;
1335 * Toggle visibility of an element.
1337 * @param {boolean} [show] Make element visible, omit to toggle visibility
1341 OO
.ui
.Element
.prototype.toggle = function ( show
) {
1342 show
= show
=== undefined ? !this.visible
: !!show
;
1344 if ( show
!== this.isVisible() ) {
1345 this.visible
= show
;
1346 this.$element
.toggleClass( 'oo-ui-element-hidden', !this.visible
);
1347 this.emit( 'toggle', show
);
1354 * Check if element is visible.
1356 * @return {boolean} element is visible
1358 OO
.ui
.Element
.prototype.isVisible = function () {
1359 return this.visible
;
1365 * @return {Mixed} Element data
1367 OO
.ui
.Element
.prototype.getData = function () {
1374 * @param {Mixed} data Element data
1377 OO
.ui
.Element
.prototype.setData = function ( data
) {
1383 * Check if element supports one or more methods.
1385 * @param {string|string[]} methods Method or list of methods to check
1386 * @return {boolean} All methods are supported
1388 OO
.ui
.Element
.prototype.supports = function ( methods
) {
1392 methods
= Array
.isArray( methods
) ? methods
: [ methods
];
1393 for ( i
= 0, len
= methods
.length
; i
< len
; i
++ ) {
1394 if ( $.isFunction( this[ methods
[ i
] ] ) ) {
1399 return methods
.length
=== support
;
1403 * Update the theme-provided classes.
1405 * @localdoc This is called in element mixins and widget classes any time state changes.
1406 * Updating is debounced, minimizing overhead of changing multiple attributes and
1407 * guaranteeing that theme updates do not occur within an element's constructor
1409 OO
.ui
.Element
.prototype.updateThemeClasses = function () {
1410 OO
.ui
.theme
.queueUpdateElementClasses( this );
1414 * Get the HTML tag name.
1416 * Override this method to base the result on instance information.
1418 * @return {string} HTML tag name
1420 OO
.ui
.Element
.prototype.getTagName = function () {
1421 return this.constructor.static.tagName
;
1425 * Check if the element is attached to the DOM
1427 * @return {boolean} The element is attached to the DOM
1429 OO
.ui
.Element
.prototype.isElementAttached = function () {
1430 return $.contains( this.getElementDocument(), this.$element
[ 0 ] );
1434 * Get the DOM document.
1436 * @return {HTMLDocument} Document object
1438 OO
.ui
.Element
.prototype.getElementDocument = function () {
1439 // Don't cache this in other ways either because subclasses could can change this.$element
1440 return OO
.ui
.Element
.static.getDocument( this.$element
);
1444 * Get the DOM window.
1446 * @return {Window} Window object
1448 OO
.ui
.Element
.prototype.getElementWindow = function () {
1449 return OO
.ui
.Element
.static.getWindow( this.$element
);
1453 * Get closest scrollable container.
1455 * @return {HTMLElement} Closest scrollable container
1457 OO
.ui
.Element
.prototype.getClosestScrollableElementContainer = function () {
1458 return OO
.ui
.Element
.static.getClosestScrollableContainer( this.$element
[ 0 ] );
1462 * Get group element is in.
1464 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1466 OO
.ui
.Element
.prototype.getElementGroup = function () {
1467 return this.elementGroup
;
1471 * Set group element is in.
1473 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1476 OO
.ui
.Element
.prototype.setElementGroup = function ( group
) {
1477 this.elementGroup
= group
;
1482 * Scroll element into view.
1484 * @param {Object} [config] Configuration options
1485 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1487 OO
.ui
.Element
.prototype.scrollElementIntoView = function ( config
) {
1489 !this.isElementAttached() ||
1490 !this.isVisible() ||
1491 ( this.getElementGroup() && !this.getElementGroup().isVisible() )
1493 return $.Deferred().resolve();
1495 return OO
.ui
.Element
.static.scrollIntoView( this.$element
[ 0 ], config
);
1499 * Restore the pre-infusion dynamic state for this widget.
1501 * This method is called after #$element has been inserted into DOM. The parameter is the return
1502 * value of #gatherPreInfuseState.
1505 * @param {Object} state
1507 OO
.ui
.Element
.prototype.restorePreInfuseState = function () {
1511 * Wraps an HTML snippet for use with configuration values which default
1512 * to strings. This bypasses the default html-escaping done to string
1518 * @param {string} [content] HTML content
1520 OO
.ui
.HtmlSnippet
= function OoUiHtmlSnippet( content
) {
1522 this.content
= content
;
1527 OO
.initClass( OO
.ui
.HtmlSnippet
);
1534 * @return {string} Unchanged HTML snippet.
1536 OO
.ui
.HtmlSnippet
.prototype.toString = function () {
1537 return this.content
;
1541 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1542 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1543 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1544 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1545 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1549 * @extends OO.ui.Element
1550 * @mixins OO.EventEmitter
1553 * @param {Object} [config] Configuration options
1555 OO
.ui
.Layout
= function OoUiLayout( config
) {
1556 // Configuration initialization
1557 config
= config
|| {};
1559 // Parent constructor
1560 OO
.ui
.Layout
.parent
.call( this, config
);
1562 // Mixin constructors
1563 OO
.EventEmitter
.call( this );
1566 this.$element
.addClass( 'oo-ui-layout' );
1571 OO
.inheritClass( OO
.ui
.Layout
, OO
.ui
.Element
);
1572 OO
.mixinClass( OO
.ui
.Layout
, OO
.EventEmitter
);
1575 * Widgets are compositions of one or more OOjs UI elements that users can both view
1576 * and interact with. All widgets can be configured and modified via a standard API,
1577 * and their state can change dynamically according to a model.
1581 * @extends OO.ui.Element
1582 * @mixins OO.EventEmitter
1585 * @param {Object} [config] Configuration options
1586 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1587 * appearance reflects this state.
1589 OO
.ui
.Widget
= function OoUiWidget( config
) {
1590 // Initialize config
1591 config
= $.extend( { disabled
: false }, config
);
1593 // Parent constructor
1594 OO
.ui
.Widget
.parent
.call( this, config
);
1596 // Mixin constructors
1597 OO
.EventEmitter
.call( this );
1600 this.disabled
= null;
1601 this.wasDisabled
= null;
1604 this.$element
.addClass( 'oo-ui-widget' );
1605 this.setDisabled( !!config
.disabled
);
1610 OO
.inheritClass( OO
.ui
.Widget
, OO
.ui
.Element
);
1611 OO
.mixinClass( OO
.ui
.Widget
, OO
.EventEmitter
);
1613 /* Static Properties */
1616 * Whether this widget will behave reasonably when wrapped in an HTML `<label>`. If this is true,
1617 * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click
1622 * @property {boolean}
1624 OO
.ui
.Widget
.static.supportsSimpleLabel
= false;
1631 * A 'disable' event is emitted when the disabled state of the widget changes
1632 * (i.e. on disable **and** enable).
1634 * @param {boolean} disabled Widget is disabled
1640 * A 'toggle' event is emitted when the visibility of the widget changes.
1642 * @param {boolean} visible Widget is visible
1648 * Check if the widget is disabled.
1650 * @return {boolean} Widget is disabled
1652 OO
.ui
.Widget
.prototype.isDisabled = function () {
1653 return this.disabled
;
1657 * Set the 'disabled' state of the widget.
1659 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1661 * @param {boolean} disabled Disable widget
1664 OO
.ui
.Widget
.prototype.setDisabled = function ( disabled
) {
1667 this.disabled
= !!disabled
;
1668 isDisabled
= this.isDisabled();
1669 if ( isDisabled
!== this.wasDisabled
) {
1670 this.$element
.toggleClass( 'oo-ui-widget-disabled', isDisabled
);
1671 this.$element
.toggleClass( 'oo-ui-widget-enabled', !isDisabled
);
1672 this.$element
.attr( 'aria-disabled', isDisabled
.toString() );
1673 this.emit( 'disable', isDisabled
);
1674 this.updateThemeClasses();
1676 this.wasDisabled
= isDisabled
;
1682 * Update the disabled state, in case of changes in parent widget.
1686 OO
.ui
.Widget
.prototype.updateDisabled = function () {
1687 this.setDisabled( this.disabled
);
1699 OO
.ui
.Theme
= function OoUiTheme() {
1700 this.elementClassesQueue
= [];
1701 this.debouncedUpdateQueuedElementClasses
= OO
.ui
.debounce( this.updateQueuedElementClasses
);
1706 OO
.initClass( OO
.ui
.Theme
);
1711 * Get a list of classes to be applied to a widget.
1713 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
1714 * otherwise state transitions will not work properly.
1716 * @param {OO.ui.Element} element Element for which to get classes
1717 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
1719 OO
.ui
.Theme
.prototype.getElementClasses = function () {
1720 return { on
: [], off
: [] };
1724 * Update CSS classes provided by the theme.
1726 * For elements with theme logic hooks, this should be called any time there's a state change.
1728 * @param {OO.ui.Element} element Element for which to update classes
1730 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
1731 var $elements
= $( [] ),
1732 classes
= this.getElementClasses( element
);
1734 if ( element
.$icon
) {
1735 $elements
= $elements
.add( element
.$icon
);
1737 if ( element
.$indicator
) {
1738 $elements
= $elements
.add( element
.$indicator
);
1742 .removeClass( classes
.off
.join( ' ' ) )
1743 .addClass( classes
.on
.join( ' ' ) );
1749 OO
.ui
.Theme
.prototype.updateQueuedElementClasses = function () {
1751 for ( i
= 0; i
< this.elementClassesQueue
.length
; i
++ ) {
1752 this.updateElementClasses( this.elementClassesQueue
[ i
] );
1755 this.elementClassesQueue
= [];
1759 * Queue #updateElementClasses to be called for this element.
1761 * @localdoc QUnit tests override this method to directly call #queueUpdateElementClasses,
1762 * to make them synchronous.
1764 * @param {OO.ui.Element} element Element for which to update classes
1766 OO
.ui
.Theme
.prototype.queueUpdateElementClasses = function ( element
) {
1767 // Keep items in the queue unique. Use lastIndexOf to start checking from the end because that's
1768 // the most common case (this method is often called repeatedly for the same element).
1769 if ( this.elementClassesQueue
.lastIndexOf( element
) !== -1 ) {
1772 this.elementClassesQueue
.push( element
);
1773 this.debouncedUpdateQueuedElementClasses();
1777 * Get the transition duration in milliseconds for dialogs opening/closing
1779 * The dialog should be fully rendered this many milliseconds after the
1780 * ready process has executed.
1782 * @return {number} Transition duration in milliseconds
1784 OO
.ui
.Theme
.prototype.getDialogTransitionDuration = function () {
1789 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
1790 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
1791 * order in which users will navigate through the focusable elements via the "tab" key.
1794 * // TabIndexedElement is mixed into the ButtonWidget class
1795 * // to provide a tabIndex property.
1796 * var button1 = new OO.ui.ButtonWidget( {
1800 * var button2 = new OO.ui.ButtonWidget( {
1804 * var button3 = new OO.ui.ButtonWidget( {
1808 * var button4 = new OO.ui.ButtonWidget( {
1812 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
1818 * @param {Object} [config] Configuration options
1819 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
1820 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
1821 * functionality will be applied to it instead.
1822 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
1823 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
1824 * to remove the element from the tab-navigation flow.
1826 OO
.ui
.mixin
.TabIndexedElement
= function OoUiMixinTabIndexedElement( config
) {
1827 // Configuration initialization
1828 config
= $.extend( { tabIndex
: 0 }, config
);
1831 this.$tabIndexed
= null;
1832 this.tabIndex
= null;
1835 this.connect( this, { disable
: 'onTabIndexedElementDisable' } );
1838 this.setTabIndex( config
.tabIndex
);
1839 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
1844 OO
.initClass( OO
.ui
.mixin
.TabIndexedElement
);
1849 * Set the element that should use the tabindex functionality.
1851 * This method is used to retarget a tabindex mixin so that its functionality applies
1852 * to the specified element. If an element is currently using the functionality, the mixin’s
1853 * effect on that element is removed before the new element is set up.
1855 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
1858 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
1859 var tabIndex
= this.tabIndex
;
1860 // Remove attributes from old $tabIndexed
1861 this.setTabIndex( null );
1862 // Force update of new $tabIndexed
1863 this.$tabIndexed
= $tabIndexed
;
1864 this.tabIndex
= tabIndex
;
1865 return this.updateTabIndex();
1869 * Set the value of the tabindex.
1871 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
1874 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
1875 tabIndex
= typeof tabIndex
=== 'number' ? tabIndex
: null;
1877 if ( this.tabIndex
!== tabIndex
) {
1878 this.tabIndex
= tabIndex
;
1879 this.updateTabIndex();
1886 * Update the `tabindex` attribute, in case of changes to tab index or
1892 OO
.ui
.mixin
.TabIndexedElement
.prototype.updateTabIndex = function () {
1893 if ( this.$tabIndexed
) {
1894 if ( this.tabIndex
!== null ) {
1895 // Do not index over disabled elements
1896 this.$tabIndexed
.attr( {
1897 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
1898 // Support: ChromeVox and NVDA
1899 // These do not seem to inherit aria-disabled from parent elements
1900 'aria-disabled': this.isDisabled().toString()
1903 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
1910 * Handle disable events.
1913 * @param {boolean} disabled Element is disabled
1915 OO
.ui
.mixin
.TabIndexedElement
.prototype.onTabIndexedElementDisable = function () {
1916 this.updateTabIndex();
1920 * Get the value of the tabindex.
1922 * @return {number|null} Tabindex value
1924 OO
.ui
.mixin
.TabIndexedElement
.prototype.getTabIndex = function () {
1925 return this.tabIndex
;
1929 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
1930 * interface element that can be configured with access keys for accessibility.
1931 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
1933 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
1939 * @param {Object} [config] Configuration options
1940 * @cfg {jQuery} [$button] The button element created by the class.
1941 * If this configuration is omitted, the button element will use a generated `<a>`.
1942 * @cfg {boolean} [framed=true] Render the button with a frame
1944 OO
.ui
.mixin
.ButtonElement
= function OoUiMixinButtonElement( config
) {
1945 // Configuration initialization
1946 config
= config
|| {};
1949 this.$button
= null;
1951 this.active
= config
.active
!== undefined && config
.active
;
1952 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
1953 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
1954 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
1955 this.onKeyUpHandler
= this.onKeyUp
.bind( this );
1956 this.onClickHandler
= this.onClick
.bind( this );
1957 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
1960 this.$element
.addClass( 'oo-ui-buttonElement' );
1961 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
1962 this.setButtonElement( config
.$button
|| $( '<a>' ) );
1967 OO
.initClass( OO
.ui
.mixin
.ButtonElement
);
1969 /* Static Properties */
1972 * Cancel mouse down events.
1974 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
1975 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
1976 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
1981 * @property {boolean}
1983 OO
.ui
.mixin
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
1988 * A 'click' event is emitted when the button element is clicked.
1996 * Set the button element.
1998 * This method is used to retarget a button mixin so that its functionality applies to
1999 * the specified button element instead of the one created by the class. If a button element
2000 * is already set, the method will remove the mixin’s effect on that element.
2002 * @param {jQuery} $button Element to use as button
2004 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
2005 if ( this.$button
) {
2007 .removeClass( 'oo-ui-buttonElement-button' )
2008 .removeAttr( 'role accesskey' )
2010 mousedown
: this.onMouseDownHandler
,
2011 keydown
: this.onKeyDownHandler
,
2012 click
: this.onClickHandler
,
2013 keypress
: this.onKeyPressHandler
2017 this.$button
= $button
2018 .addClass( 'oo-ui-buttonElement-button' )
2020 mousedown
: this.onMouseDownHandler
,
2021 keydown
: this.onKeyDownHandler
,
2022 click
: this.onClickHandler
,
2023 keypress
: this.onKeyPressHandler
2026 // Add `role="button"` on `<a>` elements, where it's needed
2027 // `toUppercase()` is added for XHTML documents
2028 if ( this.$button
.prop( 'tagName' ).toUpperCase() === 'A' ) {
2029 this.$button
.attr( 'role', 'button' );
2034 * Handles mouse down events.
2037 * @param {jQuery.Event} e Mouse down event
2039 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown = function ( e
) {
2040 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
2043 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
2044 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
2045 // reliably remove the pressed class
2046 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
2047 // Prevent change of focus unless specifically configured otherwise
2048 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
2054 * Handles mouse up events.
2057 * @param {MouseEvent} e Mouse up event
2059 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp = function ( e
) {
2060 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
2063 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
2064 // Stop listening for mouseup, since we only needed this once
2065 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
2069 * Handles mouse click events.
2072 * @param {jQuery.Event} e Mouse click event
2075 OO
.ui
.mixin
.ButtonElement
.prototype.onClick = function ( e
) {
2076 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
2077 if ( this.emit( 'click' ) ) {
2084 * Handles key down events.
2087 * @param {jQuery.Event} e Key down event
2089 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyDown = function ( e
) {
2090 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
2093 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
2094 // Run the keyup handler no matter where the key is when the button is let go, so we can
2095 // reliably remove the pressed class
2096 this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler
, true );
2100 * Handles key up events.
2103 * @param {KeyboardEvent} e Key up event
2105 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyUp = function ( e
) {
2106 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
2109 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
2110 // Stop listening for keyup, since we only needed this once
2111 this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler
, true );
2115 * Handles key press events.
2118 * @param {jQuery.Event} e Key press event
2121 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyPress = function ( e
) {
2122 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
2123 if ( this.emit( 'click' ) ) {
2130 * Check if button has a frame.
2132 * @return {boolean} Button is framed
2134 OO
.ui
.mixin
.ButtonElement
.prototype.isFramed = function () {
2139 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
2141 * @param {boolean} [framed] Make button framed, omit to toggle
2144 OO
.ui
.mixin
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
2145 framed
= framed
=== undefined ? !this.framed
: !!framed
;
2146 if ( framed
!== this.framed
) {
2147 this.framed
= framed
;
2149 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
2150 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
2151 this.updateThemeClasses();
2158 * Set the button's active state.
2160 * The active state can be set on:
2162 * - {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} when it is selected
2163 * - {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} when it is toggle on
2164 * - {@link OO.ui.ButtonWidget ButtonWidget} when clicking the button would only refresh the page
2167 * @param {boolean} value Make button active
2170 OO
.ui
.mixin
.ButtonElement
.prototype.setActive = function ( value
) {
2171 this.active
= !!value
;
2172 this.$element
.toggleClass( 'oo-ui-buttonElement-active', this.active
);
2173 this.updateThemeClasses();
2178 * Check if the button is active
2181 * @return {boolean} The button is active
2183 OO
.ui
.mixin
.ButtonElement
.prototype.isActive = function () {
2188 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
2189 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
2190 * items from the group is done through the interface the class provides.
2191 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2193 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
2199 * @param {Object} [config] Configuration options
2200 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
2201 * is omitted, the group element will use a generated `<div>`.
2203 OO
.ui
.mixin
.GroupElement
= function OoUiMixinGroupElement( config
) {
2204 // Configuration initialization
2205 config
= config
|| {};
2210 this.aggregateItemEvents
= {};
2213 this.setGroupElement( config
.$group
|| $( '<div>' ) );
2221 * A change event is emitted when the set of selected items changes.
2223 * @param {OO.ui.Element[]} items Items currently in the group
2229 * Set the group element.
2231 * If an element is already set, items will be moved to the new element.
2233 * @param {jQuery} $group Element to use as group
2235 OO
.ui
.mixin
.GroupElement
.prototype.setGroupElement = function ( $group
) {
2238 this.$group
= $group
;
2239 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2240 this.$group
.append( this.items
[ i
].$element
);
2245 * Check if a group contains no items.
2247 * @return {boolean} Group is empty
2249 OO
.ui
.mixin
.GroupElement
.prototype.isEmpty = function () {
2250 return !this.items
.length
;
2254 * Get all items in the group.
2256 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
2257 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
2260 * @return {OO.ui.Element[]} An array of items.
2262 OO
.ui
.mixin
.GroupElement
.prototype.getItems = function () {
2263 return this.items
.slice( 0 );
2267 * Get an item by its data.
2269 * Only the first item with matching data will be returned. To return all matching items,
2270 * use the #getItemsFromData method.
2272 * @param {Object} data Item data to search for
2273 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
2275 OO
.ui
.mixin
.GroupElement
.prototype.getItemFromData = function ( data
) {
2277 hash
= OO
.getHash( data
);
2279 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2280 item
= this.items
[ i
];
2281 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2290 * Get items by their data.
2292 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
2294 * @param {Object} data Item data to search for
2295 * @return {OO.ui.Element[]} Items with equivalent data
2297 OO
.ui
.mixin
.GroupElement
.prototype.getItemsFromData = function ( data
) {
2299 hash
= OO
.getHash( data
),
2302 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2303 item
= this.items
[ i
];
2304 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2313 * Aggregate the events emitted by the group.
2315 * When events are aggregated, the group will listen to all contained items for the event,
2316 * and then emit the event under a new name. The new event will contain an additional leading
2317 * parameter containing the item that emitted the original event. Other arguments emitted from
2318 * the original event are passed through.
2320 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
2321 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
2322 * A `null` value will remove aggregated events.
2324 * @throws {Error} An error is thrown if aggregation already exists.
2326 OO
.ui
.mixin
.GroupElement
.prototype.aggregate = function ( events
) {
2327 var i
, len
, item
, add
, remove
, itemEvent
, groupEvent
;
2329 for ( itemEvent
in events
) {
2330 groupEvent
= events
[ itemEvent
];
2332 // Remove existing aggregated event
2333 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
2334 // Don't allow duplicate aggregations
2336 throw new Error( 'Duplicate item event aggregation for ' + itemEvent
);
2338 // Remove event aggregation from existing items
2339 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2340 item
= this.items
[ i
];
2341 if ( item
.connect
&& item
.disconnect
) {
2343 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
2344 item
.disconnect( this, remove
);
2347 // Prevent future items from aggregating event
2348 delete this.aggregateItemEvents
[ itemEvent
];
2351 // Add new aggregate event
2353 // Make future items aggregate event
2354 this.aggregateItemEvents
[ itemEvent
] = groupEvent
;
2355 // Add event aggregation to existing items
2356 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2357 item
= this.items
[ i
];
2358 if ( item
.connect
&& item
.disconnect
) {
2360 add
[ itemEvent
] = [ 'emit', groupEvent
, item
];
2361 item
.connect( this, add
);
2369 * Add items to the group.
2371 * Items will be added to the end of the group array unless the optional `index` parameter specifies
2372 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
2374 * @param {OO.ui.Element[]} items An array of items to add to the group
2375 * @param {number} [index] Index of the insertion point
2378 OO
.ui
.mixin
.GroupElement
.prototype.addItems = function ( items
, index
) {
2379 var i
, len
, item
, itemEvent
, events
, currentIndex
,
2382 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
2385 // Check if item exists then remove it first, effectively "moving" it
2386 currentIndex
= this.items
.indexOf( item
);
2387 if ( currentIndex
>= 0 ) {
2388 this.removeItems( [ item
] );
2389 // Adjust index to compensate for removal
2390 if ( currentIndex
< index
) {
2395 if ( item
.connect
&& item
.disconnect
&& !$.isEmptyObject( this.aggregateItemEvents
) ) {
2397 for ( itemEvent
in this.aggregateItemEvents
) {
2398 events
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
2400 item
.connect( this, events
);
2402 item
.setElementGroup( this );
2403 itemElements
.push( item
.$element
.get( 0 ) );
2406 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
2407 this.$group
.append( itemElements
);
2408 this.items
.push
.apply( this.items
, items
);
2409 } else if ( index
=== 0 ) {
2410 this.$group
.prepend( itemElements
);
2411 this.items
.unshift
.apply( this.items
, items
);
2413 this.items
[ index
].$element
.before( itemElements
);
2414 this.items
.splice
.apply( this.items
, [ index
, 0 ].concat( items
) );
2417 this.emit( 'change', this.getItems() );
2422 * Remove the specified items from a group.
2424 * Removed items are detached (not removed) from the DOM so that they may be reused.
2425 * To remove all items from a group, you may wish to use the #clearItems method instead.
2427 * @param {OO.ui.Element[]} items An array of items to remove
2430 OO
.ui
.mixin
.GroupElement
.prototype.removeItems = function ( items
) {
2431 var i
, len
, item
, index
, events
, itemEvent
;
2433 // Remove specific items
2434 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
2436 index
= this.items
.indexOf( item
);
2437 if ( index
!== -1 ) {
2438 if ( item
.connect
&& item
.disconnect
&& !$.isEmptyObject( this.aggregateItemEvents
) ) {
2440 for ( itemEvent
in this.aggregateItemEvents
) {
2441 events
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
2443 item
.disconnect( this, events
);
2445 item
.setElementGroup( null );
2446 this.items
.splice( index
, 1 );
2447 item
.$element
.detach();
2451 this.emit( 'change', this.getItems() );
2456 * Clear all items from the group.
2458 * Cleared items are detached from the DOM, not removed, so that they may be reused.
2459 * To remove only a subset of items from a group, use the #removeItems method.
2463 OO
.ui
.mixin
.GroupElement
.prototype.clearItems = function () {
2464 var i
, len
, item
, remove
, itemEvent
;
2467 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2468 item
= this.items
[ i
];
2470 item
.connect
&& item
.disconnect
&&
2471 !$.isEmptyObject( this.aggregateItemEvents
)
2474 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
2475 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
2477 item
.disconnect( this, remove
);
2479 item
.setElementGroup( null );
2480 item
.$element
.detach();
2483 this.emit( 'change', this.getItems() );
2489 * IconElement is often mixed into other classes to generate an icon.
2490 * Icons are graphics, about the size of normal text. They are used to aid the user
2491 * in locating a control or to convey information in a space-efficient way. See the
2492 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
2493 * included in the library.
2495 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
2501 * @param {Object} [config] Configuration options
2502 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
2503 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
2504 * the icon element be set to an existing icon instead of the one generated by this class, set a
2505 * value using a jQuery selection. For example:
2507 * // Use a <div> tag instead of a <span>
2509 * // Use an existing icon element instead of the one generated by the class
2510 * $icon: this.$element
2511 * // Use an icon element from a child widget
2512 * $icon: this.childwidget.$element
2513 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
2514 * symbolic names. A map is used for i18n purposes and contains a `default` icon
2515 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
2516 * by the user's language.
2518 * Example of an i18n map:
2520 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2521 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
2522 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
2523 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
2524 * text. The icon title is displayed when users move the mouse over the icon.
2526 OO
.ui
.mixin
.IconElement
= function OoUiMixinIconElement( config
) {
2527 // Configuration initialization
2528 config
= config
|| {};
2533 this.iconTitle
= null;
2536 this.setIcon( config
.icon
|| this.constructor.static.icon
);
2537 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
2538 this.setIconElement( config
.$icon
|| $( '<span>' ) );
2543 OO
.initClass( OO
.ui
.mixin
.IconElement
);
2545 /* Static Properties */
2548 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
2549 * for i18n purposes and contains a `default` icon name and additional names keyed by
2550 * language code. The `default` name is used when no icon is keyed by the user's language.
2552 * Example of an i18n map:
2554 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2556 * Note: the static property will be overridden if the #icon configuration is used.
2560 * @property {Object|string}
2562 OO
.ui
.mixin
.IconElement
.static.icon
= null;
2565 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
2566 * function that returns title text, or `null` for no title.
2568 * The static property will be overridden if the #iconTitle configuration is used.
2572 * @property {string|Function|null}
2574 OO
.ui
.mixin
.IconElement
.static.iconTitle
= null;
2579 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
2580 * applies to the specified icon element instead of the one created by the class. If an icon
2581 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
2582 * and mixin methods will no longer affect the element.
2584 * @param {jQuery} $icon Element to use as icon
2586 OO
.ui
.mixin
.IconElement
.prototype.setIconElement = function ( $icon
) {
2589 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
2590 .removeAttr( 'title' );
2594 .addClass( 'oo-ui-iconElement-icon' )
2595 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
2596 if ( this.iconTitle
!== null ) {
2597 this.$icon
.attr( 'title', this.iconTitle
);
2600 this.updateThemeClasses();
2604 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
2605 * The icon parameter can also be set to a map of icon names. See the #icon config setting
2608 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
2609 * by language code, or `null` to remove the icon.
2612 OO
.ui
.mixin
.IconElement
.prototype.setIcon = function ( icon
) {
2613 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
2614 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
2616 if ( this.icon
!== icon
) {
2618 if ( this.icon
!== null ) {
2619 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
2621 if ( icon
!== null ) {
2622 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
2628 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
2629 this.updateThemeClasses();
2635 * Set the icon title. Use `null` to remove the title.
2637 * @param {string|Function|null} iconTitle A text string used as the icon title,
2638 * a function that returns title text, or `null` for no title.
2641 OO
.ui
.mixin
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
2642 iconTitle
= typeof iconTitle
=== 'function' ||
2643 ( typeof iconTitle
=== 'string' && iconTitle
.length
) ?
2644 OO
.ui
.resolveMsg( iconTitle
) : null;
2646 if ( this.iconTitle
!== iconTitle
) {
2647 this.iconTitle
= iconTitle
;
2649 if ( this.iconTitle
!== null ) {
2650 this.$icon
.attr( 'title', iconTitle
);
2652 this.$icon
.removeAttr( 'title' );
2661 * Get the symbolic name of the icon.
2663 * @return {string} Icon name
2665 OO
.ui
.mixin
.IconElement
.prototype.getIcon = function () {
2670 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
2672 * @return {string} Icon title text
2674 OO
.ui
.mixin
.IconElement
.prototype.getIconTitle = function () {
2675 return this.iconTitle
;
2679 * IndicatorElement is often mixed into other classes to generate an indicator.
2680 * Indicators are small graphics that are generally used in two ways:
2682 * - To draw attention to the status of an item. For example, an indicator might be
2683 * used to show that an item in a list has errors that need to be resolved.
2684 * - To clarify the function of a control that acts in an exceptional way (a button
2685 * that opens a menu instead of performing an action directly, for example).
2687 * For a list of indicators included in the library, please see the
2688 * [OOjs UI documentation on MediaWiki] [1].
2690 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2696 * @param {Object} [config] Configuration options
2697 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
2698 * configuration is omitted, the indicator element will use a generated `<span>`.
2699 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2700 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
2702 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2703 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
2704 * or a function that returns title text. The indicator title is displayed when users move
2705 * the mouse over the indicator.
2707 OO
.ui
.mixin
.IndicatorElement
= function OoUiMixinIndicatorElement( config
) {
2708 // Configuration initialization
2709 config
= config
|| {};
2712 this.$indicator
= null;
2713 this.indicator
= null;
2714 this.indicatorTitle
= null;
2717 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
2718 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
2719 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
2724 OO
.initClass( OO
.ui
.mixin
.IndicatorElement
);
2726 /* Static Properties */
2729 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2730 * The static property will be overridden if the #indicator configuration is used.
2734 * @property {string|null}
2736 OO
.ui
.mixin
.IndicatorElement
.static.indicator
= null;
2739 * A text string used as the indicator title, a function that returns title text, or `null`
2740 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
2744 * @property {string|Function|null}
2746 OO
.ui
.mixin
.IndicatorElement
.static.indicatorTitle
= null;
2751 * Set the indicator element.
2753 * If an element is already set, it will be cleaned up before setting up the new element.
2755 * @param {jQuery} $indicator Element to use as indicator
2757 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
2758 if ( this.$indicator
) {
2760 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
2761 .removeAttr( 'title' );
2764 this.$indicator
= $indicator
2765 .addClass( 'oo-ui-indicatorElement-indicator' )
2766 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
2767 if ( this.indicatorTitle
!== null ) {
2768 this.$indicator
.attr( 'title', this.indicatorTitle
);
2771 this.updateThemeClasses();
2775 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
2777 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
2780 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
2781 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
2783 if ( this.indicator
!== indicator
) {
2784 if ( this.$indicator
) {
2785 if ( this.indicator
!== null ) {
2786 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
2788 if ( indicator
!== null ) {
2789 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
2792 this.indicator
= indicator
;
2795 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
2796 this.updateThemeClasses();
2802 * Set the indicator title.
2804 * The title is displayed when a user moves the mouse over the indicator.
2806 * @param {string|Function|null} indicatorTitle Indicator title text, a function that returns text, or
2807 * `null` for no indicator title
2810 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorTitle = function ( indicatorTitle
) {
2811 indicatorTitle
= typeof indicatorTitle
=== 'function' ||
2812 ( typeof indicatorTitle
=== 'string' && indicatorTitle
.length
) ?
2813 OO
.ui
.resolveMsg( indicatorTitle
) : null;
2815 if ( this.indicatorTitle
!== indicatorTitle
) {
2816 this.indicatorTitle
= indicatorTitle
;
2817 if ( this.$indicator
) {
2818 if ( this.indicatorTitle
!== null ) {
2819 this.$indicator
.attr( 'title', indicatorTitle
);
2821 this.$indicator
.removeAttr( 'title' );
2830 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2832 * @return {string} Symbolic name of indicator
2834 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicator = function () {
2835 return this.indicator
;
2839 * Get the indicator title.
2841 * The title is displayed when a user moves the mouse over the indicator.
2843 * @return {string} Indicator title text
2845 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicatorTitle = function () {
2846 return this.indicatorTitle
;
2850 * LabelElement is often mixed into other classes to generate a label, which
2851 * helps identify the function of an interface element.
2852 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
2854 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
2860 * @param {Object} [config] Configuration options
2861 * @cfg {jQuery} [$label] The label element created by the class. If this
2862 * configuration is omitted, the label element will use a generated `<span>`.
2863 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
2864 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
2865 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
2866 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
2868 OO
.ui
.mixin
.LabelElement
= function OoUiMixinLabelElement( config
) {
2869 // Configuration initialization
2870 config
= config
|| {};
2877 this.setLabel( config
.label
|| this.constructor.static.label
);
2878 this.setLabelElement( config
.$label
|| $( '<span>' ) );
2883 OO
.initClass( OO
.ui
.mixin
.LabelElement
);
2888 * @event labelChange
2889 * @param {string} value
2892 /* Static Properties */
2895 * The label text. The label can be specified as a plaintext string, a function that will
2896 * produce a string in the future, or `null` for no label. The static value will
2897 * be overridden if a label is specified with the #label config option.
2901 * @property {string|Function|null}
2903 OO
.ui
.mixin
.LabelElement
.static.label
= null;
2905 /* Static methods */
2908 * Highlight the first occurrence of the query in the given text
2910 * @param {string} text Text
2911 * @param {string} query Query to find
2912 * @return {jQuery} Text with the first match of the query
2913 * sub-string wrapped in highlighted span
2915 OO
.ui
.mixin
.LabelElement
.static.highlightQuery = function ( text
, query
) {
2916 var $result
= $( '<span>' ),
2917 offset
= text
.toLowerCase().indexOf( query
.toLowerCase() );
2919 if ( !query
.length
|| offset
=== -1 ) {
2920 return $result
.text( text
);
2923 document
.createTextNode( text
.slice( 0, offset
) ),
2925 .addClass( 'oo-ui-labelElement-label-highlight' )
2926 .text( text
.slice( offset
, offset
+ query
.length
) ),
2927 document
.createTextNode( text
.slice( offset
+ query
.length
) )
2929 return $result
.contents();
2935 * Set the label element.
2937 * If an element is already set, it will be cleaned up before setting up the new element.
2939 * @param {jQuery} $label Element to use as label
2941 OO
.ui
.mixin
.LabelElement
.prototype.setLabelElement = function ( $label
) {
2942 if ( this.$label
) {
2943 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
2946 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
2947 this.setLabelContent( this.label
);
2953 * An empty string will result in the label being hidden. A string containing only whitespace will
2954 * be converted to a single ` `.
2956 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
2957 * text; or null for no label
2960 OO
.ui
.mixin
.LabelElement
.prototype.setLabel = function ( label
) {
2961 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
2962 label
= ( ( typeof label
=== 'string' || label
instanceof jQuery
) && label
.length
) || ( label
instanceof OO
.ui
.HtmlSnippet
&& label
.toString().length
) ? label
: null;
2964 if ( this.label
!== label
) {
2965 if ( this.$label
) {
2966 this.setLabelContent( label
);
2969 this.emit( 'labelChange' );
2972 this.$element
.toggleClass( 'oo-ui-labelElement', !!this.label
);
2978 * Set the label as plain text with a highlighted query
2980 * @param {string} text Text label to set
2981 * @param {string} query Substring of text to highlight
2984 OO
.ui
.mixin
.LabelElement
.prototype.setHighlightedQuery = function ( text
, query
) {
2985 return this.setLabel( this.constructor.static.highlightQuery( text
, query
) );
2991 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
2992 * text; or null for no label
2994 OO
.ui
.mixin
.LabelElement
.prototype.getLabel = function () {
2999 * Set the content of the label.
3001 * Do not call this method until after the label element has been set by #setLabelElement.
3004 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
3005 * text; or null for no label
3007 OO
.ui
.mixin
.LabelElement
.prototype.setLabelContent = function ( label
) {
3008 if ( typeof label
=== 'string' ) {
3009 if ( label
.match( /^\s*$/ ) ) {
3010 // Convert whitespace only string to a single non-breaking space
3011 this.$label
.html( ' ' );
3013 this.$label
.text( label
);
3015 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
3016 this.$label
.html( label
.toString() );
3017 } else if ( label
instanceof jQuery
) {
3018 this.$label
.empty().append( label
);
3020 this.$label
.empty();
3025 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
3026 * additional functionality to an element created by another class. The class provides
3027 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
3028 * which are used to customize the look and feel of a widget to better describe its
3029 * importance and functionality.
3031 * The library currently contains the following styling flags for general use:
3033 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
3034 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
3035 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
3037 * The flags affect the appearance of the buttons:
3040 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
3041 * var button1 = new OO.ui.ButtonWidget( {
3042 * label: 'Constructive',
3043 * flags: 'constructive'
3045 * var button2 = new OO.ui.ButtonWidget( {
3046 * label: 'Destructive',
3047 * flags: 'destructive'
3049 * var button3 = new OO.ui.ButtonWidget( {
3050 * label: 'Progressive',
3051 * flags: 'progressive'
3053 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
3055 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
3056 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
3058 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
3064 * @param {Object} [config] Configuration options
3065 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
3066 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
3067 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
3068 * @cfg {jQuery} [$flagged] The flagged element. By default,
3069 * the flagged functionality is applied to the element created by the class ($element).
3070 * If a different element is specified, the flagged functionality will be applied to it instead.
3072 OO
.ui
.mixin
.FlaggedElement
= function OoUiMixinFlaggedElement( config
) {
3073 // Configuration initialization
3074 config
= config
|| {};
3078 this.$flagged
= null;
3081 this.setFlags( config
.flags
);
3082 this.setFlaggedElement( config
.$flagged
|| this.$element
);
3089 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
3090 * parameter contains the name of each modified flag and indicates whether it was
3093 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
3094 * that the flag was added, `false` that the flag was removed.
3100 * Set the flagged element.
3102 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
3103 * If an element is already set, the method will remove the mixin’s effect on that element.
3105 * @param {jQuery} $flagged Element that should be flagged
3107 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
3108 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
3109 return 'oo-ui-flaggedElement-' + flag
;
3112 if ( this.$flagged
) {
3113 this.$flagged
.removeClass( classNames
);
3116 this.$flagged
= $flagged
.addClass( classNames
);
3120 * Check if the specified flag is set.
3122 * @param {string} flag Name of flag
3123 * @return {boolean} The flag is set
3125 OO
.ui
.mixin
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
3126 // This may be called before the constructor, thus before this.flags is set
3127 return this.flags
&& ( flag
in this.flags
);
3131 * Get the names of all flags set.
3133 * @return {string[]} Flag names
3135 OO
.ui
.mixin
.FlaggedElement
.prototype.getFlags = function () {
3136 // This may be called before the constructor, thus before this.flags is set
3137 return Object
.keys( this.flags
|| {} );
3146 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags = function () {
3147 var flag
, className
,
3150 classPrefix
= 'oo-ui-flaggedElement-';
3152 for ( flag
in this.flags
) {
3153 className
= classPrefix
+ flag
;
3154 changes
[ flag
] = false;
3155 delete this.flags
[ flag
];
3156 remove
.push( className
);
3159 if ( this.$flagged
) {
3160 this.$flagged
.removeClass( remove
.join( ' ' ) );
3163 this.updateThemeClasses();
3164 this.emit( 'flag', changes
);
3170 * Add one or more flags.
3172 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
3173 * or an object keyed by flag name with a boolean value that indicates whether the flag should
3174 * be added (`true`) or removed (`false`).
3178 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags = function ( flags
) {
3179 var i
, len
, flag
, className
,
3183 classPrefix
= 'oo-ui-flaggedElement-';
3185 if ( typeof flags
=== 'string' ) {
3186 className
= classPrefix
+ flags
;
3188 if ( !this.flags
[ flags
] ) {
3189 this.flags
[ flags
] = true;
3190 add
.push( className
);
3192 } else if ( Array
.isArray( flags
) ) {
3193 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
3195 className
= classPrefix
+ flag
;
3197 if ( !this.flags
[ flag
] ) {
3198 changes
[ flag
] = true;
3199 this.flags
[ flag
] = true;
3200 add
.push( className
);
3203 } else if ( OO
.isPlainObject( flags
) ) {
3204 for ( flag
in flags
) {
3205 className
= classPrefix
+ flag
;
3206 if ( flags
[ flag
] ) {
3208 if ( !this.flags
[ flag
] ) {
3209 changes
[ flag
] = true;
3210 this.flags
[ flag
] = true;
3211 add
.push( className
);
3215 if ( this.flags
[ flag
] ) {
3216 changes
[ flag
] = false;
3217 delete this.flags
[ flag
];
3218 remove
.push( className
);
3224 if ( this.$flagged
) {
3226 .addClass( add
.join( ' ' ) )
3227 .removeClass( remove
.join( ' ' ) );
3230 this.updateThemeClasses();
3231 this.emit( 'flag', changes
);
3237 * TitledElement is mixed into other classes to provide a `title` attribute.
3238 * Titles are rendered by the browser and are made visible when the user moves
3239 * the mouse over the element. Titles are not visible on touch devices.
3242 * // TitledElement provides a 'title' attribute to the
3243 * // ButtonWidget class
3244 * var button = new OO.ui.ButtonWidget( {
3245 * label: 'Button with Title',
3246 * title: 'I am a button'
3248 * $( 'body' ).append( button.$element );
3254 * @param {Object} [config] Configuration options
3255 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
3256 * If this config is omitted, the title functionality is applied to $element, the
3257 * element created by the class.
3258 * @cfg {string|Function} [title] The title text or a function that returns text. If
3259 * this config is omitted, the value of the {@link #static-title static title} property is used.
3261 OO
.ui
.mixin
.TitledElement
= function OoUiMixinTitledElement( config
) {
3262 // Configuration initialization
3263 config
= config
|| {};
3266 this.$titled
= null;
3270 this.setTitle( config
.title
!== undefined ? config
.title
: this.constructor.static.title
);
3271 this.setTitledElement( config
.$titled
|| this.$element
);
3276 OO
.initClass( OO
.ui
.mixin
.TitledElement
);
3278 /* Static Properties */
3281 * The title text, a function that returns text, or `null` for no title. The value of the static property
3282 * is overridden if the #title config option is used.
3286 * @property {string|Function|null}
3288 OO
.ui
.mixin
.TitledElement
.static.title
= null;
3293 * Set the titled element.
3295 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
3296 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
3298 * @param {jQuery} $titled Element that should use the 'titled' functionality
3300 OO
.ui
.mixin
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
3301 if ( this.$titled
) {
3302 this.$titled
.removeAttr( 'title' );
3305 this.$titled
= $titled
;
3307 this.$titled
.attr( 'title', this.title
);
3314 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
3317 OO
.ui
.mixin
.TitledElement
.prototype.setTitle = function ( title
) {
3318 title
= typeof title
=== 'function' ? OO
.ui
.resolveMsg( title
) : title
;
3319 title
= ( typeof title
=== 'string' && title
.length
) ? title
: null;
3321 if ( this.title
!== title
) {
3322 if ( this.$titled
) {
3323 if ( title
!== null ) {
3324 this.$titled
.attr( 'title', title
);
3326 this.$titled
.removeAttr( 'title' );
3338 * @return {string} Title string
3340 OO
.ui
.mixin
.TitledElement
.prototype.getTitle = function () {
3345 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
3346 * Accesskeys allow an user to go to a specific element by using
3347 * a shortcut combination of a browser specific keys + the key
3351 * // AccessKeyedElement provides an 'accesskey' attribute to the
3352 * // ButtonWidget class
3353 * var button = new OO.ui.ButtonWidget( {
3354 * label: 'Button with Accesskey',
3357 * $( 'body' ).append( button.$element );
3363 * @param {Object} [config] Configuration options
3364 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
3365 * If this config is omitted, the accesskey functionality is applied to $element, the
3366 * element created by the class.
3367 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
3368 * this config is omitted, no accesskey will be added.
3370 OO
.ui
.mixin
.AccessKeyedElement
= function OoUiMixinAccessKeyedElement( config
) {
3371 // Configuration initialization
3372 config
= config
|| {};
3375 this.$accessKeyed
= null;
3376 this.accessKey
= null;
3379 this.setAccessKey( config
.accessKey
|| null );
3380 this.setAccessKeyedElement( config
.$accessKeyed
|| this.$element
);
3385 OO
.initClass( OO
.ui
.mixin
.AccessKeyedElement
);
3387 /* Static Properties */
3390 * The access key, a function that returns a key, or `null` for no accesskey.
3394 * @property {string|Function|null}
3396 OO
.ui
.mixin
.AccessKeyedElement
.static.accessKey
= null;
3401 * Set the accesskeyed element.
3403 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
3404 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
3406 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
3408 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKeyedElement = function ( $accessKeyed
) {
3409 if ( this.$accessKeyed
) {
3410 this.$accessKeyed
.removeAttr( 'accesskey' );
3413 this.$accessKeyed
= $accessKeyed
;
3414 if ( this.accessKey
) {
3415 this.$accessKeyed
.attr( 'accesskey', this.accessKey
);
3422 * @param {string|Function|null} accessKey Key, a function that returns a key, or `null` for no accesskey
3425 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKey = function ( accessKey
) {
3426 accessKey
= typeof accessKey
=== 'string' ? OO
.ui
.resolveMsg( accessKey
) : null;
3428 if ( this.accessKey
!== accessKey
) {
3429 if ( this.$accessKeyed
) {
3430 if ( accessKey
!== null ) {
3431 this.$accessKeyed
.attr( 'accesskey', accessKey
);
3433 this.$accessKeyed
.removeAttr( 'accesskey' );
3436 this.accessKey
= accessKey
;
3445 * @return {string} accessKey string
3447 OO
.ui
.mixin
.AccessKeyedElement
.prototype.getAccessKey = function () {
3448 return this.accessKey
;
3452 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
3453 * feels, and functionality can be customized via the class’s configuration options
3454 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
3457 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
3460 * // A button widget
3461 * var button = new OO.ui.ButtonWidget( {
3462 * label: 'Button with Icon',
3464 * iconTitle: 'Remove'
3466 * $( 'body' ).append( button.$element );
3468 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
3471 * @extends OO.ui.Widget
3472 * @mixins OO.ui.mixin.ButtonElement
3473 * @mixins OO.ui.mixin.IconElement
3474 * @mixins OO.ui.mixin.IndicatorElement
3475 * @mixins OO.ui.mixin.LabelElement
3476 * @mixins OO.ui.mixin.TitledElement
3477 * @mixins OO.ui.mixin.FlaggedElement
3478 * @mixins OO.ui.mixin.TabIndexedElement
3479 * @mixins OO.ui.mixin.AccessKeyedElement
3482 * @param {Object} [config] Configuration options
3483 * @cfg {boolean} [active=false] Whether button should be shown as active
3484 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
3485 * @cfg {string} [target] The frame or window in which to open the hyperlink.
3486 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
3488 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
3489 // Configuration initialization
3490 config
= config
|| {};
3492 // Parent constructor
3493 OO
.ui
.ButtonWidget
.parent
.call( this, config
);
3495 // Mixin constructors
3496 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
3497 OO
.ui
.mixin
.IconElement
.call( this, config
);
3498 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
3499 OO
.ui
.mixin
.LabelElement
.call( this, config
);
3500 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
3501 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
3502 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
3503 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$button
} ) );
3508 this.noFollow
= false;
3511 this.connect( this, { disable
: 'onDisable' } );
3514 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
3516 .addClass( 'oo-ui-buttonWidget' )
3517 .append( this.$button
);
3518 this.setActive( config
.active
);
3519 this.setHref( config
.href
);
3520 this.setTarget( config
.target
);
3521 this.setNoFollow( config
.noFollow
);
3526 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
3527 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
3528 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IconElement
);
3529 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
3530 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.LabelElement
);
3531 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TitledElement
);
3532 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
3533 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
3534 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
3536 /* Static Properties */
3542 OO
.ui
.ButtonWidget
.static.cancelButtonMouseDownEvents
= false;
3547 * Get hyperlink location.
3549 * @return {string} Hyperlink location
3551 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
3556 * Get hyperlink target.
3558 * @return {string} Hyperlink target
3560 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
3565 * Get search engine traversal hint.
3567 * @return {boolean} Whether search engines should avoid traversing this hyperlink
3569 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
3570 return this.noFollow
;
3574 * Set hyperlink location.
3576 * @param {string|null} href Hyperlink location, null to remove
3578 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
3579 href
= typeof href
=== 'string' ? href
: null;
3580 if ( href
!== null && !OO
.ui
.isSafeUrl( href
) ) {
3584 if ( href
!== this.href
) {
3593 * Update the `href` attribute, in case of changes to href or
3599 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
3600 if ( this.href
!== null && !this.isDisabled() ) {
3601 this.$button
.attr( 'href', this.href
);
3603 this.$button
.removeAttr( 'href' );
3610 * Handle disable events.
3613 * @param {boolean} disabled Element is disabled
3615 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
3620 * Set hyperlink target.
3622 * @param {string|null} target Hyperlink target, null to remove
3624 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
3625 target
= typeof target
=== 'string' ? target
: null;
3627 if ( target
!== this.target
) {
3628 this.target
= target
;
3629 if ( target
!== null ) {
3630 this.$button
.attr( 'target', target
);
3632 this.$button
.removeAttr( 'target' );
3640 * Set search engine traversal hint.
3642 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
3644 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
3645 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
3647 if ( noFollow
!== this.noFollow
) {
3648 this.noFollow
= noFollow
;
3650 this.$button
.attr( 'rel', 'nofollow' );
3652 this.$button
.removeAttr( 'rel' );
3659 // Override method visibility hints from ButtonElement
3668 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
3669 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
3670 * removed, and cleared from the group.
3673 * // Example: A ButtonGroupWidget with two buttons
3674 * var button1 = new OO.ui.PopupButtonWidget( {
3675 * label: 'Select a category',
3678 * $content: $( '<p>List of categories...</p>' ),
3683 * var button2 = new OO.ui.ButtonWidget( {
3686 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
3687 * items: [button1, button2]
3689 * $( 'body' ).append( buttonGroup.$element );
3692 * @extends OO.ui.Widget
3693 * @mixins OO.ui.mixin.GroupElement
3696 * @param {Object} [config] Configuration options
3697 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
3699 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
3700 // Configuration initialization
3701 config
= config
|| {};
3703 // Parent constructor
3704 OO
.ui
.ButtonGroupWidget
.parent
.call( this, config
);
3706 // Mixin constructors
3707 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
3710 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
3711 if ( Array
.isArray( config
.items
) ) {
3712 this.addItems( config
.items
);
3718 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
3719 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.GroupElement
);
3722 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
3723 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
3724 * for a list of icons included in the library.
3727 * // An icon widget with a label
3728 * var myIcon = new OO.ui.IconWidget( {
3732 * // Create a label.
3733 * var iconLabel = new OO.ui.LabelWidget( {
3736 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
3738 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
3741 * @extends OO.ui.Widget
3742 * @mixins OO.ui.mixin.IconElement
3743 * @mixins OO.ui.mixin.TitledElement
3744 * @mixins OO.ui.mixin.FlaggedElement
3747 * @param {Object} [config] Configuration options
3749 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
3750 // Configuration initialization
3751 config
= config
|| {};
3753 // Parent constructor
3754 OO
.ui
.IconWidget
.parent
.call( this, config
);
3756 // Mixin constructors
3757 OO
.ui
.mixin
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
3758 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
3759 OO
.ui
.mixin
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
3762 this.$element
.addClass( 'oo-ui-iconWidget' );
3767 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
3768 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.IconElement
);
3769 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.TitledElement
);
3770 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.FlaggedElement
);
3772 /* Static Properties */
3778 OO
.ui
.IconWidget
.static.tagName
= 'span';
3781 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
3782 * attention to the status of an item or to clarify the function of a control. For a list of
3783 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
3786 * // Example of an indicator widget
3787 * var indicator1 = new OO.ui.IndicatorWidget( {
3788 * indicator: 'alert'
3791 * // Create a fieldset layout to add a label
3792 * var fieldset = new OO.ui.FieldsetLayout();
3793 * fieldset.addItems( [
3794 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
3796 * $( 'body' ).append( fieldset.$element );
3798 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3801 * @extends OO.ui.Widget
3802 * @mixins OO.ui.mixin.IndicatorElement
3803 * @mixins OO.ui.mixin.TitledElement
3806 * @param {Object} [config] Configuration options
3808 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
3809 // Configuration initialization
3810 config
= config
|| {};
3812 // Parent constructor
3813 OO
.ui
.IndicatorWidget
.parent
.call( this, config
);
3815 // Mixin constructors
3816 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
3817 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
3820 this.$element
.addClass( 'oo-ui-indicatorWidget' );
3825 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
3826 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.IndicatorElement
);
3827 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.TitledElement
);
3829 /* Static Properties */
3835 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
3838 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
3839 * be configured with a `label` option that is set to a string, a label node, or a function:
3841 * - String: a plaintext string
3842 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
3843 * label that includes a link or special styling, such as a gray color or additional graphical elements.
3844 * - Function: a function that will produce a string in the future. Functions are used
3845 * in cases where the value of the label is not currently defined.
3847 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
3848 * will come into focus when the label is clicked.
3851 * // Examples of LabelWidgets
3852 * var label1 = new OO.ui.LabelWidget( {
3853 * label: 'plaintext label'
3855 * var label2 = new OO.ui.LabelWidget( {
3856 * label: $( '<a href="default.html">jQuery label</a>' )
3858 * // Create a fieldset layout with fields for each example
3859 * var fieldset = new OO.ui.FieldsetLayout();
3860 * fieldset.addItems( [
3861 * new OO.ui.FieldLayout( label1 ),
3862 * new OO.ui.FieldLayout( label2 )
3864 * $( 'body' ).append( fieldset.$element );
3867 * @extends OO.ui.Widget
3868 * @mixins OO.ui.mixin.LabelElement
3869 * @mixins OO.ui.mixin.TitledElement
3872 * @param {Object} [config] Configuration options
3873 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
3874 * Clicking the label will focus the specified input field.
3876 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
3877 // Configuration initialization
3878 config
= config
|| {};
3880 // Parent constructor
3881 OO
.ui
.LabelWidget
.parent
.call( this, config
);
3883 // Mixin constructors
3884 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
3885 OO
.ui
.mixin
.TitledElement
.call( this, config
);
3888 this.input
= config
.input
;
3891 if ( this.input
instanceof OO
.ui
.InputWidget
) {
3892 if ( this.input
.getInputId() ) {
3893 this.$element
.attr( 'for', this.input
.getInputId() );
3895 this.$label
.on( 'click', function () {
3896 this.fieldWidget
.focus();
3901 this.$element
.addClass( 'oo-ui-labelWidget' );
3906 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
3907 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.LabelElement
);
3908 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.TitledElement
);
3910 /* Static Properties */
3916 OO
.ui
.LabelWidget
.static.tagName
= 'label';
3919 * PendingElement is a mixin that is used to create elements that notify users that something is happening
3920 * and that they should wait before proceeding. The pending state is visually represented with a pending
3921 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
3922 * field of a {@link OO.ui.TextInputWidget text input widget}.
3924 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
3925 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
3926 * in process dialogs.
3929 * function MessageDialog( config ) {
3930 * MessageDialog.parent.call( this, config );
3932 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
3934 * MessageDialog.static.name = 'myMessageDialog';
3935 * MessageDialog.static.actions = [
3936 * { action: 'save', label: 'Done', flags: 'primary' },
3937 * { label: 'Cancel', flags: 'safe' }
3940 * MessageDialog.prototype.initialize = function () {
3941 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
3942 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
3943 * 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>' );
3944 * this.$body.append( this.content.$element );
3946 * MessageDialog.prototype.getBodyHeight = function () {
3949 * MessageDialog.prototype.getActionProcess = function ( action ) {
3950 * var dialog = this;
3951 * if ( action === 'save' ) {
3952 * dialog.getActions().get({actions: 'save'})[0].pushPending();
3953 * return new OO.ui.Process()
3955 * .next( function () {
3956 * dialog.getActions().get({actions: 'save'})[0].popPending();
3959 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
3962 * var windowManager = new OO.ui.WindowManager();
3963 * $( 'body' ).append( windowManager.$element );
3965 * var dialog = new MessageDialog();
3966 * windowManager.addWindows( [ dialog ] );
3967 * windowManager.openWindow( dialog );
3973 * @param {Object} [config] Configuration options
3974 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
3976 OO
.ui
.mixin
.PendingElement
= function OoUiMixinPendingElement( config
) {
3977 // Configuration initialization
3978 config
= config
|| {};
3982 this.$pending
= null;
3985 this.setPendingElement( config
.$pending
|| this.$element
);
3990 OO
.initClass( OO
.ui
.mixin
.PendingElement
);
3995 * Set the pending element (and clean up any existing one).
3997 * @param {jQuery} $pending The element to set to pending.
3999 OO
.ui
.mixin
.PendingElement
.prototype.setPendingElement = function ( $pending
) {
4000 if ( this.$pending
) {
4001 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
4004 this.$pending
= $pending
;
4005 if ( this.pending
> 0 ) {
4006 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
4011 * Check if an element is pending.
4013 * @return {boolean} Element is pending
4015 OO
.ui
.mixin
.PendingElement
.prototype.isPending = function () {
4016 return !!this.pending
;
4020 * Increase the pending counter. The pending state will remain active until the counter is zero
4021 * (i.e., the number of calls to #pushPending and #popPending is the same).
4025 OO
.ui
.mixin
.PendingElement
.prototype.pushPending = function () {
4026 if ( this.pending
=== 0 ) {
4027 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
4028 this.updateThemeClasses();
4036 * Decrease the pending counter. The pending state will remain active until the counter is zero
4037 * (i.e., the number of calls to #pushPending and #popPending is the same).
4041 OO
.ui
.mixin
.PendingElement
.prototype.popPending = function () {
4042 if ( this.pending
=== 1 ) {
4043 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
4044 this.updateThemeClasses();
4046 this.pending
= Math
.max( 0, this.pending
- 1 );
4052 * Element that will stick adjacent to a specified container, even when it is inserted elsewhere
4053 * in the document (for example, in an OO.ui.Window's $overlay).
4055 * The elements's position is automatically calculated and maintained when window is resized or the
4056 * page is scrolled. If you reposition the container manually, you have to call #position to make
4057 * sure the element is still placed correctly.
4059 * As positioning is only possible when both the element and the container are attached to the DOM
4060 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
4061 * the #toggle method to display a floating popup, for example.
4067 * @param {Object} [config] Configuration options
4068 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
4069 * @cfg {jQuery} [$floatableContainer] Node to position adjacent to
4070 * @cfg {string} [verticalPosition='below'] Where to position $floatable vertically:
4071 * 'below': Directly below $floatableContainer, aligning f's top edge with fC's bottom edge
4072 * 'above': Directly above $floatableContainer, aligning f's bottom edge with fC's top edge
4073 * 'top': Align the top edge with $floatableContainer's top edge
4074 * 'bottom': Align the bottom edge with $floatableContainer's bottom edge
4075 * 'center': Vertically align the center with $floatableContainer's center
4076 * @cfg {string} [horizontalPosition='start'] Where to position $floatable horizontally:
4077 * 'before': Directly before $floatableContainer, aligning f's end edge with fC's start edge
4078 * 'after': Directly after $floatableContainer, algining f's start edge with fC's end edge
4079 * 'start': Align the start (left in LTR, right in RTL) edge with $floatableContainer's start edge
4080 * 'end': Align the end (right in LTR, left in RTL) edge with $floatableContainer's end edge
4081 * 'center': Horizontally align the center with $floatableContainer's center
4083 OO
.ui
.mixin
.FloatableElement
= function OoUiMixinFloatableElement( config
) {
4084 // Configuration initialization
4085 config
= config
|| {};
4088 this.$floatable
= null;
4089 this.$floatableContainer
= null;
4090 this.$floatableWindow
= null;
4091 this.$floatableClosestScrollable
= null;
4092 this.onFloatableScrollHandler
= this.position
.bind( this );
4093 this.onFloatableWindowResizeHandler
= this.position
.bind( this );
4096 this.setFloatableContainer( config
.$floatableContainer
);
4097 this.setFloatableElement( config
.$floatable
|| this.$element
);
4098 this.setVerticalPosition( config
.verticalPosition
|| 'below' );
4099 this.setHorizontalPosition( config
.horizontalPosition
|| 'start' );
4105 * Set floatable element.
4107 * If an element is already set, it will be cleaned up before setting up the new element.
4109 * @param {jQuery} $floatable Element to make floatable
4111 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableElement = function ( $floatable
) {
4112 if ( this.$floatable
) {
4113 this.$floatable
.removeClass( 'oo-ui-floatableElement-floatable' );
4114 this.$floatable
.css( { left
: '', top
: '' } );
4117 this.$floatable
= $floatable
.addClass( 'oo-ui-floatableElement-floatable' );
4122 * Set floatable container.
4124 * The element will be positioned relative to the specified container.
4126 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
4128 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableContainer = function ( $floatableContainer
) {
4129 this.$floatableContainer
= $floatableContainer
;
4130 if ( this.$floatable
) {
4136 * Change how the element is positioned vertically.
4138 * @param {string} position 'below', 'above', 'top', 'bottom' or 'center'
4140 OO
.ui
.mixin
.FloatableElement
.prototype.setVerticalPosition = function ( position
) {
4141 if ( [ 'below', 'above', 'top', 'bottom', 'center' ].indexOf( position
) === -1 ) {
4142 throw new Error( 'Invalid value for vertical position: ' + position
);
4144 this.verticalPosition
= position
;
4145 if ( this.$floatable
) {
4151 * Change how the element is positioned horizontally.
4153 * @param {string} position 'before', 'after', 'start', 'end' or 'center'
4155 OO
.ui
.mixin
.FloatableElement
.prototype.setHorizontalPosition = function ( position
) {
4156 if ( [ 'before', 'after', 'start', 'end', 'center' ].indexOf( position
) === -1 ) {
4157 throw new Error( 'Invalid value for horizontal position: ' + position
);
4159 this.horizontalPosition
= position
;
4160 if ( this.$floatable
) {
4166 * Toggle positioning.
4168 * Do not turn positioning on until after the element is attached to the DOM and visible.
4170 * @param {boolean} [positioning] Enable positioning, omit to toggle
4173 OO
.ui
.mixin
.FloatableElement
.prototype.togglePositioning = function ( positioning
) {
4174 var closestScrollableOfContainer
;
4176 if ( !this.$floatable
|| !this.$floatableContainer
) {
4180 positioning
= positioning
=== undefined ? !this.positioning
: !!positioning
;
4182 if ( positioning
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
4183 OO
.ui
.warnDeprecation( 'FloatableElement#togglePositioning: Before calling this method, the element must be attached to the DOM.' );
4184 this.warnedUnattached
= true;
4187 if ( this.positioning
!== positioning
) {
4188 this.positioning
= positioning
;
4190 this.needsCustomPosition
=
4191 this.verticalPostion
!== 'below' ||
4192 this.horizontalPosition
!== 'start' ||
4193 !OO
.ui
.contains( this.$floatableContainer
[ 0 ], this.$floatable
[ 0 ] );
4195 closestScrollableOfContainer
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatableContainer
[ 0 ] );
4196 // If the scrollable is the root, we have to listen to scroll events
4197 // on the window because of browser inconsistencies.
4198 if ( $( closestScrollableOfContainer
).is( 'html, body' ) ) {
4199 closestScrollableOfContainer
= OO
.ui
.Element
.static.getWindow( closestScrollableOfContainer
);
4202 if ( positioning
) {
4203 this.$floatableWindow
= $( this.getElementWindow() );
4204 this.$floatableWindow
.on( 'resize', this.onFloatableWindowResizeHandler
);
4206 this.$floatableClosestScrollable
= $( closestScrollableOfContainer
);
4207 this.$floatableClosestScrollable
.on( 'scroll', this.onFloatableScrollHandler
);
4209 // Initial position after visible
4212 if ( this.$floatableWindow
) {
4213 this.$floatableWindow
.off( 'resize', this.onFloatableWindowResizeHandler
);
4214 this.$floatableWindow
= null;
4217 if ( this.$floatableClosestScrollable
) {
4218 this.$floatableClosestScrollable
.off( 'scroll', this.onFloatableScrollHandler
);
4219 this.$floatableClosestScrollable
= null;
4222 this.$floatable
.css( { left
: '', right
: '', top
: '' } );
4230 * Check whether the bottom edge of the given element is within the viewport of the given container.
4233 * @param {jQuery} $element
4234 * @param {jQuery} $container
4237 OO
.ui
.mixin
.FloatableElement
.prototype.isElementInViewport = function ( $element
, $container
) {
4238 var elemRect
, contRect
, topEdgeInBounds
, bottomEdgeInBounds
, leftEdgeInBounds
, rightEdgeInBounds
,
4239 startEdgeInBounds
, endEdgeInBounds
,
4240 direction
= $element
.css( 'direction' );
4242 elemRect
= $element
[ 0 ].getBoundingClientRect();
4243 if ( $container
[ 0 ] === window
) {
4247 right
: document
.documentElement
.clientWidth
,
4248 bottom
: document
.documentElement
.clientHeight
4251 contRect
= $container
[ 0 ].getBoundingClientRect();
4254 topEdgeInBounds
= elemRect
.top
>= contRect
.top
&& elemRect
.top
<= contRect
.bottom
;
4255 bottomEdgeInBounds
= elemRect
.bottom
>= contRect
.top
&& elemRect
.bottom
<= contRect
.bottom
;
4256 leftEdgeInBounds
= elemRect
.left
>= contRect
.left
&& elemRect
.left
<= contRect
.right
;
4257 rightEdgeInBounds
= elemRect
.right
>= contRect
.left
&& elemRect
.right
<= contRect
.right
;
4258 if ( direction
=== 'rtl' ) {
4259 startEdgeInBounds
= rightEdgeInBounds
;
4260 endEdgeInBounds
= leftEdgeInBounds
;
4262 startEdgeInBounds
= leftEdgeInBounds
;
4263 endEdgeInBounds
= rightEdgeInBounds
;
4266 if ( this.verticalPosition
=== 'below' && !bottomEdgeInBounds
) {
4269 if ( this.verticalPosition
=== 'above' && !topEdgeInBounds
) {
4272 if ( this.horizontalPosition
=== 'before' && !startEdgeInBounds
) {
4275 if ( this.horizontalPosition
=== 'after' && !endEdgeInBounds
) {
4279 // The other positioning values are all about being inside the container,
4280 // so in those cases all we care about is that any part of the container is visible.
4281 return elemRect
.top
<= contRect
.bottom
&& elemRect
.bottom
>= contRect
.top
&&
4282 elemRect
.left
<= contRect
.right
&& elemRect
.right
>= contRect
.left
;
4286 * Position the floatable below its container.
4288 * This should only be done when both of them are attached to the DOM and visible.
4292 OO
.ui
.mixin
.FloatableElement
.prototype.position = function () {
4293 var containerPos
, direction
, $offsetParent
, isBody
, scrollableX
, scrollableY
,
4294 horizScrollbarHeight
, vertScrollbarWidth
, scrollTop
, scrollLeft
,
4295 newPos
= { top
: '', left
: '', bottom
: '', right
: '' };
4297 if ( !this.positioning
) {
4301 if ( !this.isElementInViewport( this.$floatableContainer
, this.$floatableClosestScrollable
) ) {
4302 this.$floatable
.addClass( 'oo-ui-element-hidden' );
4305 this.$floatable
.removeClass( 'oo-ui-element-hidden' );
4308 if ( !this.needsCustomPosition
) {
4312 direction
= this.$floatableContainer
.css( 'direction' );
4313 $offsetParent
= this.$floatable
.offsetParent();
4314 if ( $offsetParent
.is( 'html' ) ) {
4315 // The innerHeight/Width and clientHeight/Width calculations don't work well on the
4316 // <html> element, but they do work on the <body>
4317 $offsetParent
= $( $offsetParent
[ 0 ].ownerDocument
.body
);
4319 isBody
= $offsetParent
.is( 'body' );
4320 scrollableX
= $offsetParent
.css( 'overflow-x' ) === 'scroll' || $offsetParent
.css( 'overflow-x' ) === 'auto';
4321 scrollableY
= $offsetParent
.css( 'overflow-y' ) === 'scroll' || $offsetParent
.css( 'overflow-y' ) === 'auto';
4323 vertScrollbarWidth
= $offsetParent
.innerWidth() - $offsetParent
.prop( 'clientWidth' );
4324 horizScrollbarHeight
= $offsetParent
.innerHeight() - $offsetParent
.prop( 'clientHeight' );
4325 // We don't need to compute and add scrollTop and scrollLeft if the scrollable container is the body,
4326 // or if it isn't scrollable
4327 scrollTop
= scrollableY
&& !isBody
? $offsetParent
.scrollTop() : 0;
4328 scrollLeft
= scrollableX
&& !isBody
? OO
.ui
.Element
.static.getScrollLeft( $offsetParent
[ 0 ] ) : 0;
4330 // Avoid passing the <body> to getRelativePosition(), because it won't return what we expect
4331 // if the <body> has a margin
4332 containerPos
= isBody
?
4333 this.$floatableContainer
.offset() :
4334 OO
.ui
.Element
.static.getRelativePosition( this.$floatableContainer
, $offsetParent
);
4335 containerPos
.bottom
= containerPos
.top
+ this.$floatableContainer
.outerHeight();
4336 containerPos
.right
= containerPos
.left
+ this.$floatableContainer
.outerWidth();
4337 containerPos
.start
= direction
=== 'rtl' ? containerPos
.right
: containerPos
.left
;
4338 containerPos
.end
= direction
=== 'rtl' ? containerPos
.left
: containerPos
.right
;
4340 if ( this.verticalPosition
=== 'below' ) {
4341 newPos
.top
= containerPos
.bottom
;
4342 } else if ( this.verticalPosition
=== 'above' ) {
4343 newPos
.bottom
= $offsetParent
.outerHeight() - containerPos
.top
;
4344 } else if ( this.verticalPosition
=== 'top' ) {
4345 newPos
.top
= containerPos
.top
;
4346 } else if ( this.verticalPosition
=== 'bottom' ) {
4347 newPos
.bottom
= $offsetParent
.outerHeight() - containerPos
.bottom
;
4348 } else if ( this.verticalPosition
=== 'center' ) {
4349 newPos
.top
= containerPos
.top
+
4350 ( this.$floatableContainer
.height() - this.$floatable
.height() ) / 2;
4353 if ( this.horizontalPosition
=== 'before' ) {
4354 newPos
.end
= containerPos
.start
;
4355 } else if ( this.horizontalPosition
=== 'after' ) {
4356 newPos
.start
= containerPos
.end
;
4357 } else if ( this.horizontalPosition
=== 'start' ) {
4358 newPos
.start
= containerPos
.start
;
4359 } else if ( this.horizontalPosition
=== 'end' ) {
4360 newPos
.end
= containerPos
.end
;
4361 } else if ( this.horizontalPosition
=== 'center' ) {
4362 newPos
.left
= containerPos
.left
+
4363 ( this.$floatableContainer
.width() - this.$floatable
.width() ) / 2;
4366 if ( newPos
.start
!== undefined ) {
4367 if ( direction
=== 'rtl' ) {
4368 newPos
.right
= ( isBody
? $( $offsetParent
[ 0 ].ownerDocument
.documentElement
) : $offsetParent
).outerWidth() - newPos
.start
;
4370 newPos
.left
= newPos
.start
;
4372 delete newPos
.start
;
4374 if ( newPos
.end
!== undefined ) {
4375 if ( direction
=== 'rtl' ) {
4376 newPos
.left
= newPos
.end
;
4378 newPos
.right
= ( isBody
? $( $offsetParent
[ 0 ].ownerDocument
.documentElement
) : $offsetParent
).outerWidth() - newPos
.end
;
4383 // Account for scroll position
4384 if ( newPos
.top
!== '' ) {
4385 newPos
.top
+= scrollTop
;
4387 if ( newPos
.bottom
!== '' ) {
4388 newPos
.bottom
-= scrollTop
;
4390 if ( newPos
.left
!== '' ) {
4391 newPos
.left
+= scrollLeft
;
4393 if ( newPos
.right
!== '' ) {
4394 newPos
.right
-= scrollLeft
;
4397 // Account for scrollbar gutter
4398 if ( newPos
.bottom
!== '' ) {
4399 newPos
.bottom
-= horizScrollbarHeight
;
4401 if ( direction
=== 'rtl' ) {
4402 if ( newPos
.left
!== '' ) {
4403 newPos
.left
-= vertScrollbarWidth
;
4406 if ( newPos
.right
!== '' ) {
4407 newPos
.right
-= vertScrollbarWidth
;
4411 this.$floatable
.css( newPos
);
4413 // We updated the position, so re-evaluate the clipping state.
4414 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
4415 // will not notice the need to update itself.)
4416 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
4417 // it not listen to the right events in the right places?
4426 * Element that can be automatically clipped to visible boundaries.
4428 * Whenever the element's natural height changes, you have to call
4429 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
4430 * clipping correctly.
4432 * The dimensions of #$clippableContainer will be compared to the boundaries of the
4433 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
4434 * then #$clippable will be given a fixed reduced height and/or width and will be made
4435 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
4436 * but you can build a static footer by setting #$clippableContainer to an element that contains
4437 * #$clippable and the footer.
4443 * @param {Object} [config] Configuration options
4444 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
4445 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
4446 * omit to use #$clippable
4448 OO
.ui
.mixin
.ClippableElement
= function OoUiMixinClippableElement( config
) {
4449 // Configuration initialization
4450 config
= config
|| {};
4453 this.$clippable
= null;
4454 this.$clippableContainer
= null;
4455 this.clipping
= false;
4456 this.clippedHorizontally
= false;
4457 this.clippedVertically
= false;
4458 this.$clippableScrollableContainer
= null;
4459 this.$clippableScroller
= null;
4460 this.$clippableWindow
= null;
4461 this.idealWidth
= null;
4462 this.idealHeight
= null;
4463 this.onClippableScrollHandler
= this.clip
.bind( this );
4464 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
4467 if ( config
.$clippableContainer
) {
4468 this.setClippableContainer( config
.$clippableContainer
);
4470 this.setClippableElement( config
.$clippable
|| this.$element
);
4476 * Set clippable element.
4478 * If an element is already set, it will be cleaned up before setting up the new element.
4480 * @param {jQuery} $clippable Element to make clippable
4482 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
4483 if ( this.$clippable
) {
4484 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
4485 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
4486 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4489 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
4494 * Set clippable container.
4496 * This is the container that will be measured when deciding whether to clip. When clipping,
4497 * #$clippable will be resized in order to keep the clippable container fully visible.
4499 * If the clippable container is unset, #$clippable will be used.
4501 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
4503 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableContainer = function ( $clippableContainer
) {
4504 this.$clippableContainer
= $clippableContainer
;
4505 if ( this.$clippable
) {
4513 * Do not turn clipping on until after the element is attached to the DOM and visible.
4515 * @param {boolean} [clipping] Enable clipping, omit to toggle
4518 OO
.ui
.mixin
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
4519 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
4521 if ( clipping
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
4522 OO
.ui
.warnDeprecation( 'ClippableElement#toggleClipping: Before calling this method, the element must be attached to the DOM.' );
4523 this.warnedUnattached
= true;
4526 if ( this.clipping
!== clipping
) {
4527 this.clipping
= clipping
;
4529 this.$clippableScrollableContainer
= $( this.getClosestScrollableElementContainer() );
4530 // If the clippable container is the root, we have to listen to scroll events and check
4531 // jQuery.scrollTop on the window because of browser inconsistencies
4532 this.$clippableScroller
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
4533 $( OO
.ui
.Element
.static.getWindow( this.$clippableScrollableContainer
) ) :
4534 this.$clippableScrollableContainer
;
4535 this.$clippableScroller
.on( 'scroll', this.onClippableScrollHandler
);
4536 this.$clippableWindow
= $( this.getElementWindow() )
4537 .on( 'resize', this.onClippableWindowResizeHandler
);
4538 // Initial clip after visible
4541 this.$clippable
.css( {
4549 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4551 this.$clippableScrollableContainer
= null;
4552 this.$clippableScroller
.off( 'scroll', this.onClippableScrollHandler
);
4553 this.$clippableScroller
= null;
4554 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
4555 this.$clippableWindow
= null;
4563 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
4565 * @return {boolean} Element will be clipped to the visible area
4567 OO
.ui
.mixin
.ClippableElement
.prototype.isClipping = function () {
4568 return this.clipping
;
4572 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
4574 * @return {boolean} Part of the element is being clipped
4576 OO
.ui
.mixin
.ClippableElement
.prototype.isClipped = function () {
4577 return this.clippedHorizontally
|| this.clippedVertically
;
4581 * Check if the right of the element is being clipped by the nearest scrollable container.
4583 * @return {boolean} Part of the element is being clipped
4585 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedHorizontally = function () {
4586 return this.clippedHorizontally
;
4590 * Check if the bottom of the element is being clipped by the nearest scrollable container.
4592 * @return {boolean} Part of the element is being clipped
4594 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedVertically = function () {
4595 return this.clippedVertically
;
4599 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
4601 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
4602 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
4604 OO
.ui
.mixin
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
4605 this.idealWidth
= width
;
4606 this.idealHeight
= height
;
4608 if ( !this.clipping
) {
4609 // Update dimensions
4610 this.$clippable
.css( { width
: width
, height
: height
} );
4612 // While clipping, idealWidth and idealHeight are not considered
4616 * Clip element to visible boundaries and allow scrolling when needed. You should call this method
4617 * when the element's natural height changes.
4619 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
4620 * overlapped by, the visible area of the nearest scrollable container.
4622 * Because calling clip() when the natural height changes isn't always possible, we also set
4623 * max-height when the element isn't being clipped. This means that if the element tries to grow
4624 * beyond the edge, something reasonable will happen before clip() is called.
4628 OO
.ui
.mixin
.ClippableElement
.prototype.clip = function () {
4629 var $container
, extraHeight
, extraWidth
, ccOffset
,
4630 $scrollableContainer
, scOffset
, scHeight
, scWidth
,
4631 ccWidth
, scrollerIsWindow
, scrollTop
, scrollLeft
,
4632 desiredWidth
, desiredHeight
, allotedWidth
, allotedHeight
,
4633 naturalWidth
, naturalHeight
, clipWidth
, clipHeight
,
4634 buffer
= 7; // Chosen by fair dice roll
4636 if ( !this.clipping
) {
4637 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
4641 $container
= this.$clippableContainer
|| this.$clippable
;
4642 extraHeight
= $container
.outerHeight() - this.$clippable
.outerHeight();
4643 extraWidth
= $container
.outerWidth() - this.$clippable
.outerWidth();
4644 ccOffset
= $container
.offset();
4645 if ( this.$clippableScrollableContainer
.is( 'html, body' ) ) {
4646 $scrollableContainer
= this.$clippableWindow
;
4647 scOffset
= { top
: 0, left
: 0 };
4649 $scrollableContainer
= this.$clippableScrollableContainer
;
4650 scOffset
= $scrollableContainer
.offset();
4652 scHeight
= $scrollableContainer
.innerHeight() - buffer
;
4653 scWidth
= $scrollableContainer
.innerWidth() - buffer
;
4654 ccWidth
= $container
.outerWidth() + buffer
;
4655 scrollerIsWindow
= this.$clippableScroller
[ 0 ] === this.$clippableWindow
[ 0 ];
4656 scrollTop
= scrollerIsWindow
? this.$clippableScroller
.scrollTop() : 0;
4657 scrollLeft
= scrollerIsWindow
? this.$clippableScroller
.scrollLeft() : 0;
4658 desiredWidth
= ccOffset
.left
< 0 ?
4659 ccWidth
+ ccOffset
.left
:
4660 ( scOffset
.left
+ scrollLeft
+ scWidth
) - ccOffset
.left
;
4661 desiredHeight
= ( scOffset
.top
+ scrollTop
+ scHeight
) - ccOffset
.top
;
4662 // It should never be desirable to exceed the dimensions of the browser viewport... right?
4663 desiredWidth
= Math
.min( desiredWidth
, document
.documentElement
.clientWidth
);
4664 desiredHeight
= Math
.min( desiredHeight
, document
.documentElement
.clientHeight
);
4665 allotedWidth
= Math
.ceil( desiredWidth
- extraWidth
);
4666 allotedHeight
= Math
.ceil( desiredHeight
- extraHeight
);
4667 naturalWidth
= this.$clippable
.prop( 'scrollWidth' );
4668 naturalHeight
= this.$clippable
.prop( 'scrollHeight' );
4669 clipWidth
= allotedWidth
< naturalWidth
;
4670 clipHeight
= allotedHeight
< naturalHeight
;
4673 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. (T157672)
4674 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
4675 this.$clippable
.css( 'overflowX', 'scroll' );
4676 void this.$clippable
[ 0 ].offsetHeight
; // Force reflow
4677 this.$clippable
.css( {
4678 width
: Math
.max( 0, allotedWidth
),
4682 this.$clippable
.css( {
4684 width
: this.idealWidth
? this.idealWidth
- extraWidth
: '',
4685 maxWidth
: Math
.max( 0, allotedWidth
)
4689 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. (T157672)
4690 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
4691 this.$clippable
.css( 'overflowY', 'scroll' );
4692 void this.$clippable
[ 0 ].offsetHeight
; // Force reflow
4693 this.$clippable
.css( {
4694 height
: Math
.max( 0, allotedHeight
),
4698 this.$clippable
.css( {
4700 height
: this.idealHeight
? this.idealHeight
- extraHeight
: '',
4701 maxHeight
: Math
.max( 0, allotedHeight
)
4705 // If we stopped clipping in at least one of the dimensions
4706 if ( ( this.clippedHorizontally
&& !clipWidth
) || ( this.clippedVertically
&& !clipHeight
) ) {
4707 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4710 this.clippedHorizontally
= clipWidth
;
4711 this.clippedVertically
= clipHeight
;
4717 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
4718 * By default, each popup has an anchor that points toward its origin.
4719 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
4721 * Unlike most widgets, PopupWidget is initially hidden and must be shown by calling #toggle.
4724 * // A popup widget.
4725 * var popup = new OO.ui.PopupWidget( {
4726 * $content: $( '<p>Hi there!</p>' ),
4731 * $( 'body' ).append( popup.$element );
4732 * // To display the popup, toggle the visibility to 'true'.
4733 * popup.toggle( true );
4735 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
4738 * @extends OO.ui.Widget
4739 * @mixins OO.ui.mixin.LabelElement
4740 * @mixins OO.ui.mixin.ClippableElement
4741 * @mixins OO.ui.mixin.FloatableElement
4744 * @param {Object} [config] Configuration options
4745 * @cfg {number} [width=320] Width of popup in pixels
4746 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
4747 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
4748 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
4749 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
4750 * popup is leaning towards the right of the screen.
4751 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
4752 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
4753 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
4754 * sentence in the given language.
4755 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
4756 * See the [OOjs UI docs on MediaWiki][3] for an example.
4757 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
4758 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
4759 * @cfg {jQuery} [$content] Content to append to the popup's body
4760 * @cfg {jQuery} [$footer] Content to append to the popup's footer
4761 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
4762 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
4763 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
4765 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
4766 * @cfg {boolean} [head=false] Show a popup header that contains a #label (if specified) and close
4768 * @cfg {boolean} [padded=false] Add padding to the popup's body
4770 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
4771 // Configuration initialization
4772 config
= config
|| {};
4774 // Parent constructor
4775 OO
.ui
.PopupWidget
.parent
.call( this, config
);
4777 // Properties (must be set before ClippableElement constructor call)
4778 this.$body
= $( '<div>' );
4779 this.$popup
= $( '<div>' );
4781 // Mixin constructors
4782 OO
.ui
.mixin
.LabelElement
.call( this, config
);
4783 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, {
4784 $clippable
: this.$body
,
4785 $clippableContainer
: this.$popup
4787 OO
.ui
.mixin
.FloatableElement
.call( this, config
);
4790 this.$anchor
= $( '<div>' );
4791 // If undefined, will be computed lazily in updateDimensions()
4792 this.$container
= config
.$container
;
4793 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
4794 this.autoClose
= !!config
.autoClose
;
4795 this.$autoCloseIgnore
= config
.$autoCloseIgnore
;
4796 this.transitionTimeout
= null;
4798 this.width
= config
.width
!== undefined ? config
.width
: 320;
4799 this.height
= config
.height
!== undefined ? config
.height
: null;
4800 this.setAlignment( config
.align
);
4801 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
4802 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
4805 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
4806 this.$body
.addClass( 'oo-ui-popupWidget-body' );
4807 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
4809 .addClass( 'oo-ui-popupWidget-popup' )
4810 .append( this.$body
);
4812 .addClass( 'oo-ui-popupWidget' )
4813 .append( this.$popup
, this.$anchor
);
4814 // Move content, which was added to #$element by OO.ui.Widget, to the body
4815 // FIXME This is gross, we should use '$body' or something for the config
4816 if ( config
.$content
instanceof jQuery
) {
4817 this.$body
.append( config
.$content
);
4820 if ( config
.padded
) {
4821 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
4824 if ( config
.head
) {
4825 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
4826 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
4827 this.$head
= $( '<div>' )
4828 .addClass( 'oo-ui-popupWidget-head' )
4829 .append( this.$label
, this.closeButton
.$element
);
4830 this.$popup
.prepend( this.$head
);
4833 if ( config
.$footer
) {
4834 this.$footer
= $( '<div>' )
4835 .addClass( 'oo-ui-popupWidget-footer' )
4836 .append( config
.$footer
);
4837 this.$popup
.append( this.$footer
);
4840 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
4841 // that reference properties not initialized at that time of parent class construction
4842 // TODO: Find a better way to handle post-constructor setup
4843 this.visible
= false;
4844 this.$element
.addClass( 'oo-ui-element-hidden' );
4849 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
4850 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.LabelElement
);
4851 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.ClippableElement
);
4852 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.FloatableElement
);
4857 * Handles mouse down events.
4860 * @param {MouseEvent} e Mouse down event
4862 OO
.ui
.PopupWidget
.prototype.onMouseDown = function ( e
) {
4865 !OO
.ui
.contains( this.$element
.add( this.$autoCloseIgnore
).get(), e
.target
, true )
4867 this.toggle( false );
4872 * Bind mouse down listener.
4876 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
4877 // Capture clicks outside popup
4878 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler
, true );
4882 * Handles close button click events.
4886 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
4887 if ( this.isVisible() ) {
4888 this.toggle( false );
4893 * Unbind mouse down listener.
4897 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
4898 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler
, true );
4902 * Handles key down events.
4905 * @param {KeyboardEvent} e Key down event
4907 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
4909 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
4912 this.toggle( false );
4914 e
.stopPropagation();
4919 * Bind key down listener.
4923 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
4924 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
4928 * Unbind key down listener.
4932 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
4933 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
4937 * Show, hide, or toggle the visibility of the anchor.
4939 * @param {boolean} [show] Show anchor, omit to toggle
4941 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
4942 show
= show
=== undefined ? !this.anchored
: !!show
;
4944 if ( this.anchored
!== show
) {
4946 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
4948 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
4950 this.anchored
= show
;
4955 * Check if the anchor is visible.
4957 * @return {boolean} Anchor is visible
4959 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
4964 * Toggle visibility of the popup. The popup is initially hidden and must be shown by calling
4965 * `.toggle( true )` after its #$element is attached to the DOM.
4967 * Do not show the popup while it is not attached to the DOM. The calculations required to display
4968 * it in the right place and with the right dimensions only work correctly while it is attached.
4969 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
4970 * strictly enforced, so currently it only generates a warning in the browser console.
4974 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
4976 show
= show
=== undefined ? !this.isVisible() : !!show
;
4978 change
= show
!== this.isVisible();
4980 if ( show
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
4981 OO
.ui
.warnDeprecation( 'PopupWidget#toggle: Before calling this method, the popup must be attached to the DOM.' );
4982 this.warnedUnattached
= true;
4986 OO
.ui
.PopupWidget
.parent
.prototype.toggle
.call( this, show
);
4989 this.togglePositioning( show
&& !!this.$floatableContainer
);
4992 if ( this.autoClose
) {
4993 this.bindMouseDownListener();
4994 this.bindKeyDownListener();
4996 this.updateDimensions();
4997 this.toggleClipping( true );
4999 this.toggleClipping( false );
5000 if ( this.autoClose
) {
5001 this.unbindMouseDownListener();
5002 this.unbindKeyDownListener();
5011 * Set the size of the popup.
5013 * Changing the size may also change the popup's position depending on the alignment.
5015 * @param {number} width Width in pixels
5016 * @param {number} height Height in pixels
5017 * @param {boolean} [transition=false] Use a smooth transition
5020 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
5022 this.height
= height
!== undefined ? height
: null;
5023 if ( this.isVisible() ) {
5024 this.updateDimensions( transition
);
5029 * Update the size and position.
5031 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
5032 * be called automatically.
5034 * @param {boolean} [transition=false] Use a smooth transition
5037 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
5038 var popupOffset
, originOffset
, containerLeft
, containerWidth
, containerRight
,
5039 popupLeft
, popupRight
, overlapLeft
, overlapRight
, anchorWidth
, direction
,
5043 'force-left': 'backwards',
5044 'force-right': 'forwards'
5047 'force-left': 'forwards',
5048 'force-right': 'backwards'
5053 if ( !this.$container
) {
5054 // Lazy-initialize $container if not specified in constructor
5055 this.$container
= $( this.getClosestScrollableElementContainer() );
5057 direction
= this.$container
.css( 'direction' );
5058 dirFactor
= direction
=== 'rtl' ? -1 : 1;
5059 align
= alignMap
[ direction
][ this.align
] || this.align
;
5061 // Set height and width before measuring things, since it might cause our measurements
5062 // to change (e.g. due to scrollbars appearing or disappearing)
5065 height
: this.height
!== null ? this.height
: 'auto'
5068 // Compute initial popupOffset based on alignment
5069 popupOffset
= this.width
* ( { backwards
: -1, center
: -0.5, forwards
: 0 } )[ align
];
5071 // Figure out if this will cause the popup to go beyond the edge of the container
5072 originOffset
= this.$element
.offset().left
;
5073 containerLeft
= this.$container
.offset().left
;
5074 containerWidth
= this.$container
.innerWidth();
5075 containerRight
= containerLeft
+ containerWidth
;
5076 popupLeft
= dirFactor
* popupOffset
- this.containerPadding
;
5077 popupRight
= dirFactor
* popupOffset
+ this.containerPadding
+ this.width
+ this.containerPadding
;
5078 overlapLeft
= ( originOffset
+ popupLeft
) - containerLeft
;
5079 overlapRight
= containerRight
- ( originOffset
+ popupRight
);
5081 // Adjust offset to make the popup not go beyond the edge, if needed
5082 if ( overlapRight
< 0 ) {
5083 popupOffset
+= dirFactor
* overlapRight
;
5084 } else if ( overlapLeft
< 0 ) {
5085 popupOffset
-= dirFactor
* overlapLeft
;
5088 // Adjust offset to avoid anchor being rendered too close to the edge
5089 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
5090 // TODO: Find a measurement that works for CSS anchors and image anchors
5091 anchorWidth
= this.$anchor
[ 0 ].scrollWidth
* 2;
5092 if ( popupOffset
+ this.width
< anchorWidth
) {
5093 popupOffset
= anchorWidth
- this.width
;
5094 } else if ( -popupOffset
< anchorWidth
) {
5095 popupOffset
= -anchorWidth
;
5098 // Prevent transition from being interrupted
5099 clearTimeout( this.transitionTimeout
);
5101 // Enable transition
5102 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
5105 // Position body relative to anchor
5106 this.$popup
.css( direction
=== 'rtl' ? 'margin-right' : 'margin-left', popupOffset
);
5109 // Prevent transitioning after transition is complete
5110 this.transitionTimeout
= setTimeout( function () {
5111 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
5114 // Prevent transitioning immediately
5115 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
5118 // Reevaluate clipping state since we've relocated and resized the popup
5125 * Set popup alignment
5127 * @param {string} [align=center] Alignment of the popup, `center`, `force-left`, `force-right`,
5128 * `backwards` or `forwards`.
5130 OO
.ui
.PopupWidget
.prototype.setAlignment = function ( align
) {
5131 // Transform values deprecated since v0.11.0
5132 if ( align
=== 'left' || align
=== 'right' ) {
5133 OO
.ui
.warnDeprecation( 'PopupWidget#setAlignment parameter value `' + align
+ '` is deprecated. Use `force-right` or `force-left` instead.' );
5134 align
= { left
: 'force-right', right
: 'force-left' }[ align
];
5137 // Validate alignment
5138 if ( [ 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align
) > -1 ) {
5141 this.align
= 'center';
5146 * Get popup alignment
5148 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
5149 * `backwards` or `forwards`.
5151 OO
.ui
.PopupWidget
.prototype.getAlignment = function () {
5156 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5157 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5158 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5159 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5165 * @param {Object} [config] Configuration options
5166 * @cfg {Object} [popup] Configuration to pass to popup
5167 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5169 OO
.ui
.mixin
.PopupElement
= function OoUiMixinPopupElement( config
) {
5170 // Configuration initialization
5171 config
= config
|| {};
5174 this.popup
= new OO
.ui
.PopupWidget( $.extend(
5175 { autoClose
: true },
5177 { $autoCloseIgnore
: this.$element
.add( config
.popup
&& config
.popup
.$autoCloseIgnore
) }
5186 * @return {OO.ui.PopupWidget} Popup widget
5188 OO
.ui
.mixin
.PopupElement
.prototype.getPopup = function () {
5193 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
5194 * which is used to display additional information or options.
5197 * // Example of a popup button.
5198 * var popupButton = new OO.ui.PopupButtonWidget( {
5199 * label: 'Popup button with options',
5202 * $content: $( '<p>Additional options here.</p>' ),
5204 * align: 'force-left'
5207 * // Append the button to the DOM.
5208 * $( 'body' ).append( popupButton.$element );
5211 * @extends OO.ui.ButtonWidget
5212 * @mixins OO.ui.mixin.PopupElement
5215 * @param {Object} [config] Configuration options
5216 * @cfg {jQuery} [$overlay] Render the popup into a separate layer. This configuration is useful in cases where
5217 * the expanded popup is larger than its containing `<div>`. The specified overlay layer is usually on top of the
5218 * containing `<div>` and has a larger area. By default, the popup uses relative positioning.
5220 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
5221 // Parent constructor
5222 OO
.ui
.PopupButtonWidget
.parent
.call( this, config
);
5224 // Mixin constructors
5225 OO
.ui
.mixin
.PopupElement
.call( this, $.extend( true, {}, config
, {
5227 $floatableContainer
: this.$element
5232 this.$overlay
= config
.$overlay
|| this.$element
;
5235 this.connect( this, { click
: 'onAction' } );
5239 .addClass( 'oo-ui-popupButtonWidget' )
5240 .attr( 'aria-haspopup', 'true' );
5242 .addClass( 'oo-ui-popupButtonWidget-popup' )
5243 .toggleClass( 'oo-ui-popupButtonWidget-framed-popup', this.isFramed() )
5244 .toggleClass( 'oo-ui-popupButtonWidget-frameless-popup', !this.isFramed() );
5245 this.$overlay
.append( this.popup
.$element
);
5250 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
5251 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.mixin
.PopupElement
);
5256 * Handle the button action being triggered.
5260 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
5261 this.popup
.toggle();
5265 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
5267 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
5272 * @mixins OO.ui.mixin.GroupElement
5275 * @param {Object} [config] Configuration options
5277 OO
.ui
.mixin
.GroupWidget
= function OoUiMixinGroupWidget( config
) {
5278 // Mixin constructors
5279 OO
.ui
.mixin
.GroupElement
.call( this, config
);
5284 OO
.mixinClass( OO
.ui
.mixin
.GroupWidget
, OO
.ui
.mixin
.GroupElement
);
5289 * Set the disabled state of the widget.
5291 * This will also update the disabled state of child widgets.
5293 * @param {boolean} disabled Disable widget
5296 OO
.ui
.mixin
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
5300 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
5301 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
5303 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
5305 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5306 this.items
[ i
].updateDisabled();
5314 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
5316 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
5317 * allows bidirectional communication.
5319 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
5327 OO
.ui
.mixin
.ItemWidget
= function OoUiMixinItemWidget() {
5334 * Check if widget is disabled.
5336 * Checks parent if present, making disabled state inheritable.
5338 * @return {boolean} Widget is disabled
5340 OO
.ui
.mixin
.ItemWidget
.prototype.isDisabled = function () {
5341 return this.disabled
||
5342 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
5346 * Set group element is in.
5348 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
5351 OO
.ui
.mixin
.ItemWidget
.prototype.setElementGroup = function ( group
) {
5353 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
5354 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
5356 // Initialize item disabled states
5357 this.updateDisabled();
5363 * OptionWidgets are special elements that can be selected and configured with data. The
5364 * data is often unique for each option, but it does not have to be. OptionWidgets are used
5365 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
5366 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
5368 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5371 * @extends OO.ui.Widget
5372 * @mixins OO.ui.mixin.ItemWidget
5373 * @mixins OO.ui.mixin.LabelElement
5374 * @mixins OO.ui.mixin.FlaggedElement
5375 * @mixins OO.ui.mixin.AccessKeyedElement
5378 * @param {Object} [config] Configuration options
5380 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
5381 // Configuration initialization
5382 config
= config
|| {};
5384 // Parent constructor
5385 OO
.ui
.OptionWidget
.parent
.call( this, config
);
5387 // Mixin constructors
5388 OO
.ui
.mixin
.ItemWidget
.call( this );
5389 OO
.ui
.mixin
.LabelElement
.call( this, config
);
5390 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
5391 OO
.ui
.mixin
.AccessKeyedElement
.call( this, config
);
5394 this.selected
= false;
5395 this.highlighted
= false;
5396 this.pressed
= false;
5400 .data( 'oo-ui-optionWidget', this )
5401 // Allow programmatic focussing (and by accesskey), but not tabbing
5402 .attr( 'tabindex', '-1' )
5403 .attr( 'role', 'option' )
5404 .attr( 'aria-selected', 'false' )
5405 .addClass( 'oo-ui-optionWidget' )
5406 .append( this.$label
);
5411 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
5412 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.ItemWidget
);
5413 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.LabelElement
);
5414 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.FlaggedElement
);
5415 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
5417 /* Static Properties */
5420 * Whether this option can be selected. See #setSelected.
5424 * @property {boolean}
5426 OO
.ui
.OptionWidget
.static.selectable
= true;
5429 * Whether this option can be highlighted. See #setHighlighted.
5433 * @property {boolean}
5435 OO
.ui
.OptionWidget
.static.highlightable
= true;
5438 * Whether this option can be pressed. See #setPressed.
5442 * @property {boolean}
5444 OO
.ui
.OptionWidget
.static.pressable
= true;
5447 * Whether this option will be scrolled into view when it is selected.
5451 * @property {boolean}
5453 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
5458 * Check if the option can be selected.
5460 * @return {boolean} Item is selectable
5462 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
5463 return this.constructor.static.selectable
&& !this.isDisabled() && this.isVisible();
5467 * Check if the option can be highlighted. A highlight indicates that the option
5468 * may be selected when a user presses enter or clicks. Disabled items cannot
5471 * @return {boolean} Item is highlightable
5473 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
5474 return this.constructor.static.highlightable
&& !this.isDisabled() && this.isVisible();
5478 * Check if the option can be pressed. The pressed state occurs when a user mouses
5479 * down on an item, but has not yet let go of the mouse.
5481 * @return {boolean} Item is pressable
5483 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
5484 return this.constructor.static.pressable
&& !this.isDisabled() && this.isVisible();
5488 * Check if the option is selected.
5490 * @return {boolean} Item is selected
5492 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
5493 return this.selected
;
5497 * Check if the option is highlighted. A highlight indicates that the
5498 * item may be selected when a user presses enter or clicks.
5500 * @return {boolean} Item is highlighted
5502 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
5503 return this.highlighted
;
5507 * Check if the option is pressed. The pressed state occurs when a user mouses
5508 * down on an item, but has not yet let go of the mouse. The item may appear
5509 * selected, but it will not be selected until the user releases the mouse.
5511 * @return {boolean} Item is pressed
5513 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
5514 return this.pressed
;
5518 * Set the option’s selected state. In general, all modifications to the selection
5519 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
5520 * method instead of this method.
5522 * @param {boolean} [state=false] Select option
5525 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
5526 if ( this.constructor.static.selectable
) {
5527 this.selected
= !!state
;
5529 .toggleClass( 'oo-ui-optionWidget-selected', state
)
5530 .attr( 'aria-selected', state
.toString() );
5531 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
5532 this.scrollElementIntoView();
5534 this.updateThemeClasses();
5540 * Set the option’s highlighted state. In general, all programmatic
5541 * modifications to the highlight should be handled by the
5542 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
5543 * method instead of this method.
5545 * @param {boolean} [state=false] Highlight option
5548 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
5549 if ( this.constructor.static.highlightable
) {
5550 this.highlighted
= !!state
;
5551 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
5552 this.updateThemeClasses();
5558 * Set the option’s pressed state. In general, all
5559 * programmatic modifications to the pressed state should be handled by the
5560 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
5561 * method instead of this method.
5563 * @param {boolean} [state=false] Press option
5566 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
5567 if ( this.constructor.static.pressable
) {
5568 this.pressed
= !!state
;
5569 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
5570 this.updateThemeClasses();
5576 * Get text to match search strings against.
5578 * The default implementation returns the label text, but subclasses
5579 * can override this to provide more complex behavior.
5581 * @return {string|boolean} String to match search string against
5583 OO
.ui
.OptionWidget
.prototype.getMatchText = function () {
5584 var label
= this.getLabel();
5585 return typeof label
=== 'string' ? label
: this.$label
.text();
5589 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
5590 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
5591 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
5594 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
5595 * information, please see the [OOjs UI documentation on MediaWiki][1].
5598 * // Example of a select widget with three options
5599 * var select = new OO.ui.SelectWidget( {
5601 * new OO.ui.OptionWidget( {
5603 * label: 'Option One',
5605 * new OO.ui.OptionWidget( {
5607 * label: 'Option Two',
5609 * new OO.ui.OptionWidget( {
5611 * label: 'Option Three',
5615 * $( 'body' ).append( select.$element );
5617 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5621 * @extends OO.ui.Widget
5622 * @mixins OO.ui.mixin.GroupWidget
5625 * @param {Object} [config] Configuration options
5626 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
5627 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
5628 * the [OOjs UI documentation on MediaWiki] [2] for examples.
5629 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5631 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
5632 // Configuration initialization
5633 config
= config
|| {};
5635 // Parent constructor
5636 OO
.ui
.SelectWidget
.parent
.call( this, config
);
5638 // Mixin constructors
5639 OO
.ui
.mixin
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
5642 this.pressed
= false;
5643 this.selecting
= null;
5644 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
5645 this.onMouseMoveHandler
= this.onMouseMove
.bind( this );
5646 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
5647 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
5648 this.keyPressBuffer
= '';
5649 this.keyPressBufferTimer
= null;
5650 this.blockMouseOverEvents
= 0;
5653 this.connect( this, {
5657 focusin
: this.onFocus
.bind( this ),
5658 mousedown
: this.onMouseDown
.bind( this ),
5659 mouseover
: this.onMouseOver
.bind( this ),
5660 mouseleave
: this.onMouseLeave
.bind( this )
5665 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
5666 .attr( 'role', 'listbox' );
5667 if ( Array
.isArray( config
.items
) ) {
5668 this.addItems( config
.items
);
5674 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
5675 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupWidget
);
5682 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
5684 * @param {OO.ui.OptionWidget|null} item Highlighted item
5690 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
5691 * pressed state of an option.
5693 * @param {OO.ui.OptionWidget|null} item Pressed item
5699 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
5701 * @param {OO.ui.OptionWidget|null} item Selected item
5706 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
5707 * @param {OO.ui.OptionWidget} item Chosen item
5713 * An `add` event is emitted when options are added to the select with the #addItems method.
5715 * @param {OO.ui.OptionWidget[]} items Added items
5716 * @param {number} index Index of insertion point
5722 * A `remove` event is emitted when options are removed from the select with the #clearItems
5723 * or #removeItems methods.
5725 * @param {OO.ui.OptionWidget[]} items Removed items
5731 * Handle focus events
5734 * @param {jQuery.Event} event
5736 OO
.ui
.SelectWidget
.prototype.onFocus = function ( event
) {
5738 if ( event
.target
=== this.$element
[ 0 ] ) {
5739 // This widget was focussed, e.g. by the user tabbing to it.
5740 // The styles for focus state depend on one of the items being selected.
5741 if ( !this.getSelectedItem() ) {
5742 item
= this.getFirstSelectableItem();
5745 // One of the options got focussed (and the event bubbled up here).
5746 // They can't be tabbed to, but they can be activated using accesskeys.
5747 item
= this.getTargetItem( event
);
5751 if ( item
.constructor.static.highlightable
) {
5752 this.highlightItem( item
);
5754 this.selectItem( item
);
5758 if ( event
.target
!== this.$element
[ 0 ] ) {
5759 this.$element
.focus();
5764 * Handle mouse down events.
5767 * @param {jQuery.Event} e Mouse down event
5769 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
5772 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
5773 this.togglePressed( true );
5774 item
= this.getTargetItem( e
);
5775 if ( item
&& item
.isSelectable() ) {
5776 this.pressItem( item
);
5777 this.selecting
= item
;
5778 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
5779 this.getElementDocument().addEventListener( 'mousemove', this.onMouseMoveHandler
, true );
5786 * Handle mouse up events.
5789 * @param {MouseEvent} e Mouse up event
5791 OO
.ui
.SelectWidget
.prototype.onMouseUp = function ( e
) {
5794 this.togglePressed( false );
5795 if ( !this.selecting
) {
5796 item
= this.getTargetItem( e
);
5797 if ( item
&& item
.isSelectable() ) {
5798 this.selecting
= item
;
5801 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
&& this.selecting
) {
5802 this.pressItem( null );
5803 this.chooseItem( this.selecting
);
5804 this.selecting
= null;
5807 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
5808 this.getElementDocument().removeEventListener( 'mousemove', this.onMouseMoveHandler
, true );
5814 * Handle mouse move events.
5817 * @param {MouseEvent} e Mouse move event
5819 OO
.ui
.SelectWidget
.prototype.onMouseMove = function ( e
) {
5822 if ( !this.isDisabled() && this.pressed
) {
5823 item
= this.getTargetItem( e
);
5824 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
5825 this.pressItem( item
);
5826 this.selecting
= item
;
5832 * Handle mouse over events.
5835 * @param {jQuery.Event} e Mouse over event
5837 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
5839 if ( this.blockMouseOverEvents
) {
5842 if ( !this.isDisabled() ) {
5843 item
= this.getTargetItem( e
);
5844 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
5850 * Handle mouse leave events.
5853 * @param {jQuery.Event} e Mouse over event
5855 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
5856 if ( !this.isDisabled() ) {
5857 this.highlightItem( null );
5863 * Handle key down events.
5866 * @param {KeyboardEvent} e Key down event
5868 OO
.ui
.SelectWidget
.prototype.onKeyDown = function ( e
) {
5871 currentItem
= this.getHighlightedItem() || this.getSelectedItem();
5873 if ( !this.isDisabled() && this.isVisible() ) {
5874 switch ( e
.keyCode
) {
5875 case OO
.ui
.Keys
.ENTER
:
5876 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
5877 // Was only highlighted, now let's select it. No-op if already selected.
5878 this.chooseItem( currentItem
);
5883 case OO
.ui
.Keys
.LEFT
:
5884 this.clearKeyPressBuffer();
5885 nextItem
= this.getRelativeSelectableItem( currentItem
, -1 );
5888 case OO
.ui
.Keys
.DOWN
:
5889 case OO
.ui
.Keys
.RIGHT
:
5890 this.clearKeyPressBuffer();
5891 nextItem
= this.getRelativeSelectableItem( currentItem
, 1 );
5894 case OO
.ui
.Keys
.ESCAPE
:
5895 case OO
.ui
.Keys
.TAB
:
5896 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
5897 currentItem
.setHighlighted( false );
5899 this.unbindKeyDownListener();
5900 this.unbindKeyPressListener();
5901 // Don't prevent tabbing away / defocusing
5907 if ( nextItem
.constructor.static.highlightable
) {
5908 this.highlightItem( nextItem
);
5910 this.chooseItem( nextItem
);
5912 this.scrollItemIntoView( nextItem
);
5917 e
.stopPropagation();
5923 * Bind key down listener.
5927 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
5928 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler
, true );
5932 * Unbind key down listener.
5936 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
5937 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler
, true );
5941 * Scroll item into view, preventing spurious mouse highlight actions from happening.
5943 * @param {OO.ui.OptionWidget} item Item to scroll into view
5945 OO
.ui
.SelectWidget
.prototype.scrollItemIntoView = function ( item
) {
5947 // Chromium's Blink engine will generate spurious 'mouseover' events during programmatic scrolling
5948 // and around 100-150 ms after it is finished.
5949 this.blockMouseOverEvents
++;
5950 item
.scrollElementIntoView().done( function () {
5951 setTimeout( function () {
5952 widget
.blockMouseOverEvents
--;
5958 * Clear the key-press buffer
5962 OO
.ui
.SelectWidget
.prototype.clearKeyPressBuffer = function () {
5963 if ( this.keyPressBufferTimer
) {
5964 clearTimeout( this.keyPressBufferTimer
);
5965 this.keyPressBufferTimer
= null;
5967 this.keyPressBuffer
= '';
5971 * Handle key press events.
5974 * @param {KeyboardEvent} e Key press event
5976 OO
.ui
.SelectWidget
.prototype.onKeyPress = function ( e
) {
5977 var c
, filter
, item
;
5979 if ( !e
.charCode
) {
5980 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.keyPressBuffer
!== '' ) {
5981 this.keyPressBuffer
= this.keyPressBuffer
.substr( 0, this.keyPressBuffer
.length
- 1 );
5986 if ( String
.fromCodePoint
) {
5987 c
= String
.fromCodePoint( e
.charCode
);
5989 c
= String
.fromCharCode( e
.charCode
);
5992 if ( this.keyPressBufferTimer
) {
5993 clearTimeout( this.keyPressBufferTimer
);
5995 this.keyPressBufferTimer
= setTimeout( this.clearKeyPressBuffer
.bind( this ), 1500 );
5997 item
= this.getHighlightedItem() || this.getSelectedItem();
5999 if ( this.keyPressBuffer
=== c
) {
6000 // Common (if weird) special case: typing "xxxx" will cycle through all
6001 // the items beginning with "x".
6003 item
= this.getRelativeSelectableItem( item
, 1 );
6006 this.keyPressBuffer
+= c
;
6009 filter
= this.getItemMatcher( this.keyPressBuffer
, false );
6010 if ( !item
|| !filter( item
) ) {
6011 item
= this.getRelativeSelectableItem( item
, 1, filter
);
6014 if ( this.isVisible() && item
.constructor.static.highlightable
) {
6015 this.highlightItem( item
);
6017 this.chooseItem( item
);
6019 this.scrollItemIntoView( item
);
6023 e
.stopPropagation();
6027 * Get a matcher for the specific string
6030 * @param {string} s String to match against items
6031 * @param {boolean} [exact=false] Only accept exact matches
6032 * @return {Function} function ( OO.ui.OptionWidget ) => boolean
6034 OO
.ui
.SelectWidget
.prototype.getItemMatcher = function ( s
, exact
) {
6037 if ( s
.normalize
) {
6040 s
= exact
? s
.trim() : s
.replace( /^\s+/, '' );
6041 re
= '^\\s*' + s
.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
6045 re
= new RegExp( re
, 'i' );
6046 return function ( item
) {
6047 var matchText
= item
.getMatchText();
6048 if ( matchText
.normalize
) {
6049 matchText
= matchText
.normalize();
6051 return re
.test( matchText
);
6056 * Bind key press listener.
6060 OO
.ui
.SelectWidget
.prototype.bindKeyPressListener = function () {
6061 this.getElementWindow().addEventListener( 'keypress', this.onKeyPressHandler
, true );
6065 * Unbind key down listener.
6067 * If you override this, be sure to call this.clearKeyPressBuffer() from your
6072 OO
.ui
.SelectWidget
.prototype.unbindKeyPressListener = function () {
6073 this.getElementWindow().removeEventListener( 'keypress', this.onKeyPressHandler
, true );
6074 this.clearKeyPressBuffer();
6078 * Visibility change handler
6081 * @param {boolean} visible
6083 OO
.ui
.SelectWidget
.prototype.onToggle = function ( visible
) {
6085 this.clearKeyPressBuffer();
6090 * Get the closest item to a jQuery.Event.
6093 * @param {jQuery.Event} e
6094 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
6096 OO
.ui
.SelectWidget
.prototype.getTargetItem = function ( e
) {
6097 return $( e
.target
).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
6101 * Get selected item.
6103 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
6105 OO
.ui
.SelectWidget
.prototype.getSelectedItem = function () {
6108 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6109 if ( this.items
[ i
].isSelected() ) {
6110 return this.items
[ i
];
6117 * Get highlighted item.
6119 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
6121 OO
.ui
.SelectWidget
.prototype.getHighlightedItem = function () {
6124 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6125 if ( this.items
[ i
].isHighlighted() ) {
6126 return this.items
[ i
];
6133 * Toggle pressed state.
6135 * Press is a state that occurs when a user mouses down on an item, but
6136 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
6137 * until the user releases the mouse.
6139 * @param {boolean} pressed An option is being pressed
6141 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
6142 if ( pressed
=== undefined ) {
6143 pressed
= !this.pressed
;
6145 if ( pressed
!== this.pressed
) {
6147 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
6148 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
6149 this.pressed
= pressed
;
6154 * Highlight an option. If the `item` param is omitted, no options will be highlighted
6155 * and any existing highlight will be removed. The highlight is mutually exclusive.
6157 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
6161 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
6162 var i
, len
, highlighted
,
6165 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6166 highlighted
= this.items
[ i
] === item
;
6167 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
6168 this.items
[ i
].setHighlighted( highlighted
);
6173 this.emit( 'highlight', item
);
6180 * Fetch an item by its label.
6182 * @param {string} label Label of the item to select.
6183 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
6184 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
6186 OO
.ui
.SelectWidget
.prototype.getItemFromLabel = function ( label
, prefix
) {
6188 len
= this.items
.length
,
6189 filter
= this.getItemMatcher( label
, true );
6191 for ( i
= 0; i
< len
; i
++ ) {
6192 item
= this.items
[ i
];
6193 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
6200 filter
= this.getItemMatcher( label
, false );
6201 for ( i
= 0; i
< len
; i
++ ) {
6202 item
= this.items
[ i
];
6203 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
6219 * Programmatically select an option by its label. If the item does not exist,
6220 * all options will be deselected.
6222 * @param {string} [label] Label of the item to select.
6223 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
6227 OO
.ui
.SelectWidget
.prototype.selectItemByLabel = function ( label
, prefix
) {
6228 var itemFromLabel
= this.getItemFromLabel( label
, !!prefix
);
6229 if ( label
=== undefined || !itemFromLabel
) {
6230 return this.selectItem();
6232 return this.selectItem( itemFromLabel
);
6236 * Programmatically select an option by its data. If the `data` parameter is omitted,
6237 * or if the item does not exist, all options will be deselected.
6239 * @param {Object|string} [data] Value of the item to select, omit to deselect all
6243 OO
.ui
.SelectWidget
.prototype.selectItemByData = function ( data
) {
6244 var itemFromData
= this.getItemFromData( data
);
6245 if ( data
=== undefined || !itemFromData
) {
6246 return this.selectItem();
6248 return this.selectItem( itemFromData
);
6252 * Programmatically select an option by its reference. If the `item` parameter is omitted,
6253 * all options will be deselected.
6255 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
6259 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
6260 var i
, len
, selected
,
6263 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6264 selected
= this.items
[ i
] === item
;
6265 if ( this.items
[ i
].isSelected() !== selected
) {
6266 this.items
[ i
].setSelected( selected
);
6271 this.emit( 'select', item
);
6280 * Press is a state that occurs when a user mouses down on an item, but has not
6281 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
6282 * releases the mouse.
6284 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
6288 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
6289 var i
, len
, pressed
,
6292 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6293 pressed
= this.items
[ i
] === item
;
6294 if ( this.items
[ i
].isPressed() !== pressed
) {
6295 this.items
[ i
].setPressed( pressed
);
6300 this.emit( 'press', item
);
6309 * Note that ‘choose’ should never be modified programmatically. A user can choose
6310 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
6311 * use the #selectItem method.
6313 * This method is identical to #selectItem, but may vary in subclasses that take additional action
6314 * when users choose an item with the keyboard or mouse.
6316 * @param {OO.ui.OptionWidget} item Item to choose
6320 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
6322 this.selectItem( item
);
6323 this.emit( 'choose', item
);
6330 * Get an option by its position relative to the specified item (or to the start of the option array,
6331 * if item is `null`). The direction in which to search through the option array is specified with a
6332 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
6333 * `null` if there are no options in the array.
6335 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
6336 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
6337 * @param {Function} [filter] Only consider items for which this function returns
6338 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
6339 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
6341 OO
.ui
.SelectWidget
.prototype.getRelativeSelectableItem = function ( item
, direction
, filter
) {
6342 var currentIndex
, nextIndex
, i
,
6343 increase
= direction
> 0 ? 1 : -1,
6344 len
= this.items
.length
;
6346 if ( item
instanceof OO
.ui
.OptionWidget
) {
6347 currentIndex
= this.items
.indexOf( item
);
6348 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
6350 // If no item is selected and moving forward, start at the beginning.
6351 // If moving backward, start at the end.
6352 nextIndex
= direction
> 0 ? 0 : len
- 1;
6355 for ( i
= 0; i
< len
; i
++ ) {
6356 item
= this.items
[ nextIndex
];
6358 item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() &&
6359 ( !filter
|| filter( item
) )
6363 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
6369 * Get the next selectable item or `null` if there are no selectable items.
6370 * Disabled options and menu-section markers and breaks are not selectable.
6372 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
6374 OO
.ui
.SelectWidget
.prototype.getFirstSelectableItem = function () {
6375 return this.getRelativeSelectableItem( null, 1 );
6379 * Add an array of options to the select. Optionally, an index number can be used to
6380 * specify an insertion point.
6382 * @param {OO.ui.OptionWidget[]} items Items to add
6383 * @param {number} [index] Index to insert items after
6387 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
6389 OO
.ui
.mixin
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
6391 // Always provide an index, even if it was omitted
6392 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
6398 * Remove the specified array of options from the select. Options will be detached
6399 * from the DOM, not removed, so they can be reused later. To remove all options from
6400 * the select, you may wish to use the #clearItems method instead.
6402 * @param {OO.ui.OptionWidget[]} items Items to remove
6406 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
6409 // Deselect items being removed
6410 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
6412 if ( item
.isSelected() ) {
6413 this.selectItem( null );
6418 OO
.ui
.mixin
.GroupWidget
.prototype.removeItems
.call( this, items
);
6420 this.emit( 'remove', items
);
6426 * Clear all options from the select. Options will be detached from the DOM, not removed,
6427 * so that they can be reused later. To remove a subset of options from the select, use
6428 * the #removeItems method.
6433 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
6434 var items
= this.items
.slice();
6437 OO
.ui
.mixin
.GroupWidget
.prototype.clearItems
.call( this );
6440 this.selectItem( null );
6442 this.emit( 'remove', items
);
6448 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
6449 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
6450 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
6451 * options. For more information about options and selects, please see the
6452 * [OOjs UI documentation on MediaWiki][1].
6455 * // Decorated options in a select widget
6456 * var select = new OO.ui.SelectWidget( {
6458 * new OO.ui.DecoratedOptionWidget( {
6460 * label: 'Option with icon',
6463 * new OO.ui.DecoratedOptionWidget( {
6465 * label: 'Option with indicator',
6470 * $( 'body' ).append( select.$element );
6472 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
6475 * @extends OO.ui.OptionWidget
6476 * @mixins OO.ui.mixin.IconElement
6477 * @mixins OO.ui.mixin.IndicatorElement
6480 * @param {Object} [config] Configuration options
6482 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
6483 // Parent constructor
6484 OO
.ui
.DecoratedOptionWidget
.parent
.call( this, config
);
6486 // Mixin constructors
6487 OO
.ui
.mixin
.IconElement
.call( this, config
);
6488 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
6492 .addClass( 'oo-ui-decoratedOptionWidget' )
6493 .prepend( this.$icon
)
6494 .append( this.$indicator
);
6499 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
6500 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IconElement
);
6501 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IndicatorElement
);
6504 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
6505 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
6506 * the [OOjs UI documentation on MediaWiki] [1] for more information.
6508 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
6511 * @extends OO.ui.DecoratedOptionWidget
6514 * @param {Object} [config] Configuration options
6516 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
6517 // Configuration initialization
6518 config
= $.extend( { icon
: 'check' }, config
);
6520 // Parent constructor
6521 OO
.ui
.MenuOptionWidget
.parent
.call( this, config
);
6525 .attr( 'role', 'menuitem' )
6526 .addClass( 'oo-ui-menuOptionWidget' );
6531 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
6533 /* Static Properties */
6539 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
6542 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
6543 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
6546 * var myDropdown = new OO.ui.DropdownWidget( {
6549 * new OO.ui.MenuSectionOptionWidget( {
6552 * new OO.ui.MenuOptionWidget( {
6554 * label: 'Welsh Corgi'
6556 * new OO.ui.MenuOptionWidget( {
6558 * label: 'Standard Poodle'
6560 * new OO.ui.MenuSectionOptionWidget( {
6563 * new OO.ui.MenuOptionWidget( {
6570 * $( 'body' ).append( myDropdown.$element );
6573 * @extends OO.ui.DecoratedOptionWidget
6576 * @param {Object} [config] Configuration options
6578 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
6579 // Parent constructor
6580 OO
.ui
.MenuSectionOptionWidget
.parent
.call( this, config
);
6583 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' );
6588 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
6590 /* Static Properties */
6596 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
6602 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
6605 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
6606 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
6607 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
6608 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
6609 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
6610 * and customized to be opened, closed, and displayed as needed.
6612 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
6613 * mouse outside the menu.
6615 * Menus also have support for keyboard interaction:
6617 * - Enter/Return key: choose and select a menu option
6618 * - Up-arrow key: highlight the previous menu option
6619 * - Down-arrow key: highlight the next menu option
6620 * - Esc key: hide the menu
6622 * Unlike most widgets, MenuSelectWidget is initially hidden and must be shown by calling #toggle.
6624 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
6625 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
6628 * @extends OO.ui.SelectWidget
6629 * @mixins OO.ui.mixin.ClippableElement
6632 * @param {Object} [config] Configuration options
6633 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
6634 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
6635 * and {@link OO.ui.mixin.LookupElement LookupElement}
6636 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
6637 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiselectWidget CapsuleMultiselectWidget}
6638 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
6639 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
6640 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
6641 * that button, unless the button (or its parent widget) is passed in here.
6642 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
6643 * @cfg {boolean} [hideOnChoose=true] Hide the menu when the user chooses an option.
6644 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
6646 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
6647 // Configuration initialization
6648 config
= config
|| {};
6650 // Parent constructor
6651 OO
.ui
.MenuSelectWidget
.parent
.call( this, config
);
6653 // Mixin constructors
6654 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
6657 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
6658 this.hideOnChoose
= config
.hideOnChoose
=== undefined || !!config
.hideOnChoose
;
6659 this.filterFromInput
= !!config
.filterFromInput
;
6660 this.$input
= config
.$input
? config
.$input
: config
.input
? config
.input
.$input
: null;
6661 this.$widget
= config
.widget
? config
.widget
.$element
: null;
6662 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
6663 this.onInputEditHandler
= OO
.ui
.debounce( this.updateItemVisibility
.bind( this ), 100 );
6667 .addClass( 'oo-ui-menuSelectWidget' )
6668 .attr( 'role', 'menu' );
6670 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
6671 // that reference properties not initialized at that time of parent class construction
6672 // TODO: Find a better way to handle post-constructor setup
6673 this.visible
= false;
6674 this.$element
.addClass( 'oo-ui-element-hidden' );
6679 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
6680 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.ClippableElement
);
6685 * Handles document mouse down events.
6688 * @param {MouseEvent} e Mouse down event
6690 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
6692 !OO
.ui
.contains( this.$element
[ 0 ], e
.target
, true ) &&
6693 ( !this.$widget
|| !OO
.ui
.contains( this.$widget
[ 0 ], e
.target
, true ) )
6695 this.toggle( false );
6702 OO
.ui
.MenuSelectWidget
.prototype.onKeyDown = function ( e
) {
6703 var currentItem
= this.getHighlightedItem() || this.getSelectedItem();
6705 if ( !this.isDisabled() && this.isVisible() ) {
6706 switch ( e
.keyCode
) {
6707 case OO
.ui
.Keys
.LEFT
:
6708 case OO
.ui
.Keys
.RIGHT
:
6709 // Do nothing if a text field is associated, arrow keys will be handled natively
6710 if ( !this.$input
) {
6711 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
6714 case OO
.ui
.Keys
.ESCAPE
:
6715 case OO
.ui
.Keys
.TAB
:
6716 if ( currentItem
) {
6717 currentItem
.setHighlighted( false );
6719 this.toggle( false );
6720 // Don't prevent tabbing away, prevent defocusing
6721 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
6723 e
.stopPropagation();
6727 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
6734 * Update menu item visibility after input changes.
6738 OO
.ui
.MenuSelectWidget
.prototype.updateItemVisibility = function () {
6739 var i
, item
, visible
,
6741 len
= this.items
.length
,
6742 showAll
= !this.isVisible(),
6743 filter
= showAll
? null : this.getItemMatcher( this.$input
.val() );
6745 for ( i
= 0; i
< len
; i
++ ) {
6746 item
= this.items
[ i
];
6747 if ( item
instanceof OO
.ui
.OptionWidget
) {
6748 visible
= showAll
|| filter( item
);
6749 anyVisible
= anyVisible
|| visible
;
6750 item
.toggle( visible
);
6754 this.$element
.toggleClass( 'oo-ui-menuSelectWidget-invisible', !anyVisible
);
6756 // Reevaluate clipping
6763 OO
.ui
.MenuSelectWidget
.prototype.bindKeyDownListener = function () {
6764 if ( this.$input
) {
6765 this.$input
.on( 'keydown', this.onKeyDownHandler
);
6767 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyDownListener
.call( this );
6774 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyDownListener = function () {
6775 if ( this.$input
) {
6776 this.$input
.off( 'keydown', this.onKeyDownHandler
);
6778 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyDownListener
.call( this );
6785 OO
.ui
.MenuSelectWidget
.prototype.bindKeyPressListener = function () {
6786 if ( this.$input
) {
6787 if ( this.filterFromInput
) {
6788 this.$input
.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
6791 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyPressListener
.call( this );
6798 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyPressListener = function () {
6799 if ( this.$input
) {
6800 if ( this.filterFromInput
) {
6801 this.$input
.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
6802 this.updateItemVisibility();
6805 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyPressListener
.call( this );
6812 * When a user chooses an item, the menu is closed, unless the hideOnChoose config option is set to false.
6814 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
6815 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
6817 * @param {OO.ui.OptionWidget} item Item to choose
6820 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
6821 OO
.ui
.MenuSelectWidget
.parent
.prototype.chooseItem
.call( this, item
);
6822 if ( this.hideOnChoose
) {
6823 this.toggle( false );
6831 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
6833 OO
.ui
.MenuSelectWidget
.parent
.prototype.addItems
.call( this, items
, index
);
6835 // Reevaluate clipping
6844 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
6846 OO
.ui
.MenuSelectWidget
.parent
.prototype.removeItems
.call( this, items
);
6848 // Reevaluate clipping
6857 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
6859 OO
.ui
.MenuSelectWidget
.parent
.prototype.clearItems
.call( this );
6861 // Reevaluate clipping
6868 * Toggle visibility of the menu. The menu is initially hidden and must be shown by calling
6869 * `.toggle( true )` after its #$element is attached to the DOM.
6871 * Do not show the menu while it is not attached to the DOM. The calculations required to display
6872 * it in the right place and with the right dimensions only work correctly while it is attached.
6873 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
6874 * strictly enforced, so currently it only generates a warning in the browser console.
6878 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
6881 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
6882 change
= visible
!== this.isVisible();
6884 if ( visible
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
6885 OO
.ui
.warnDeprecation( 'MenuSelectWidget#toggle: Before calling this method, the menu must be attached to the DOM.' );
6886 this.warnedUnattached
= true;
6890 OO
.ui
.MenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
6894 this.bindKeyDownListener();
6895 this.bindKeyPressListener();
6897 this.toggleClipping( true );
6899 if ( this.getSelectedItem() ) {
6900 this.getSelectedItem().scrollElementIntoView( { duration
: 0 } );
6904 if ( this.autoHide
) {
6905 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
6908 this.unbindKeyDownListener();
6909 this.unbindKeyPressListener();
6910 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
6911 this.toggleClipping( false );
6919 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
6920 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
6921 * users can interact with it.
6923 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
6924 * OO.ui.DropdownInputWidget instead.
6927 * // Example: A DropdownWidget with a menu that contains three options
6928 * var dropDown = new OO.ui.DropdownWidget( {
6929 * label: 'Dropdown menu: Select a menu option',
6932 * new OO.ui.MenuOptionWidget( {
6936 * new OO.ui.MenuOptionWidget( {
6940 * new OO.ui.MenuOptionWidget( {
6948 * $( 'body' ).append( dropDown.$element );
6950 * dropDown.getMenu().selectItemByData( 'b' );
6952 * dropDown.getMenu().getSelectedItem().getData(); // returns 'b'
6954 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
6956 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
6959 * @extends OO.ui.Widget
6960 * @mixins OO.ui.mixin.IconElement
6961 * @mixins OO.ui.mixin.IndicatorElement
6962 * @mixins OO.ui.mixin.LabelElement
6963 * @mixins OO.ui.mixin.TitledElement
6964 * @mixins OO.ui.mixin.TabIndexedElement
6967 * @param {Object} [config] Configuration options
6968 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
6969 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
6970 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
6971 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
6973 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
6974 // Configuration initialization
6975 config
= $.extend( { indicator
: 'down' }, config
);
6977 // Parent constructor
6978 OO
.ui
.DropdownWidget
.parent
.call( this, config
);
6980 // Properties (must be set before TabIndexedElement constructor call)
6981 this.$handle
= this.$( '<span>' );
6982 this.$overlay
= config
.$overlay
|| this.$element
;
6984 // Mixin constructors
6985 OO
.ui
.mixin
.IconElement
.call( this, config
);
6986 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
6987 OO
.ui
.mixin
.LabelElement
.call( this, config
);
6988 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
6989 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
6992 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend( {
6994 $container
: this.$element
6999 click
: this.onClick
.bind( this ),
7000 keydown
: this.onKeyDown
.bind( this ),
7001 // Hack? Handle type-to-search when menu is not expanded and not handling its own events
7002 keypress
: this.menu
.onKeyPressHandler
,
7003 blur
: this.menu
.clearKeyPressBuffer
.bind( this.menu
)
7005 this.menu
.connect( this, {
7006 select
: 'onMenuSelect',
7007 toggle
: 'onMenuToggle'
7012 .addClass( 'oo-ui-dropdownWidget-handle' )
7013 .append( this.$icon
, this.$label
, this.$indicator
);
7015 .addClass( 'oo-ui-dropdownWidget' )
7016 .append( this.$handle
);
7017 this.$overlay
.append( this.menu
.$element
);
7022 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
7023 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IconElement
);
7024 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IndicatorElement
);
7025 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.LabelElement
);
7026 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TitledElement
);
7027 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TabIndexedElement
);
7034 * @return {OO.ui.MenuSelectWidget} Menu of widget
7036 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
7041 * Handles menu select events.
7044 * @param {OO.ui.MenuOptionWidget} item Selected menu item
7046 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
7050 this.setLabel( null );
7054 selectedLabel
= item
.getLabel();
7056 // If the label is a DOM element, clone it, because setLabel will append() it
7057 if ( selectedLabel
instanceof jQuery
) {
7058 selectedLabel
= selectedLabel
.clone();
7061 this.setLabel( selectedLabel
);
7065 * Handle menu toggle events.
7068 * @param {boolean} isVisible Menu toggle event
7070 OO
.ui
.DropdownWidget
.prototype.onMenuToggle = function ( isVisible
) {
7071 this.$element
.toggleClass( 'oo-ui-dropdownWidget-open', isVisible
);
7075 * Handle mouse click events.
7078 * @param {jQuery.Event} e Mouse click event
7080 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
7081 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
7088 * Handle key down events.
7091 * @param {jQuery.Event} e Key down event
7093 OO
.ui
.DropdownWidget
.prototype.onKeyDown = function ( e
) {
7095 !this.isDisabled() &&
7097 e
.which
=== OO
.ui
.Keys
.ENTER
||
7099 !this.menu
.isVisible() &&
7101 e
.which
=== OO
.ui
.Keys
.SPACE
||
7102 e
.which
=== OO
.ui
.Keys
.UP
||
7103 e
.which
=== OO
.ui
.Keys
.DOWN
7114 * RadioOptionWidget is an option widget that looks like a radio button.
7115 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
7116 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
7118 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
7121 * @extends OO.ui.OptionWidget
7124 * @param {Object} [config] Configuration options
7126 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
7127 // Configuration initialization
7128 config
= config
|| {};
7130 // Properties (must be done before parent constructor which calls #setDisabled)
7131 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
7133 // Parent constructor
7134 OO
.ui
.RadioOptionWidget
.parent
.call( this, config
);
7137 // Remove implicit role, we're handling it ourselves
7138 this.radio
.$input
.attr( 'role', 'presentation' );
7140 .addClass( 'oo-ui-radioOptionWidget' )
7141 .attr( 'role', 'radio' )
7142 .attr( 'aria-checked', 'false' )
7143 .removeAttr( 'aria-selected' )
7144 .prepend( this.radio
.$element
);
7149 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
7151 /* Static Properties */
7157 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
7163 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
7169 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
7175 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
7182 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
7183 OO
.ui
.RadioOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
7185 this.radio
.setSelected( state
);
7187 .attr( 'aria-checked', state
.toString() )
7188 .removeAttr( 'aria-selected' );
7196 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
7197 OO
.ui
.RadioOptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
7199 this.radio
.setDisabled( this.isDisabled() );
7205 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
7206 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
7207 * an interface for adding, removing and selecting options.
7208 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
7210 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7211 * OO.ui.RadioSelectInputWidget instead.
7214 * // A RadioSelectWidget with RadioOptions.
7215 * var option1 = new OO.ui.RadioOptionWidget( {
7217 * label: 'Selected radio option'
7220 * var option2 = new OO.ui.RadioOptionWidget( {
7222 * label: 'Unselected radio option'
7225 * var radioSelect=new OO.ui.RadioSelectWidget( {
7226 * items: [ option1, option2 ]
7229 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
7230 * radioSelect.selectItem( option1 );
7232 * $( 'body' ).append( radioSelect.$element );
7234 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
7238 * @extends OO.ui.SelectWidget
7239 * @mixins OO.ui.mixin.TabIndexedElement
7242 * @param {Object} [config] Configuration options
7244 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
7245 // Parent constructor
7246 OO
.ui
.RadioSelectWidget
.parent
.call( this, config
);
7248 // Mixin constructors
7249 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
7253 focus
: this.bindKeyDownListener
.bind( this ),
7254 blur
: this.unbindKeyDownListener
.bind( this )
7259 .addClass( 'oo-ui-radioSelectWidget' )
7260 .attr( 'role', 'radiogroup' );
7265 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
7266 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
7269 * MultioptionWidgets are special elements that can be selected and configured with data. The
7270 * data is often unique for each option, but it does not have to be. MultioptionWidgets are used
7271 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
7272 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
7274 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Multioptions
7277 * @extends OO.ui.Widget
7278 * @mixins OO.ui.mixin.ItemWidget
7279 * @mixins OO.ui.mixin.LabelElement
7282 * @param {Object} [config] Configuration options
7283 * @cfg {boolean} [selected=false] Whether the option is initially selected
7285 OO
.ui
.MultioptionWidget
= function OoUiMultioptionWidget( config
) {
7286 // Configuration initialization
7287 config
= config
|| {};
7289 // Parent constructor
7290 OO
.ui
.MultioptionWidget
.parent
.call( this, config
);
7292 // Mixin constructors
7293 OO
.ui
.mixin
.ItemWidget
.call( this );
7294 OO
.ui
.mixin
.LabelElement
.call( this, config
);
7297 this.selected
= null;
7301 .addClass( 'oo-ui-multioptionWidget' )
7302 .append( this.$label
);
7303 this.setSelected( config
.selected
);
7308 OO
.inheritClass( OO
.ui
.MultioptionWidget
, OO
.ui
.Widget
);
7309 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.ItemWidget
);
7310 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.LabelElement
);
7317 * A change event is emitted when the selected state of the option changes.
7319 * @param {boolean} selected Whether the option is now selected
7325 * Check if the option is selected.
7327 * @return {boolean} Item is selected
7329 OO
.ui
.MultioptionWidget
.prototype.isSelected = function () {
7330 return this.selected
;
7334 * Set the option’s selected state. In general, all modifications to the selection
7335 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
7336 * method instead of this method.
7338 * @param {boolean} [state=false] Select option
7341 OO
.ui
.MultioptionWidget
.prototype.setSelected = function ( state
) {
7343 if ( this.selected
!== state
) {
7344 this.selected
= state
;
7345 this.emit( 'change', state
);
7346 this.$element
.toggleClass( 'oo-ui-multioptionWidget-selected', state
);
7352 * MultiselectWidget allows selecting multiple options from a list.
7354 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
7356 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
7360 * @extends OO.ui.Widget
7361 * @mixins OO.ui.mixin.GroupWidget
7364 * @param {Object} [config] Configuration options
7365 * @cfg {OO.ui.MultioptionWidget[]} [items] An array of options to add to the multiselect.
7367 OO
.ui
.MultiselectWidget
= function OoUiMultiselectWidget( config
) {
7368 // Parent constructor
7369 OO
.ui
.MultiselectWidget
.parent
.call( this, config
);
7371 // Configuration initialization
7372 config
= config
|| {};
7374 // Mixin constructors
7375 OO
.ui
.mixin
.GroupWidget
.call( this, config
);
7378 this.aggregate( { change
: 'select' } );
7379 // This is mostly for compatibility with CapsuleMultiselectWidget... normally, 'change' is emitted
7380 // by GroupElement only when items are added/removed
7381 this.connect( this, { select
: [ 'emit', 'change' ] } );
7384 if ( config
.items
) {
7385 this.addItems( config
.items
);
7387 this.$group
.addClass( 'oo-ui-multiselectWidget-group' );
7388 this.$element
.addClass( 'oo-ui-multiselectWidget' )
7389 .append( this.$group
);
7394 OO
.inheritClass( OO
.ui
.MultiselectWidget
, OO
.ui
.Widget
);
7395 OO
.mixinClass( OO
.ui
.MultiselectWidget
, OO
.ui
.mixin
.GroupWidget
);
7402 * A change event is emitted when the set of items changes, or an item is selected or deselected.
7408 * A select event is emitted when an item is selected or deselected.
7414 * Get options that are selected.
7416 * @return {OO.ui.MultioptionWidget[]} Selected options
7418 OO
.ui
.MultiselectWidget
.prototype.getSelectedItems = function () {
7419 return this.items
.filter( function ( item
) {
7420 return item
.isSelected();
7425 * Get the data of options that are selected.
7427 * @return {Object[]|string[]} Values of selected options
7429 OO
.ui
.MultiselectWidget
.prototype.getSelectedItemsData = function () {
7430 return this.getSelectedItems().map( function ( item
) {
7436 * Select options by reference. Options not mentioned in the `items` array will be deselected.
7438 * @param {OO.ui.MultioptionWidget[]} items Items to select
7441 OO
.ui
.MultiselectWidget
.prototype.selectItems = function ( items
) {
7442 this.items
.forEach( function ( item
) {
7443 var selected
= items
.indexOf( item
) !== -1;
7444 item
.setSelected( selected
);
7450 * Select items by their data. Options not mentioned in the `datas` array will be deselected.
7452 * @param {Object[]|string[]} datas Values of items to select
7455 OO
.ui
.MultiselectWidget
.prototype.selectItemsByData = function ( datas
) {
7458 items
= datas
.map( function ( data
) {
7459 return widget
.getItemFromData( data
);
7461 this.selectItems( items
);
7466 * CheckboxMultioptionWidget is an option widget that looks like a checkbox.
7467 * The class is used with OO.ui.CheckboxMultiselectWidget to create a selection of checkbox options.
7468 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
7470 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
7473 * @extends OO.ui.MultioptionWidget
7476 * @param {Object} [config] Configuration options
7478 OO
.ui
.CheckboxMultioptionWidget
= function OoUiCheckboxMultioptionWidget( config
) {
7479 // Configuration initialization
7480 config
= config
|| {};
7482 // Properties (must be done before parent constructor which calls #setDisabled)
7483 this.checkbox
= new OO
.ui
.CheckboxInputWidget();
7485 // Parent constructor
7486 OO
.ui
.CheckboxMultioptionWidget
.parent
.call( this, config
);
7489 this.checkbox
.on( 'change', this.onCheckboxChange
.bind( this ) );
7490 this.$element
.on( 'keydown', this.onKeyDown
.bind( this ) );
7494 .addClass( 'oo-ui-checkboxMultioptionWidget' )
7495 .prepend( this.checkbox
.$element
);
7500 OO
.inheritClass( OO
.ui
.CheckboxMultioptionWidget
, OO
.ui
.MultioptionWidget
);
7502 /* Static Properties */
7508 OO
.ui
.CheckboxMultioptionWidget
.static.tagName
= 'label';
7513 * Handle checkbox selected state change.
7517 OO
.ui
.CheckboxMultioptionWidget
.prototype.onCheckboxChange = function () {
7518 this.setSelected( this.checkbox
.isSelected() );
7524 OO
.ui
.CheckboxMultioptionWidget
.prototype.setSelected = function ( state
) {
7525 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setSelected
.call( this, state
);
7526 this.checkbox
.setSelected( state
);
7533 OO
.ui
.CheckboxMultioptionWidget
.prototype.setDisabled = function ( disabled
) {
7534 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
7535 this.checkbox
.setDisabled( this.isDisabled() );
7542 OO
.ui
.CheckboxMultioptionWidget
.prototype.focus = function () {
7543 this.checkbox
.focus();
7547 * Handle key down events.
7550 * @param {jQuery.Event} e
7552 OO
.ui
.CheckboxMultioptionWidget
.prototype.onKeyDown = function ( e
) {
7554 element
= this.getElementGroup(),
7557 if ( e
.keyCode
=== OO
.ui
.Keys
.LEFT
|| e
.keyCode
=== OO
.ui
.Keys
.UP
) {
7558 nextItem
= element
.getRelativeFocusableItem( this, -1 );
7559 } else if ( e
.keyCode
=== OO
.ui
.Keys
.RIGHT
|| e
.keyCode
=== OO
.ui
.Keys
.DOWN
) {
7560 nextItem
= element
.getRelativeFocusableItem( this, 1 );
7570 * CheckboxMultiselectWidget is a {@link OO.ui.MultiselectWidget multiselect widget} that contains
7571 * checkboxes and is used together with OO.ui.CheckboxMultioptionWidget. The
7572 * CheckboxMultiselectWidget provides an interface for adding, removing and selecting options.
7573 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
7575 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7576 * OO.ui.CheckboxMultiselectInputWidget instead.
7579 * // A CheckboxMultiselectWidget with CheckboxMultioptions.
7580 * var option1 = new OO.ui.CheckboxMultioptionWidget( {
7583 * label: 'Selected checkbox'
7586 * var option2 = new OO.ui.CheckboxMultioptionWidget( {
7588 * label: 'Unselected checkbox'
7591 * var multiselect=new OO.ui.CheckboxMultiselectWidget( {
7592 * items: [ option1, option2 ]
7595 * $( 'body' ).append( multiselect.$element );
7597 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
7600 * @extends OO.ui.MultiselectWidget
7603 * @param {Object} [config] Configuration options
7605 OO
.ui
.CheckboxMultiselectWidget
= function OoUiCheckboxMultiselectWidget( config
) {
7606 // Parent constructor
7607 OO
.ui
.CheckboxMultiselectWidget
.parent
.call( this, config
);
7610 this.$lastClicked
= null;
7613 this.$group
.on( 'click', this.onClick
.bind( this ) );
7617 .addClass( 'oo-ui-checkboxMultiselectWidget' );
7622 OO
.inheritClass( OO
.ui
.CheckboxMultiselectWidget
, OO
.ui
.MultiselectWidget
);
7627 * Get an option by its position relative to the specified item (or to the start of the option array,
7628 * if item is `null`). The direction in which to search through the option array is specified with a
7629 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
7630 * `null` if there are no options in the array.
7632 * @param {OO.ui.CheckboxMultioptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
7633 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
7634 * @return {OO.ui.CheckboxMultioptionWidget|null} Item at position, `null` if there are no items in the select
7636 OO
.ui
.CheckboxMultiselectWidget
.prototype.getRelativeFocusableItem = function ( item
, direction
) {
7637 var currentIndex
, nextIndex
, i
,
7638 increase
= direction
> 0 ? 1 : -1,
7639 len
= this.items
.length
;
7642 currentIndex
= this.items
.indexOf( item
);
7643 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
7645 // If no item is selected and moving forward, start at the beginning.
7646 // If moving backward, start at the end.
7647 nextIndex
= direction
> 0 ? 0 : len
- 1;
7650 for ( i
= 0; i
< len
; i
++ ) {
7651 item
= this.items
[ nextIndex
];
7652 if ( item
&& !item
.isDisabled() ) {
7655 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
7661 * Handle click events on checkboxes.
7663 * @param {jQuery.Event} e
7665 OO
.ui
.CheckboxMultiselectWidget
.prototype.onClick = function ( e
) {
7666 var $options
, lastClickedIndex
, nowClickedIndex
, i
, direction
, wasSelected
, items
,
7667 $lastClicked
= this.$lastClicked
,
7668 $nowClicked
= $( e
.target
).closest( '.oo-ui-checkboxMultioptionWidget' )
7669 .not( '.oo-ui-widget-disabled' );
7671 // Allow selecting multiple options at once by Shift-clicking them
7672 if ( $lastClicked
&& $nowClicked
.length
&& e
.shiftKey
) {
7673 $options
= this.$group
.find( '.oo-ui-checkboxMultioptionWidget' );
7674 lastClickedIndex
= $options
.index( $lastClicked
);
7675 nowClickedIndex
= $options
.index( $nowClicked
);
7676 // If it's the same item, either the user is being silly, or it's a fake event generated by the
7677 // browser. In either case we don't need custom handling.
7678 if ( nowClickedIndex
!== lastClickedIndex
) {
7680 wasSelected
= items
[ nowClickedIndex
].isSelected();
7681 direction
= nowClickedIndex
> lastClickedIndex
? 1 : -1;
7683 // This depends on the DOM order of the items and the order of the .items array being the same.
7684 for ( i
= lastClickedIndex
; i
!== nowClickedIndex
; i
+= direction
) {
7685 if ( !items
[ i
].isDisabled() ) {
7686 items
[ i
].setSelected( !wasSelected
);
7689 // For the now-clicked element, use immediate timeout to allow the browser to do its own
7690 // handling first, then set our value. The order in which events happen is different for
7691 // clicks on the <input> and on the <label> and there are additional fake clicks fired for
7692 // non-click actions that change the checkboxes.
7694 setTimeout( function () {
7695 if ( !items
[ nowClickedIndex
].isDisabled() ) {
7696 items
[ nowClickedIndex
].setSelected( !wasSelected
);
7702 if ( $nowClicked
.length
) {
7703 this.$lastClicked
= $nowClicked
;
7708 * FloatingMenuSelectWidget is a menu that will stick under a specified
7709 * container, even when it is inserted elsewhere in the document (for example,
7710 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
7711 * menu from being clipped too aggresively.
7713 * The menu's position is automatically calculated and maintained when the menu
7714 * is toggled or the window is resized.
7716 * See OO.ui.ComboBoxInputWidget for an example of a widget that uses this class.
7719 * @extends OO.ui.MenuSelectWidget
7720 * @mixins OO.ui.mixin.FloatableElement
7723 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
7724 * Deprecated, omit this parameter and specify `$container` instead.
7725 * @param {Object} [config] Configuration options
7726 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
7728 OO
.ui
.FloatingMenuSelectWidget
= function OoUiFloatingMenuSelectWidget( inputWidget
, config
) {
7729 // Allow 'inputWidget' parameter and config for backwards compatibility
7730 if ( OO
.isPlainObject( inputWidget
) && config
=== undefined ) {
7731 config
= inputWidget
;
7732 inputWidget
= config
.inputWidget
;
7735 // Configuration initialization
7736 config
= config
|| {};
7738 // Parent constructor
7739 OO
.ui
.FloatingMenuSelectWidget
.parent
.call( this, config
);
7741 // Properties (must be set before mixin constructors)
7742 this.inputWidget
= inputWidget
; // For backwards compatibility
7743 this.$container
= config
.$container
|| this.inputWidget
.$element
;
7745 // Mixins constructors
7746 OO
.ui
.mixin
.FloatableElement
.call( this, $.extend( {}, config
, { $floatableContainer
: this.$container
} ) );
7749 this.$element
.addClass( 'oo-ui-floatingMenuSelectWidget' );
7750 // For backwards compatibility
7751 this.$element
.addClass( 'oo-ui-textInputMenuSelectWidget' );
7756 OO
.inheritClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.MenuSelectWidget
);
7757 OO
.mixinClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.mixin
.FloatableElement
);
7764 OO
.ui
.FloatingMenuSelectWidget
.prototype.toggle = function ( visible
) {
7766 visible
= visible
=== undefined ? !this.isVisible() : !!visible
;
7767 change
= visible
!== this.isVisible();
7769 if ( change
&& visible
) {
7770 // Make sure the width is set before the parent method runs.
7771 this.setIdealSize( this.$container
.width() );
7775 // This will call this.clip(), which is nonsensical since we're not positioned yet...
7776 OO
.ui
.FloatingMenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
7779 this.togglePositioning( this.isVisible() );
7786 * The old name for the FloatingMenuSelectWidget widget, provided for backwards-compatibility.
7789 * @extends OO.ui.FloatingMenuSelectWidget
7792 * @deprecated since v0.12.5.
7794 OO
.ui
.TextInputMenuSelectWidget
= function OoUiTextInputMenuSelectWidget() {
7795 OO
.ui
.warnDeprecation( 'TextInputMenuSelectWidget is deprecated. Use the FloatingMenuSelectWidget instead.' );
7796 // Parent constructor
7797 OO
.ui
.TextInputMenuSelectWidget
.parent
.apply( this, arguments
);
7800 OO
.inheritClass( OO
.ui
.TextInputMenuSelectWidget
, OO
.ui
.FloatingMenuSelectWidget
);
7803 * Progress bars visually display the status of an operation, such as a download,
7804 * and can be either determinate or indeterminate:
7806 * - **determinate** process bars show the percent of an operation that is complete.
7808 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
7809 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
7810 * not use percentages.
7812 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
7815 * // Examples of determinate and indeterminate progress bars.
7816 * var progressBar1 = new OO.ui.ProgressBarWidget( {
7819 * var progressBar2 = new OO.ui.ProgressBarWidget();
7821 * // Create a FieldsetLayout to layout progress bars
7822 * var fieldset = new OO.ui.FieldsetLayout;
7823 * fieldset.addItems( [
7824 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
7825 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
7827 * $( 'body' ).append( fieldset.$element );
7830 * @extends OO.ui.Widget
7833 * @param {Object} [config] Configuration options
7834 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
7835 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
7836 * By default, the progress bar is indeterminate.
7838 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
7839 // Configuration initialization
7840 config
= config
|| {};
7842 // Parent constructor
7843 OO
.ui
.ProgressBarWidget
.parent
.call( this, config
);
7846 this.$bar
= $( '<div>' );
7847 this.progress
= null;
7850 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
7851 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
7854 role
: 'progressbar',
7856 'aria-valuemax': 100
7858 .addClass( 'oo-ui-progressBarWidget' )
7859 .append( this.$bar
);
7864 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
7866 /* Static Properties */
7872 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
7877 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
7879 * @return {number|boolean} Progress percent
7881 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
7882 return this.progress
;
7886 * Set the percent of the process completed or `false` for an indeterminate process.
7888 * @param {number|boolean} progress Progress percent or `false` for indeterminate
7890 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
7891 this.progress
= progress
;
7893 if ( progress
!== false ) {
7894 this.$bar
.css( 'width', this.progress
+ '%' );
7895 this.$element
.attr( 'aria-valuenow', this.progress
);
7897 this.$bar
.css( 'width', '' );
7898 this.$element
.removeAttr( 'aria-valuenow' );
7900 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', progress
=== false );
7904 * InputWidget is the base class for all input widgets, which
7905 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
7906 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
7907 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
7909 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
7913 * @extends OO.ui.Widget
7914 * @mixins OO.ui.mixin.FlaggedElement
7915 * @mixins OO.ui.mixin.TabIndexedElement
7916 * @mixins OO.ui.mixin.TitledElement
7917 * @mixins OO.ui.mixin.AccessKeyedElement
7920 * @param {Object} [config] Configuration options
7921 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
7922 * @cfg {string} [value=''] The value of the input.
7923 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
7924 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
7925 * before it is accepted.
7927 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
7928 // Configuration initialization
7929 config
= config
|| {};
7931 // Parent constructor
7932 OO
.ui
.InputWidget
.parent
.call( this, config
);
7935 // See #reusePreInfuseDOM about config.$input
7936 this.$input
= config
.$input
|| this.getInputElement( config
);
7938 this.inputFilter
= config
.inputFilter
;
7940 // Mixin constructors
7941 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
7942 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
7943 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
7944 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$input
} ) );
7947 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
7951 .addClass( 'oo-ui-inputWidget-input' )
7952 .attr( 'name', config
.name
)
7953 .prop( 'disabled', this.isDisabled() );
7955 .addClass( 'oo-ui-inputWidget' )
7956 .append( this.$input
);
7957 this.setValue( config
.value
);
7959 this.setDir( config
.dir
);
7965 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
7966 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.FlaggedElement
);
7967 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TabIndexedElement
);
7968 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TitledElement
);
7969 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
7971 /* Static Properties */
7977 OO
.ui
.InputWidget
.static.supportsSimpleLabel
= true;
7979 /* Static Methods */
7984 OO
.ui
.InputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
7985 config
= OO
.ui
.InputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
7986 // Reusing $input lets browsers preserve inputted values across page reloads (T114134)
7987 config
.$input
= $( node
).find( '.oo-ui-inputWidget-input' );
7994 OO
.ui
.InputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
7995 var state
= OO
.ui
.InputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
7996 if ( config
.$input
&& config
.$input
.length
) {
7997 state
.value
= config
.$input
.val();
7998 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
7999 state
.focus
= config
.$input
.is( ':focus' );
8009 * A change event is emitted when the value of the input changes.
8011 * @param {string} value
8017 * Get input element.
8019 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
8020 * different circumstances. The element must have a `value` property (like form elements).
8023 * @param {Object} config Configuration options
8024 * @return {jQuery} Input element
8026 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
8027 return $( '<input>' );
8031 * Get input element's ID.
8033 * If the element already has an ID then that is returned, otherwise unique ID is
8034 * generated, set on the element, and returned.
8036 * @return {string} The ID of the element
8038 OO
.ui
.InputWidget
.prototype.getInputId = function () {
8039 var id
= this.$input
.attr( 'id' );
8041 if ( id
=== undefined ) {
8042 id
= OO
.ui
.generateElementId();
8043 this.$input
.attr( 'id', id
);
8050 * Handle potentially value-changing events.
8053 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
8055 OO
.ui
.InputWidget
.prototype.onEdit = function () {
8057 if ( !this.isDisabled() ) {
8058 // Allow the stack to clear so the value will be updated
8059 setTimeout( function () {
8060 widget
.setValue( widget
.$input
.val() );
8066 * Get the value of the input.
8068 * @return {string} Input value
8070 OO
.ui
.InputWidget
.prototype.getValue = function () {
8071 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
8072 // it, and we won't know unless they're kind enough to trigger a 'change' event.
8073 var value
= this.$input
.val();
8074 if ( this.value
!== value
) {
8075 this.setValue( value
);
8081 * Set the directionality of the input.
8083 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
8086 OO
.ui
.InputWidget
.prototype.setDir = function ( dir
) {
8087 this.$input
.prop( 'dir', dir
);
8092 * Set the value of the input.
8094 * @param {string} value New value
8098 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
8099 value
= this.cleanUpValue( value
);
8100 // Update the DOM if it has changed. Note that with cleanUpValue, it
8101 // is possible for the DOM value to change without this.value changing.
8102 if ( this.$input
.val() !== value
) {
8103 this.$input
.val( value
);
8105 if ( this.value
!== value
) {
8107 this.emit( 'change', this.value
);
8113 * Clean up incoming value.
8115 * Ensures value is a string, and converts undefined and null to empty string.
8118 * @param {string} value Original value
8119 * @return {string} Cleaned up value
8121 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
8122 if ( value
=== undefined || value
=== null ) {
8124 } else if ( this.inputFilter
) {
8125 return this.inputFilter( String( value
) );
8127 return String( value
);
8132 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
8133 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
8136 OO
.ui
.InputWidget
.prototype.simulateLabelClick = function () {
8137 OO
.ui
.warnDeprecation( 'InputWidget: simulateLabelClick() is deprecated.' );
8138 if ( !this.isDisabled() ) {
8139 if ( this.$input
.is( ':checkbox, :radio' ) ) {
8140 this.$input
.click();
8142 if ( this.$input
.is( ':input' ) ) {
8143 this.$input
[ 0 ].focus();
8151 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
8152 OO
.ui
.InputWidget
.parent
.prototype.setDisabled
.call( this, state
);
8153 if ( this.$input
) {
8154 this.$input
.prop( 'disabled', this.isDisabled() );
8164 OO
.ui
.InputWidget
.prototype.focus = function () {
8165 this.$input
[ 0 ].focus();
8174 OO
.ui
.InputWidget
.prototype.blur = function () {
8175 this.$input
[ 0 ].blur();
8182 OO
.ui
.InputWidget
.prototype.restorePreInfuseState = function ( state
) {
8183 OO
.ui
.InputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
8184 if ( state
.value
!== undefined && state
.value
!== this.getValue() ) {
8185 this.setValue( state
.value
);
8187 if ( state
.focus
) {
8193 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
8194 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
8195 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
8196 * HTML `<button>` (the default) or an HTML `<input>` tags. See the
8197 * [OOjs UI documentation on MediaWiki] [1] for more information.
8200 * // A ButtonInputWidget rendered as an HTML button, the default.
8201 * var button = new OO.ui.ButtonInputWidget( {
8202 * label: 'Input button',
8206 * $( 'body' ).append( button.$element );
8208 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
8211 * @extends OO.ui.InputWidget
8212 * @mixins OO.ui.mixin.ButtonElement
8213 * @mixins OO.ui.mixin.IconElement
8214 * @mixins OO.ui.mixin.IndicatorElement
8215 * @mixins OO.ui.mixin.LabelElement
8216 * @mixins OO.ui.mixin.TitledElement
8219 * @param {Object} [config] Configuration options
8220 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
8221 * @cfg {boolean} [useInputTag=false] Use an `<input>` tag instead of a `<button>` tag, the default.
8222 * Widgets configured to be an `<input>` do not support {@link #icon icons} and {@link #indicator indicators},
8223 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
8224 * be set to `true` when there’s need to support IE 6 in a form with multiple buttons.
8226 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
8227 // Configuration initialization
8228 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
8230 // See InputWidget#reusePreInfuseDOM about config.$input
8231 if ( config
.$input
) {
8232 config
.$input
.empty();
8235 // Properties (must be set before parent constructor, which calls #setValue)
8236 this.useInputTag
= config
.useInputTag
;
8238 // Parent constructor
8239 OO
.ui
.ButtonInputWidget
.parent
.call( this, config
);
8241 // Mixin constructors
8242 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
8243 OO
.ui
.mixin
.IconElement
.call( this, config
);
8244 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
8245 OO
.ui
.mixin
.LabelElement
.call( this, config
);
8246 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
8249 if ( !config
.useInputTag
) {
8250 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
8252 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
8257 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
8258 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.ButtonElement
);
8259 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IconElement
);
8260 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
8261 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.LabelElement
);
8262 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.TitledElement
);
8264 /* Static Properties */
8267 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
8268 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
8273 OO
.ui
.ButtonInputWidget
.static.supportsSimpleLabel
= false;
8281 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
8283 type
= [ 'button', 'submit', 'reset' ].indexOf( config
.type
) !== -1 ? config
.type
: 'button';
8284 return $( '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + type
+ '">' );
8290 * If #useInputTag is `true`, the label is set as the `value` of the `<input>` tag.
8292 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
8293 * text, or `null` for no label
8296 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
8297 if ( typeof label
=== 'function' ) {
8298 label
= OO
.ui
.resolveMsg( label
);
8301 if ( this.useInputTag
) {
8302 // Discard non-plaintext labels
8303 if ( typeof label
!== 'string' ) {
8307 this.$input
.val( label
);
8310 return OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.call( this, label
);
8314 * Set the value of the input.
8316 * This method is disabled for button inputs configured as {@link #useInputTag <input> tags}, as
8317 * they do not support {@link #value values}.
8319 * @param {string} value New value
8322 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
8323 if ( !this.useInputTag
) {
8324 OO
.ui
.ButtonInputWidget
.parent
.prototype.setValue
.call( this, value
);
8330 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
8331 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
8332 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
8333 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
8335 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
8338 * // An example of selected, unselected, and disabled checkbox inputs
8339 * var checkbox1=new OO.ui.CheckboxInputWidget( {
8343 * var checkbox2=new OO.ui.CheckboxInputWidget( {
8346 * var checkbox3=new OO.ui.CheckboxInputWidget( {
8350 * // Create a fieldset layout with fields for each checkbox.
8351 * var fieldset = new OO.ui.FieldsetLayout( {
8352 * label: 'Checkboxes'
8354 * fieldset.addItems( [
8355 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
8356 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
8357 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
8359 * $( 'body' ).append( fieldset.$element );
8361 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8364 * @extends OO.ui.InputWidget
8367 * @param {Object} [config] Configuration options
8368 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
8370 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
8371 // Configuration initialization
8372 config
= config
|| {};
8374 // Parent constructor
8375 OO
.ui
.CheckboxInputWidget
.parent
.call( this, config
);
8379 .addClass( 'oo-ui-checkboxInputWidget' )
8380 // Required for pretty styling in MediaWiki theme
8381 .append( $( '<span>' ) );
8382 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
8387 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
8389 /* Static Methods */
8394 OO
.ui
.CheckboxInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8395 var state
= OO
.ui
.CheckboxInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8396 state
.checked
= config
.$input
.prop( 'checked' );
8406 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
8407 return $( '<input>' ).attr( 'type', 'checkbox' );
8413 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
8415 if ( !this.isDisabled() ) {
8416 // Allow the stack to clear so the value will be updated
8417 setTimeout( function () {
8418 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
8424 * Set selection state of this checkbox.
8426 * @param {boolean} state `true` for selected
8429 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
8431 if ( this.selected
!== state
) {
8432 this.selected
= state
;
8433 this.$input
.prop( 'checked', this.selected
);
8434 this.emit( 'change', this.selected
);
8440 * Check if this checkbox is selected.
8442 * @return {boolean} Checkbox is selected
8444 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
8445 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
8446 // it, and we won't know unless they're kind enough to trigger a 'change' event.
8447 var selected
= this.$input
.prop( 'checked' );
8448 if ( this.selected
!== selected
) {
8449 this.setSelected( selected
);
8451 return this.selected
;
8457 OO
.ui
.CheckboxInputWidget
.prototype.restorePreInfuseState = function ( state
) {
8458 OO
.ui
.CheckboxInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
8459 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
8460 this.setSelected( state
.checked
);
8465 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
8466 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
8467 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
8468 * more information about input widgets.
8470 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
8471 * are no options. If no `value` configuration option is provided, the first option is selected.
8472 * If you need a state representing no value (no option being selected), use a DropdownWidget.
8474 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
8477 * // Example: A DropdownInputWidget with three options
8478 * var dropdownInput = new OO.ui.DropdownInputWidget( {
8480 * { data: 'a', label: 'First' },
8481 * { data: 'b', label: 'Second'},
8482 * { data: 'c', label: 'Third' }
8485 * $( 'body' ).append( dropdownInput.$element );
8487 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8490 * @extends OO.ui.InputWidget
8491 * @mixins OO.ui.mixin.TitledElement
8494 * @param {Object} [config] Configuration options
8495 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
8496 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
8498 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
8499 // Configuration initialization
8500 config
= config
|| {};
8502 // See InputWidget#reusePreInfuseDOM about config.$input
8503 if ( config
.$input
) {
8504 config
.$input
.addClass( 'oo-ui-element-hidden' );
8507 // Properties (must be done before parent constructor which calls #setDisabled)
8508 this.dropdownWidget
= new OO
.ui
.DropdownWidget( config
.dropdown
);
8510 // Parent constructor
8511 OO
.ui
.DropdownInputWidget
.parent
.call( this, config
);
8513 // Mixin constructors
8514 OO
.ui
.mixin
.TitledElement
.call( this, config
);
8517 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
8520 this.setOptions( config
.options
|| [] );
8522 .addClass( 'oo-ui-dropdownInputWidget' )
8523 .append( this.dropdownWidget
.$element
);
8528 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
8529 OO
.mixinClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.mixin
.TitledElement
);
8537 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
8538 return $( '<input>' ).attr( 'type', 'hidden' );
8542 * Handles menu select events.
8545 * @param {OO.ui.MenuOptionWidget} item Selected menu item
8547 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
8548 this.setValue( item
.getData() );
8554 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
8555 value
= this.cleanUpValue( value
);
8556 this.dropdownWidget
.getMenu().selectItemByData( value
);
8557 OO
.ui
.DropdownInputWidget
.parent
.prototype.setValue
.call( this, value
);
8564 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
8565 this.dropdownWidget
.setDisabled( state
);
8566 OO
.ui
.DropdownInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
8571 * Set the options available for this input.
8573 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
8576 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
8578 value
= this.getValue(),
8581 // Rebuild the dropdown menu
8582 this.dropdownWidget
.getMenu()
8584 .addItems( options
.map( function ( opt
) {
8585 var optValue
= widget
.cleanUpValue( opt
.data
);
8586 return new OO
.ui
.MenuOptionWidget( {
8588 label
: opt
.label
!== undefined ? opt
.label
: optValue
8592 // Restore the previous value, or reset to something sensible
8593 if ( this.dropdownWidget
.getMenu().getItemFromData( value
) ) {
8594 // Previous value is still available, ensure consistency with the dropdown
8595 this.setValue( value
);
8597 // No longer valid, reset
8598 if ( options
.length
) {
8599 this.setValue( options
[ 0 ].data
);
8609 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
8610 this.dropdownWidget
.getMenu().toggle( true );
8617 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
8618 this.dropdownWidget
.getMenu().toggle( false );
8623 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
8624 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
8625 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
8626 * please see the [OOjs UI documentation on MediaWiki][1].
8628 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
8631 * // An example of selected, unselected, and disabled radio inputs
8632 * var radio1 = new OO.ui.RadioInputWidget( {
8636 * var radio2 = new OO.ui.RadioInputWidget( {
8639 * var radio3 = new OO.ui.RadioInputWidget( {
8643 * // Create a fieldset layout with fields for each radio button.
8644 * var fieldset = new OO.ui.FieldsetLayout( {
8645 * label: 'Radio inputs'
8647 * fieldset.addItems( [
8648 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
8649 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
8650 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
8652 * $( 'body' ).append( fieldset.$element );
8654 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8657 * @extends OO.ui.InputWidget
8660 * @param {Object} [config] Configuration options
8661 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
8663 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
8664 // Configuration initialization
8665 config
= config
|| {};
8667 // Parent constructor
8668 OO
.ui
.RadioInputWidget
.parent
.call( this, config
);
8672 .addClass( 'oo-ui-radioInputWidget' )
8673 // Required for pretty styling in MediaWiki theme
8674 .append( $( '<span>' ) );
8675 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
8680 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
8682 /* Static Methods */
8687 OO
.ui
.RadioInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8688 var state
= OO
.ui
.RadioInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8689 state
.checked
= config
.$input
.prop( 'checked' );
8699 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
8700 return $( '<input>' ).attr( 'type', 'radio' );
8706 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
8707 // RadioInputWidget doesn't track its state.
8711 * Set selection state of this radio button.
8713 * @param {boolean} state `true` for selected
8716 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
8717 // RadioInputWidget doesn't track its state.
8718 this.$input
.prop( 'checked', state
);
8723 * Check if this radio button is selected.
8725 * @return {boolean} Radio is selected
8727 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
8728 return this.$input
.prop( 'checked' );
8734 OO
.ui
.RadioInputWidget
.prototype.restorePreInfuseState = function ( state
) {
8735 OO
.ui
.RadioInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
8736 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
8737 this.setSelected( state
.checked
);
8742 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
8743 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
8744 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
8745 * more information about input widgets.
8747 * This and OO.ui.DropdownInputWidget support the same configuration options.
8750 * // Example: A RadioSelectInputWidget with three options
8751 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
8753 * { data: 'a', label: 'First' },
8754 * { data: 'b', label: 'Second'},
8755 * { data: 'c', label: 'Third' }
8758 * $( 'body' ).append( radioSelectInput.$element );
8760 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8763 * @extends OO.ui.InputWidget
8766 * @param {Object} [config] Configuration options
8767 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
8769 OO
.ui
.RadioSelectInputWidget
= function OoUiRadioSelectInputWidget( config
) {
8770 // Configuration initialization
8771 config
= config
|| {};
8773 // Properties (must be done before parent constructor which calls #setDisabled)
8774 this.radioSelectWidget
= new OO
.ui
.RadioSelectWidget();
8776 // Parent constructor
8777 OO
.ui
.RadioSelectInputWidget
.parent
.call( this, config
);
8780 this.radioSelectWidget
.connect( this, { select
: 'onMenuSelect' } );
8783 this.setOptions( config
.options
|| [] );
8785 .addClass( 'oo-ui-radioSelectInputWidget' )
8786 .append( this.radioSelectWidget
.$element
);
8791 OO
.inheritClass( OO
.ui
.RadioSelectInputWidget
, OO
.ui
.InputWidget
);
8793 /* Static Properties */
8799 OO
.ui
.RadioSelectInputWidget
.static.supportsSimpleLabel
= false;
8801 /* Static Methods */
8806 OO
.ui
.RadioSelectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8807 var state
= OO
.ui
.RadioSelectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8808 state
.value
= $( node
).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
8815 OO
.ui
.RadioSelectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
8816 config
= OO
.ui
.RadioSelectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
8817 // Cannot reuse the `<input type=radio>` set
8818 delete config
.$input
;
8828 OO
.ui
.RadioSelectInputWidget
.prototype.getInputElement = function () {
8829 return $( '<input>' ).attr( 'type', 'hidden' );
8833 * Handles menu select events.
8836 * @param {OO.ui.RadioOptionWidget} item Selected menu item
8838 OO
.ui
.RadioSelectInputWidget
.prototype.onMenuSelect = function ( item
) {
8839 this.setValue( item
.getData() );
8845 OO
.ui
.RadioSelectInputWidget
.prototype.setValue = function ( value
) {
8846 value
= this.cleanUpValue( value
);
8847 this.radioSelectWidget
.selectItemByData( value
);
8848 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setValue
.call( this, value
);
8855 OO
.ui
.RadioSelectInputWidget
.prototype.setDisabled = function ( state
) {
8856 this.radioSelectWidget
.setDisabled( state
);
8857 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
8862 * Set the options available for this input.
8864 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
8867 OO
.ui
.RadioSelectInputWidget
.prototype.setOptions = function ( options
) {
8869 value
= this.getValue(),
8872 // Rebuild the radioSelect menu
8873 this.radioSelectWidget
8875 .addItems( options
.map( function ( opt
) {
8876 var optValue
= widget
.cleanUpValue( opt
.data
);
8877 return new OO
.ui
.RadioOptionWidget( {
8879 label
: opt
.label
!== undefined ? opt
.label
: optValue
8883 // Restore the previous value, or reset to something sensible
8884 if ( this.radioSelectWidget
.getItemFromData( value
) ) {
8885 // Previous value is still available, ensure consistency with the radioSelect
8886 this.setValue( value
);
8888 // No longer valid, reset
8889 if ( options
.length
) {
8890 this.setValue( options
[ 0 ].data
);
8898 * CheckboxMultiselectInputWidget is a
8899 * {@link OO.ui.CheckboxMultiselectWidget CheckboxMultiselectWidget} intended to be used within a
8900 * HTML form, such as a OO.ui.FormLayout. The selected values are synchronized with the value of
8901 * HTML `<input type=checkbox>` tags. Please see the [OOjs UI documentation on MediaWiki][1] for
8902 * more information about input widgets.
8905 * // Example: A CheckboxMultiselectInputWidget with three options
8906 * var multiselectInput = new OO.ui.CheckboxMultiselectInputWidget( {
8908 * { data: 'a', label: 'First' },
8909 * { data: 'b', label: 'Second'},
8910 * { data: 'c', label: 'Third' }
8913 * $( 'body' ).append( multiselectInput.$element );
8915 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8918 * @extends OO.ui.InputWidget
8921 * @param {Object} [config] Configuration options
8922 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: …, disabled: … }`
8924 OO
.ui
.CheckboxMultiselectInputWidget
= function OoUiCheckboxMultiselectInputWidget( config
) {
8925 // Configuration initialization
8926 config
= config
|| {};
8928 // Properties (must be done before parent constructor which calls #setDisabled)
8929 this.checkboxMultiselectWidget
= new OO
.ui
.CheckboxMultiselectWidget();
8931 // Parent constructor
8932 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.call( this, config
);
8935 this.inputName
= config
.name
;
8939 .addClass( 'oo-ui-checkboxMultiselectInputWidget' )
8940 .append( this.checkboxMultiselectWidget
.$element
);
8941 // We don't use this.$input, but rather the CheckboxInputWidgets inside each option
8942 this.$input
.detach();
8943 this.setOptions( config
.options
|| [] );
8944 // Have to repeat this from parent, as we need options to be set up for this to make sense
8945 this.setValue( config
.value
);
8950 OO
.inheritClass( OO
.ui
.CheckboxMultiselectInputWidget
, OO
.ui
.InputWidget
);
8952 /* Static Properties */
8958 OO
.ui
.CheckboxMultiselectInputWidget
.static.supportsSimpleLabel
= false;
8960 /* Static Methods */
8965 OO
.ui
.CheckboxMultiselectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8966 var state
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8967 state
.value
= $( node
).find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
8968 .toArray().map( function ( el
) { return el
.value
; } );
8975 OO
.ui
.CheckboxMultiselectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
8976 config
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
8977 // Cannot reuse the `<input type=checkbox>` set
8978 delete config
.$input
;
8988 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getInputElement = function () {
8990 return $( '<div>' );
8996 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getValue = function () {
8997 var value
= this.$element
.find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
8998 .toArray().map( function ( el
) { return el
.value
; } );
8999 if ( this.value
!== value
) {
9000 this.setValue( value
);
9008 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setValue = function ( value
) {
9009 value
= this.cleanUpValue( value
);
9010 this.checkboxMultiselectWidget
.selectItemsByData( value
);
9011 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setValue
.call( this, value
);
9016 * Clean up incoming value.
9018 * @param {string[]} value Original value
9019 * @return {string[]} Cleaned up value
9021 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.cleanUpValue = function ( value
) {
9024 if ( !Array
.isArray( value
) ) {
9027 for ( i
= 0; i
< value
.length
; i
++ ) {
9029 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
.call( this, value
[ i
] );
9030 // Remove options that we don't have here
9031 if ( !this.checkboxMultiselectWidget
.getItemFromData( singleValue
) ) {
9034 cleanValue
.push( singleValue
);
9042 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setDisabled = function ( state
) {
9043 this.checkboxMultiselectWidget
.setDisabled( state
);
9044 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
9049 * Set the options available for this input.
9051 * @param {Object[]} options Array of menu options in the format `{ data: …, label: …, disabled: … }`
9054 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setOptions = function ( options
) {
9057 // Rebuild the checkboxMultiselectWidget menu
9058 this.checkboxMultiselectWidget
9060 .addItems( options
.map( function ( opt
) {
9061 var optValue
, item
, optDisabled
;
9063 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
.call( widget
, opt
.data
);
9064 optDisabled
= opt
.disabled
!== undefined ? opt
.disabled
: false;
9065 item
= new OO
.ui
.CheckboxMultioptionWidget( {
9067 label
: opt
.label
!== undefined ? opt
.label
: optValue
,
9068 disabled
: optDisabled
9070 // Set the 'name' and 'value' for form submission
9071 item
.checkbox
.$input
.attr( 'name', widget
.inputName
);
9072 item
.checkbox
.setValue( optValue
);
9076 // Re-set the value, checking the checkboxes as needed.
9077 // This will also get rid of any stale options that we just removed.
9078 this.setValue( this.getValue() );
9084 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
9085 * size of the field as well as its presentation. In addition, these widgets can be configured
9086 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
9087 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
9088 * which modifies incoming values rather than validating them.
9089 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9091 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9094 * // Example of a text input widget
9095 * var textInput = new OO.ui.TextInputWidget( {
9096 * value: 'Text input'
9098 * $( 'body' ).append( textInput.$element );
9100 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9103 * @extends OO.ui.InputWidget
9104 * @mixins OO.ui.mixin.IconElement
9105 * @mixins OO.ui.mixin.IndicatorElement
9106 * @mixins OO.ui.mixin.PendingElement
9107 * @mixins OO.ui.mixin.LabelElement
9110 * @param {Object} [config] Configuration options
9111 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
9112 * 'email', 'url', 'date', 'month' or 'number'. Ignored if `multiline` is true.
9114 * Some values of `type` result in additional behaviors:
9116 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
9117 * empties the text field
9118 * @cfg {string} [placeholder] Placeholder text
9119 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
9120 * instruct the browser to focus this widget.
9121 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
9122 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
9123 * @cfg {boolean} [multiline=false] Allow multiple lines of text
9124 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
9125 * specifies minimum number of rows to display.
9126 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
9127 * Use the #maxRows config to specify a maximum number of displayed rows.
9128 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
9129 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
9130 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
9131 * the value or placeholder text: `'before'` or `'after'`
9132 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
9133 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
9134 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
9135 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
9136 * (the value must contain only numbers); when RegExp, a regular expression that must match the
9137 * value for it to be considered valid; when Function, a function receiving the value as parameter
9138 * that must return true, or promise resolving to true, for it to be considered valid.
9140 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
9141 // Configuration initialization
9142 config
= $.extend( {
9144 labelPosition
: 'after'
9147 if ( config
.type
=== 'search' ) {
9148 OO
.ui
.warnDeprecation( 'TextInputWidget: config.type=\'search\' is deprecated. Use the SearchInputWidget instead. See T148471 for details.' );
9149 if ( config
.icon
=== undefined ) {
9150 config
.icon
= 'search';
9152 // indicator: 'clear' is set dynamically later, depending on value
9155 // Parent constructor
9156 OO
.ui
.TextInputWidget
.parent
.call( this, config
);
9158 // Mixin constructors
9159 OO
.ui
.mixin
.IconElement
.call( this, config
);
9160 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
9161 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$input
} ) );
9162 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9165 this.type
= this.getSaneType( config
);
9166 this.readOnly
= false;
9167 this.required
= false;
9168 this.multiline
= !!config
.multiline
;
9169 this.autosize
= !!config
.autosize
;
9170 this.minRows
= config
.rows
!== undefined ? config
.rows
: '';
9171 this.maxRows
= config
.maxRows
|| Math
.max( 2 * ( this.minRows
|| 0 ), 10 );
9172 this.validate
= null;
9173 this.styleHeight
= null;
9174 this.scrollWidth
= null;
9176 // Clone for resizing
9177 if ( this.autosize
) {
9178 this.$clone
= this.$input
9180 .insertAfter( this.$input
)
9181 .attr( 'aria-hidden', 'true' )
9182 .addClass( 'oo-ui-element-hidden' );
9185 this.setValidation( config
.validate
);
9186 this.setLabelPosition( config
.labelPosition
);
9190 keypress
: this.onKeyPress
.bind( this ),
9191 blur
: this.onBlur
.bind( this ),
9192 focus
: this.onFocus
.bind( this )
9194 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
9195 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
9196 this.on( 'labelChange', this.updatePosition
.bind( this ) );
9197 this.connect( this, {
9199 disable
: 'onDisable'
9201 this.on( 'change', OO
.ui
.debounce( this.onDebouncedChange
.bind( this ), 250 ) );
9205 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type
)
9206 .append( this.$icon
, this.$indicator
);
9207 this.setReadOnly( !!config
.readOnly
);
9208 this.setRequired( !!config
.required
);
9209 this.updateSearchIndicator();
9210 if ( config
.placeholder
!== undefined ) {
9211 this.$input
.attr( 'placeholder', config
.placeholder
);
9213 if ( config
.maxLength
!== undefined ) {
9214 this.$input
.attr( 'maxlength', config
.maxLength
);
9216 if ( config
.autofocus
) {
9217 this.$input
.attr( 'autofocus', 'autofocus' );
9219 if ( config
.autocomplete
=== false ) {
9220 this.$input
.attr( 'autocomplete', 'off' );
9221 // Turning off autocompletion also disables "form caching" when the user navigates to a
9222 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
9224 beforeunload: function () {
9225 this.$input
.removeAttr( 'autocomplete' );
9227 pageshow: function () {
9228 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
9229 // whole page... it shouldn't hurt, though.
9230 this.$input
.attr( 'autocomplete', 'off' );
9234 if ( this.multiline
&& config
.rows
) {
9235 this.$input
.attr( 'rows', config
.rows
);
9237 if ( this.label
|| config
.autosize
) {
9238 this.isWaitingToBeAttached
= true;
9239 this.installParentChangeDetector();
9245 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
9246 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IconElement
);
9247 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
9248 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.PendingElement
);
9249 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.LabelElement
);
9251 /* Static Properties */
9253 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
9258 /* Static Methods */
9263 OO
.ui
.TextInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9264 var state
= OO
.ui
.TextInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9265 if ( config
.multiline
) {
9266 state
.scrollTop
= config
.$input
.scrollTop();
9274 * An `enter` event is emitted when the user presses 'enter' inside the text box.
9276 * Not emitted if the input is multiline.
9282 * A `resize` event is emitted when autosize is set and the widget resizes
9290 * Handle icon mouse down events.
9293 * @param {jQuery.Event} e Mouse down event
9295 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
9296 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
9297 this.$input
[ 0 ].focus();
9303 * Handle indicator mouse down events.
9306 * @param {jQuery.Event} e Mouse down event
9308 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
9309 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
9310 if ( this.type
=== 'search' ) {
9311 // Clear the text field
9312 this.setValue( '' );
9314 this.$input
[ 0 ].focus();
9320 * Handle key press events.
9323 * @param {jQuery.Event} e Key press event
9324 * @fires enter If enter key is pressed and input is not multiline
9326 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
9327 if ( e
.which
=== OO
.ui
.Keys
.ENTER
&& !this.multiline
) {
9328 this.emit( 'enter', e
);
9333 * Handle blur events.
9336 * @param {jQuery.Event} e Blur event
9338 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
9339 this.setValidityFlag();
9343 * Handle focus events.
9346 * @param {jQuery.Event} e Focus event
9348 OO
.ui
.TextInputWidget
.prototype.onFocus = function () {
9349 if ( this.isWaitingToBeAttached
) {
9350 // If we've received focus, then we must be attached to the document, and if
9351 // isWaitingToBeAttached is still true, that means the handler never fired. Fire it now.
9352 this.onElementAttach();
9354 this.setValidityFlag( true );
9358 * Handle element attach events.
9361 * @param {jQuery.Event} e Element attach event
9363 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
9364 this.isWaitingToBeAttached
= false;
9365 // Any previously calculated size is now probably invalid if we reattached elsewhere
9366 this.valCache
= null;
9368 this.positionLabel();
9372 * Handle change events.
9374 * @param {string} value
9377 OO
.ui
.TextInputWidget
.prototype.onChange = function () {
9378 this.updateSearchIndicator();
9383 * Handle debounced change events.
9385 * @param {string} value
9388 OO
.ui
.TextInputWidget
.prototype.onDebouncedChange = function () {
9389 this.setValidityFlag();
9393 * Handle disable events.
9395 * @param {boolean} disabled Element is disabled
9398 OO
.ui
.TextInputWidget
.prototype.onDisable = function () {
9399 this.updateSearchIndicator();
9403 * Check if the input is {@link #readOnly read-only}.
9407 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
9408 return this.readOnly
;
9412 * Set the {@link #readOnly read-only} state of the input.
9414 * @param {boolean} state Make input read-only
9417 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
9418 this.readOnly
= !!state
;
9419 this.$input
.prop( 'readOnly', this.readOnly
);
9420 this.updateSearchIndicator();
9425 * Check if the input is {@link #required required}.
9429 OO
.ui
.TextInputWidget
.prototype.isRequired = function () {
9430 return this.required
;
9434 * Set the {@link #required required} state of the input.
9436 * @param {boolean} state Make input required
9439 OO
.ui
.TextInputWidget
.prototype.setRequired = function ( state
) {
9440 this.required
= !!state
;
9441 if ( this.required
) {
9443 .attr( 'required', 'required' )
9444 .attr( 'aria-required', 'true' );
9445 if ( this.getIndicator() === null ) {
9446 this.setIndicator( 'required' );
9450 .removeAttr( 'required' )
9451 .removeAttr( 'aria-required' );
9452 if ( this.getIndicator() === 'required' ) {
9453 this.setIndicator( null );
9456 this.updateSearchIndicator();
9461 * Support function for making #onElementAttach work across browsers.
9463 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
9464 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
9466 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
9467 * first time that the element gets attached to the documented.
9469 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
9470 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
9471 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
9474 if ( MutationObserver
) {
9475 // The new way. If only it wasn't so ugly.
9477 if ( this.isElementAttached() ) {
9478 // Widget is attached already, do nothing. This breaks the functionality of this function when
9479 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
9480 // would require observation of the whole document, which would hurt performance of other,
9481 // more important code.
9485 // Find topmost node in the tree
9486 topmostNode
= this.$element
[ 0 ];
9487 while ( topmostNode
.parentNode
) {
9488 topmostNode
= topmostNode
.parentNode
;
9491 // We have no way to detect the $element being attached somewhere without observing the entire
9492 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
9493 // parent node of $element, and instead detect when $element is removed from it (and thus
9494 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
9495 // doesn't get attached, we end up back here and create the parent.
9497 mutationObserver
= new MutationObserver( function ( mutations
) {
9498 var i
, j
, removedNodes
;
9499 for ( i
= 0; i
< mutations
.length
; i
++ ) {
9500 removedNodes
= mutations
[ i
].removedNodes
;
9501 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
9502 if ( removedNodes
[ j
] === topmostNode
) {
9503 setTimeout( onRemove
, 0 );
9510 onRemove = function () {
9511 // If the node was attached somewhere else, report it
9512 if ( widget
.isElementAttached() ) {
9513 widget
.onElementAttach();
9515 mutationObserver
.disconnect();
9516 widget
.installParentChangeDetector();
9519 // Create a fake parent and observe it
9520 fakeParentNode
= $( '<div>' ).append( topmostNode
)[ 0 ];
9521 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
9523 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
9524 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
9525 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
9530 * Automatically adjust the size of the text input.
9532 * This only affects #multiline inputs that are {@link #autosize autosized}.
9537 OO
.ui
.TextInputWidget
.prototype.adjustSize = function () {
9538 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
,
9539 idealHeight
, newHeight
, scrollWidth
, property
;
9541 if ( this.isWaitingToBeAttached
) {
9542 // #onElementAttach will be called soon, which calls this method
9546 if ( this.multiline
&& this.$input
.val() !== this.valCache
) {
9547 if ( this.autosize
) {
9549 .val( this.$input
.val() )
9550 .attr( 'rows', this.minRows
)
9551 // Set inline height property to 0 to measure scroll height
9552 .css( 'height', 0 );
9554 this.$clone
.removeClass( 'oo-ui-element-hidden' );
9556 this.valCache
= this.$input
.val();
9558 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
9560 // Remove inline height property to measure natural heights
9561 this.$clone
.css( 'height', '' );
9562 innerHeight
= this.$clone
.innerHeight();
9563 outerHeight
= this.$clone
.outerHeight();
9565 // Measure max rows height
9567 .attr( 'rows', this.maxRows
)
9568 .css( 'height', 'auto' )
9570 maxInnerHeight
= this.$clone
.innerHeight();
9572 // Difference between reported innerHeight and scrollHeight with no scrollbars present.
9573 // This is sometimes non-zero on Blink-based browsers, depending on zoom level.
9574 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
9575 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
9577 this.$clone
.addClass( 'oo-ui-element-hidden' );
9579 // Only apply inline height when expansion beyond natural height is needed
9580 // Use the difference between the inner and outer height as a buffer
9581 newHeight
= idealHeight
> innerHeight
? idealHeight
+ ( outerHeight
- innerHeight
) : '';
9582 if ( newHeight
!== this.styleHeight
) {
9583 this.$input
.css( 'height', newHeight
);
9584 this.styleHeight
= newHeight
;
9585 this.emit( 'resize' );
9588 scrollWidth
= this.$input
[ 0 ].offsetWidth
- this.$input
[ 0 ].clientWidth
;
9589 if ( scrollWidth
!== this.scrollWidth
) {
9590 property
= this.$element
.css( 'direction' ) === 'rtl' ? 'left' : 'right';
9592 this.$label
.css( { right
: '', left
: '' } );
9593 this.$indicator
.css( { right
: '', left
: '' } );
9595 if ( scrollWidth
) {
9596 this.$indicator
.css( property
, scrollWidth
);
9597 if ( this.labelPosition
=== 'after' ) {
9598 this.$label
.css( property
, scrollWidth
);
9602 this.scrollWidth
= scrollWidth
;
9603 this.positionLabel();
9613 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
9614 if ( config
.multiline
) {
9615 return $( '<textarea>' );
9616 } else if ( this.getSaneType( config
) === 'number' ) {
9617 return $( '<input>' )
9618 .attr( 'step', 'any' )
9619 .attr( 'type', 'number' );
9621 return $( '<input>' ).attr( 'type', this.getSaneType( config
) );
9626 * Get sanitized value for 'type' for given config.
9628 * @param {Object} config Configuration options
9629 * @return {string|null}
9632 OO
.ui
.TextInputWidget
.prototype.getSaneType = function ( config
) {
9633 var allowedTypes
= [
9643 return allowedTypes
.indexOf( config
.type
) !== -1 ? config
.type
: 'text';
9647 * Check if the input supports multiple lines.
9651 OO
.ui
.TextInputWidget
.prototype.isMultiline = function () {
9652 return !!this.multiline
;
9656 * Check if the input automatically adjusts its size.
9660 OO
.ui
.TextInputWidget
.prototype.isAutosizing = function () {
9661 return !!this.autosize
;
9665 * Focus the input and select a specified range within the text.
9667 * @param {number} from Select from offset
9668 * @param {number} [to] Select to offset, defaults to from
9671 OO
.ui
.TextInputWidget
.prototype.selectRange = function ( from, to
) {
9672 var isBackwards
, start
, end
,
9673 input
= this.$input
[ 0 ];
9677 isBackwards
= to
< from;
9678 start
= isBackwards
? to
: from;
9679 end
= isBackwards
? from : to
;
9684 input
.setSelectionRange( start
, end
, isBackwards
? 'backward' : 'forward' );
9686 // IE throws an exception if you call setSelectionRange on a unattached DOM node.
9687 // Rather than expensively check if the input is attached every time, just check
9688 // if it was the cause of an error being thrown. If not, rethrow the error.
9689 if ( this.getElementDocument().body
.contains( input
) ) {
9697 * Get an object describing the current selection range in a directional manner
9699 * @return {Object} Object containing 'from' and 'to' offsets
9701 OO
.ui
.TextInputWidget
.prototype.getRange = function () {
9702 var input
= this.$input
[ 0 ],
9703 start
= input
.selectionStart
,
9704 end
= input
.selectionEnd
,
9705 isBackwards
= input
.selectionDirection
=== 'backward';
9708 from: isBackwards
? end
: start
,
9709 to
: isBackwards
? start
: end
9714 * Get the length of the text input value.
9716 * This could differ from the length of #getValue if the
9717 * value gets filtered
9719 * @return {number} Input length
9721 OO
.ui
.TextInputWidget
.prototype.getInputLength = function () {
9722 return this.$input
[ 0 ].value
.length
;
9726 * Focus the input and select the entire text.
9730 OO
.ui
.TextInputWidget
.prototype.select = function () {
9731 return this.selectRange( 0, this.getInputLength() );
9735 * Focus the input and move the cursor to the start.
9739 OO
.ui
.TextInputWidget
.prototype.moveCursorToStart = function () {
9740 return this.selectRange( 0 );
9744 * Focus the input and move the cursor to the end.
9748 OO
.ui
.TextInputWidget
.prototype.moveCursorToEnd = function () {
9749 return this.selectRange( this.getInputLength() );
9753 * Insert new content into the input.
9755 * @param {string} content Content to be inserted
9758 OO
.ui
.TextInputWidget
.prototype.insertContent = function ( content
) {
9760 range
= this.getRange(),
9761 value
= this.getValue();
9763 start
= Math
.min( range
.from, range
.to
);
9764 end
= Math
.max( range
.from, range
.to
);
9766 this.setValue( value
.slice( 0, start
) + content
+ value
.slice( end
) );
9767 this.selectRange( start
+ content
.length
);
9772 * Insert new content either side of a selection.
9774 * @param {string} pre Content to be inserted before the selection
9775 * @param {string} post Content to be inserted after the selection
9778 OO
.ui
.TextInputWidget
.prototype.encapsulateContent = function ( pre
, post
) {
9780 range
= this.getRange(),
9781 offset
= pre
.length
;
9783 start
= Math
.min( range
.from, range
.to
);
9784 end
= Math
.max( range
.from, range
.to
);
9786 this.selectRange( start
).insertContent( pre
);
9787 this.selectRange( offset
+ end
).insertContent( post
);
9789 this.selectRange( offset
+ start
, offset
+ end
);
9794 * Set the validation pattern.
9796 * The validation pattern is either a regular expression, a function, or the symbolic name of a
9797 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
9798 * value must contain only numbers).
9800 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
9801 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
9803 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
9804 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
9805 this.validate
= validate
;
9807 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
9812 * Sets the 'invalid' flag appropriately.
9814 * @param {boolean} [isValid] Optionally override validation result
9816 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
9818 setFlag = function ( valid
) {
9820 widget
.$input
.attr( 'aria-invalid', 'true' );
9822 widget
.$input
.removeAttr( 'aria-invalid' );
9824 widget
.setFlags( { invalid
: !valid
} );
9827 if ( isValid
!== undefined ) {
9830 this.getValidity().then( function () {
9839 * Get the validity of current value.
9841 * This method returns a promise that resolves if the value is valid and rejects if
9842 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
9844 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
9846 OO
.ui
.TextInputWidget
.prototype.getValidity = function () {
9849 function rejectOrResolve( valid
) {
9851 return $.Deferred().resolve().promise();
9853 return $.Deferred().reject().promise();
9857 // Check browser validity and reject if it is invalid
9859 this.$input
[ 0 ].checkValidity
!== undefined &&
9860 this.$input
[ 0 ].checkValidity() === false
9862 return rejectOrResolve( false );
9865 // Run our checks if the browser thinks the field is valid
9866 if ( this.validate
instanceof Function
) {
9867 result
= this.validate( this.getValue() );
9868 if ( result
&& $.isFunction( result
.promise
) ) {
9869 return result
.promise().then( function ( valid
) {
9870 return rejectOrResolve( valid
);
9873 return rejectOrResolve( result
);
9876 return rejectOrResolve( this.getValue().match( this.validate
) );
9881 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
9883 * @param {string} labelPosition Label position, 'before' or 'after'
9886 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
9887 this.labelPosition
= labelPosition
;
9889 // If there is no label and we only change the position, #updatePosition is a no-op,
9890 // but it takes really a lot of work to do nothing.
9891 this.updatePosition();
9897 * Update the position of the inline label.
9899 * This method is called by #setLabelPosition, and can also be called on its own if
9900 * something causes the label to be mispositioned.
9904 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
9905 var after
= this.labelPosition
=== 'after';
9908 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
9909 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
9911 this.valCache
= null;
9912 this.scrollWidth
= null;
9914 this.positionLabel();
9920 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
9921 * already empty or when it's not editable.
9923 OO
.ui
.TextInputWidget
.prototype.updateSearchIndicator = function () {
9924 if ( this.type
=== 'search' ) {
9925 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
9926 this.setIndicator( null );
9928 this.setIndicator( 'clear' );
9934 * Position the label by setting the correct padding on the input.
9939 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
9940 var after
, rtl
, property
;
9942 if ( this.isWaitingToBeAttached
) {
9943 // #onElementAttach will be called soon, which calls this method
9949 // Clear old values if present
9951 'padding-right': '',
9956 this.$element
.append( this.$label
);
9958 this.$label
.detach();
9962 after
= this.labelPosition
=== 'after';
9963 rtl
= this.$element
.css( 'direction' ) === 'rtl';
9964 property
= after
=== rtl
? 'padding-left' : 'padding-right';
9966 this.$input
.css( property
, this.$label
.outerWidth( true ) + ( after
? this.scrollWidth
: 0 ) );
9974 OO
.ui
.TextInputWidget
.prototype.restorePreInfuseState = function ( state
) {
9975 OO
.ui
.TextInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
9976 if ( state
.scrollTop
!== undefined ) {
9977 this.$input
.scrollTop( state
.scrollTop
);
9983 * @extends OO.ui.TextInputWidget
9986 * @param {Object} [config] Configuration options
9988 OO
.ui
.SearchInputWidget
= function OoUiSearchInputWidget( config
) {
9989 config
= $.extend( {
9993 // Set type to text so that TextInputWidget doesn't
9994 // get stuck in an infinite loop.
9995 config
.type
= 'text';
9997 // Parent constructor
9998 OO
.ui
.SearchInputWidget
.parent
.call( this, config
);
10001 this.$element
.addClass( 'oo-ui-textInputWidget-type-search' );
10002 this.updateSearchIndicator();
10003 this.connect( this, {
10004 disable
: 'onDisable'
10010 OO
.inheritClass( OO
.ui
.SearchInputWidget
, OO
.ui
.TextInputWidget
);
10018 OO
.ui
.SearchInputWidget
.prototype.getInputElement = function () {
10019 return $( '<input>' ).attr( 'type', 'search' );
10025 OO
.ui
.SearchInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
10026 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
10027 // Clear the text field
10028 this.setValue( '' );
10029 this.$input
[ 0 ].focus();
10035 * Update the 'clear' indicator displayed on type: 'search' text
10036 * fields, hiding it when the field is already empty or when it's not
10039 OO
.ui
.SearchInputWidget
.prototype.updateSearchIndicator = function () {
10040 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
10041 this.setIndicator( null );
10043 this.setIndicator( 'clear' );
10050 OO
.ui
.SearchInputWidget
.prototype.onChange = function () {
10051 OO
.ui
.SearchInputWidget
.parent
.prototype.onChange
.call( this );
10052 this.updateSearchIndicator();
10056 * Handle disable events.
10058 * @param {boolean} disabled Element is disabled
10061 OO
.ui
.SearchInputWidget
.prototype.onDisable = function () {
10062 this.updateSearchIndicator();
10068 OO
.ui
.SearchInputWidget
.prototype.setReadOnly = function ( state
) {
10069 OO
.ui
.SearchInputWidget
.parent
.prototype.setReadOnly
.call( this, state
);
10070 this.updateSearchIndicator();
10075 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
10076 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
10077 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
10079 * - by typing a value in the text input field. If the value exactly matches the value of a menu
10080 * option, that option will appear to be selected.
10081 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
10084 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
10086 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
10089 * // Example: A ComboBoxInputWidget.
10090 * var comboBox = new OO.ui.ComboBoxInputWidget( {
10091 * label: 'ComboBoxInputWidget',
10092 * value: 'Option 1',
10095 * new OO.ui.MenuOptionWidget( {
10096 * data: 'Option 1',
10097 * label: 'Option One'
10099 * new OO.ui.MenuOptionWidget( {
10100 * data: 'Option 2',
10101 * label: 'Option Two'
10103 * new OO.ui.MenuOptionWidget( {
10104 * data: 'Option 3',
10105 * label: 'Option Three'
10107 * new OO.ui.MenuOptionWidget( {
10108 * data: 'Option 4',
10109 * label: 'Option Four'
10111 * new OO.ui.MenuOptionWidget( {
10112 * data: 'Option 5',
10113 * label: 'Option Five'
10118 * $( 'body' ).append( comboBox.$element );
10120 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
10123 * @extends OO.ui.TextInputWidget
10126 * @param {Object} [config] Configuration options
10127 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
10128 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
10129 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
10130 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
10131 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
10133 OO
.ui
.ComboBoxInputWidget
= function OoUiComboBoxInputWidget( config
) {
10134 // Configuration initialization
10135 config
= $.extend( {
10136 autocomplete
: false
10139 // ComboBoxInputWidget shouldn't support multiline
10140 config
.multiline
= false;
10142 // Parent constructor
10143 OO
.ui
.ComboBoxInputWidget
.parent
.call( this, config
);
10146 this.$overlay
= config
.$overlay
|| this.$element
;
10147 this.dropdownButton
= new OO
.ui
.ButtonWidget( {
10148 classes
: [ 'oo-ui-comboBoxInputWidget-dropdownButton' ],
10150 disabled
: this.disabled
10152 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend(
10156 $container
: this.$element
,
10157 disabled
: this.isDisabled()
10163 this.connect( this, {
10164 change
: 'onInputChange',
10165 enter
: 'onInputEnter'
10167 this.dropdownButton
.connect( this, {
10168 click
: 'onDropdownButtonClick'
10170 this.menu
.connect( this, {
10171 choose
: 'onMenuChoose',
10172 add
: 'onMenuItemsChange',
10173 remove
: 'onMenuItemsChange'
10177 this.$input
.attr( {
10179 'aria-autocomplete': 'list'
10181 // Do not override options set via config.menu.items
10182 if ( config
.options
!== undefined ) {
10183 this.setOptions( config
.options
);
10185 this.$field
= $( '<div>' )
10186 .addClass( 'oo-ui-comboBoxInputWidget-field' )
10187 .append( this.$input
, this.dropdownButton
.$element
);
10189 .addClass( 'oo-ui-comboBoxInputWidget' )
10190 .append( this.$field
);
10191 this.$overlay
.append( this.menu
.$element
);
10192 this.onMenuItemsChange();
10197 OO
.inheritClass( OO
.ui
.ComboBoxInputWidget
, OO
.ui
.TextInputWidget
);
10202 * Get the combobox's menu.
10204 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
10206 OO
.ui
.ComboBoxInputWidget
.prototype.getMenu = function () {
10211 * Get the combobox's text input widget.
10213 * @return {OO.ui.TextInputWidget} Text input widget
10215 OO
.ui
.ComboBoxInputWidget
.prototype.getInput = function () {
10220 * Handle input change events.
10223 * @param {string} value New value
10225 OO
.ui
.ComboBoxInputWidget
.prototype.onInputChange = function ( value
) {
10226 var match
= this.menu
.getItemFromData( value
);
10228 this.menu
.selectItem( match
);
10229 if ( this.menu
.getHighlightedItem() ) {
10230 this.menu
.highlightItem( match
);
10233 if ( !this.isDisabled() ) {
10234 this.menu
.toggle( true );
10239 * Handle input enter events.
10243 OO
.ui
.ComboBoxInputWidget
.prototype.onInputEnter = function () {
10244 if ( !this.isDisabled() ) {
10245 this.menu
.toggle( false );
10250 * Handle button click events.
10254 OO
.ui
.ComboBoxInputWidget
.prototype.onDropdownButtonClick = function () {
10255 this.menu
.toggle();
10256 this.$input
[ 0 ].focus();
10260 * Handle menu choose events.
10263 * @param {OO.ui.OptionWidget} item Chosen item
10265 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuChoose = function ( item
) {
10266 this.setValue( item
.getData() );
10270 * Handle menu item change events.
10274 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuItemsChange = function () {
10275 var match
= this.menu
.getItemFromData( this.getValue() );
10276 this.menu
.selectItem( match
);
10277 if ( this.menu
.getHighlightedItem() ) {
10278 this.menu
.highlightItem( match
);
10280 this.$element
.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu
.isEmpty() );
10286 OO
.ui
.ComboBoxInputWidget
.prototype.setDisabled = function ( disabled
) {
10288 OO
.ui
.ComboBoxInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
10290 if ( this.dropdownButton
) {
10291 this.dropdownButton
.setDisabled( this.isDisabled() );
10294 this.menu
.setDisabled( this.isDisabled() );
10301 * Set the options available for this input.
10303 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10306 OO
.ui
.ComboBoxInputWidget
.prototype.setOptions = function ( options
) {
10309 .addItems( options
.map( function ( opt
) {
10310 return new OO
.ui
.MenuOptionWidget( {
10312 label
: opt
.label
!== undefined ? opt
.label
: opt
.data
10320 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
10321 * which is a widget that is specified by reference before any optional configuration settings.
10323 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
10325 * - **left**: The label is placed before the field-widget and aligned with the left margin.
10326 * A left-alignment is used for forms with many fields.
10327 * - **right**: The label is placed before the field-widget and aligned to the right margin.
10328 * A right-alignment is used for long but familiar forms which users tab through,
10329 * verifying the current field with a quick glance at the label.
10330 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
10331 * that users fill out from top to bottom.
10332 * - **inline**: The label is placed after the field-widget and aligned to the left.
10333 * An inline-alignment is best used with checkboxes or radio buttons.
10335 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
10336 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
10338 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
10341 * @extends OO.ui.Layout
10342 * @mixins OO.ui.mixin.LabelElement
10343 * @mixins OO.ui.mixin.TitledElement
10346 * @param {OO.ui.Widget} fieldWidget Field widget
10347 * @param {Object} [config] Configuration options
10348 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
10349 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
10350 * The array may contain strings or OO.ui.HtmlSnippet instances.
10351 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
10352 * The array may contain strings or OO.ui.HtmlSnippet instances.
10353 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
10354 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
10355 * For important messages, you are advised to use `notices`, as they are always shown.
10356 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
10358 * @throws {Error} An error is thrown if no widget is specified
10360 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
10361 // Allow passing positional parameters inside the config object
10362 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
10363 config
= fieldWidget
;
10364 fieldWidget
= config
.fieldWidget
;
10367 // Make sure we have required constructor arguments
10368 if ( fieldWidget
=== undefined ) {
10369 throw new Error( 'Widget not found' );
10372 // Configuration initialization
10373 config
= $.extend( { align
: 'left' }, config
);
10375 // Parent constructor
10376 OO
.ui
.FieldLayout
.parent
.call( this, config
);
10378 // Mixin constructors
10379 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, {
10380 $label
: $( '<label>' )
10382 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
10385 this.fieldWidget
= fieldWidget
;
10388 this.$field
= $( '<div>' );
10389 this.$messages
= $( '<ul>' );
10390 this.$header
= $( '<div>' );
10391 this.$body
= $( '<div>' );
10393 if ( config
.help
) {
10394 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
10395 $overlay
: config
.$overlay
,
10399 classes
: [ 'oo-ui-fieldLayout-help' ],
10403 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
10404 this.popupButtonWidget
.getPopup().$body
.html( config
.help
.toString() );
10406 this.popupButtonWidget
.getPopup().$body
.text( config
.help
);
10408 this.$help
= this.popupButtonWidget
.$element
;
10410 this.$help
= $( [] );
10414 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
10417 if ( fieldWidget
.constructor.static.supportsSimpleLabel
) {
10418 if ( this.fieldWidget
.getInputId() ) {
10419 this.$label
.attr( 'for', this.fieldWidget
.getInputId() );
10421 this.$label
.on( 'click', function () {
10422 this.fieldWidget
.focus();
10428 .addClass( 'oo-ui-fieldLayout' )
10429 .toggleClass( 'oo-ui-fieldLayout-disabled', this.fieldWidget
.isDisabled() )
10430 .append( this.$body
);
10431 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
10432 this.$header
.addClass( 'oo-ui-fieldLayout-header' );
10433 this.$messages
.addClass( 'oo-ui-fieldLayout-messages' );
10435 .addClass( 'oo-ui-fieldLayout-field' )
10436 .append( this.fieldWidget
.$element
);
10438 this.setErrors( config
.errors
|| [] );
10439 this.setNotices( config
.notices
|| [] );
10440 this.setAlignment( config
.align
);
10445 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
10446 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.LabelElement
);
10447 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.TitledElement
);
10452 * Handle field disable events.
10455 * @param {boolean} value Field is disabled
10457 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
10458 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
10462 * Get the widget contained by the field.
10464 * @return {OO.ui.Widget} Field widget
10466 OO
.ui
.FieldLayout
.prototype.getField = function () {
10467 return this.fieldWidget
;
10472 * @param {string} kind 'error' or 'notice'
10473 * @param {string|OO.ui.HtmlSnippet} text
10476 OO
.ui
.FieldLayout
.prototype.makeMessage = function ( kind
, text
) {
10477 var $listItem
, $icon
, message
;
10478 $listItem
= $( '<li>' );
10479 if ( kind
=== 'error' ) {
10480 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'warning' ] } ).$element
;
10481 } else if ( kind
=== 'notice' ) {
10482 $icon
= new OO
.ui
.IconWidget( { icon
: 'info' } ).$element
;
10486 message
= new OO
.ui
.LabelWidget( { label
: text
} );
10488 .append( $icon
, message
.$element
)
10489 .addClass( 'oo-ui-fieldLayout-messages-' + kind
);
10494 * Set the field alignment mode.
10497 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
10500 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
10501 if ( value
!== this.align
) {
10502 // Default to 'left'
10503 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
10506 // Reorder elements
10507 if ( value
=== 'top' ) {
10508 this.$header
.append( this.$label
, this.$help
);
10509 this.$body
.append( this.$header
, this.$field
);
10510 } else if ( value
=== 'inline' ) {
10511 this.$header
.append( this.$label
, this.$help
);
10512 this.$body
.append( this.$field
, this.$header
);
10514 this.$header
.append( this.$label
);
10515 this.$body
.append( this.$header
, this.$help
, this.$field
);
10517 // Set classes. The following classes can be used here:
10518 // * oo-ui-fieldLayout-align-left
10519 // * oo-ui-fieldLayout-align-right
10520 // * oo-ui-fieldLayout-align-top
10521 // * oo-ui-fieldLayout-align-inline
10522 if ( this.align
) {
10523 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
10525 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
10526 this.align
= value
;
10533 * Set the list of error messages.
10535 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
10536 * The array may contain strings or OO.ui.HtmlSnippet instances.
10539 OO
.ui
.FieldLayout
.prototype.setErrors = function ( errors
) {
10540 this.errors
= errors
.slice();
10541 this.updateMessages();
10546 * Set the list of notice messages.
10548 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
10549 * The array may contain strings or OO.ui.HtmlSnippet instances.
10552 OO
.ui
.FieldLayout
.prototype.setNotices = function ( notices
) {
10553 this.notices
= notices
.slice();
10554 this.updateMessages();
10559 * Update the rendering of error and notice messages.
10563 OO
.ui
.FieldLayout
.prototype.updateMessages = function () {
10565 this.$messages
.empty();
10567 if ( this.errors
.length
|| this.notices
.length
) {
10568 this.$body
.after( this.$messages
);
10570 this.$messages
.remove();
10574 for ( i
= 0; i
< this.notices
.length
; i
++ ) {
10575 this.$messages
.append( this.makeMessage( 'notice', this.notices
[ i
] ) );
10577 for ( i
= 0; i
< this.errors
.length
; i
++ ) {
10578 this.$messages
.append( this.makeMessage( 'error', this.errors
[ i
] ) );
10583 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
10584 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
10585 * is required and is specified before any optional configuration settings.
10587 * Labels can be aligned in one of four ways:
10589 * - **left**: The label is placed before the field-widget and aligned with the left margin.
10590 * A left-alignment is used for forms with many fields.
10591 * - **right**: The label is placed before the field-widget and aligned to the right margin.
10592 * A right-alignment is used for long but familiar forms which users tab through,
10593 * verifying the current field with a quick glance at the label.
10594 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
10595 * that users fill out from top to bottom.
10596 * - **inline**: The label is placed after the field-widget and aligned to the left.
10597 * An inline-alignment is best used with checkboxes or radio buttons.
10599 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
10600 * text is specified.
10603 * // Example of an ActionFieldLayout
10604 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
10605 * new OO.ui.TextInputWidget( {
10606 * placeholder: 'Field widget'
10608 * new OO.ui.ButtonWidget( {
10612 * label: 'An ActionFieldLayout. This label is aligned top',
10614 * help: 'This is help text'
10618 * $( 'body' ).append( actionFieldLayout.$element );
10621 * @extends OO.ui.FieldLayout
10624 * @param {OO.ui.Widget} fieldWidget Field widget
10625 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
10626 * @param {Object} config
10628 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
10629 // Allow passing positional parameters inside the config object
10630 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
10631 config
= fieldWidget
;
10632 fieldWidget
= config
.fieldWidget
;
10633 buttonWidget
= config
.buttonWidget
;
10636 // Parent constructor
10637 OO
.ui
.ActionFieldLayout
.parent
.call( this, fieldWidget
, config
);
10640 this.buttonWidget
= buttonWidget
;
10641 this.$button
= $( '<div>' );
10642 this.$input
= $( '<div>' );
10646 .addClass( 'oo-ui-actionFieldLayout' );
10648 .addClass( 'oo-ui-actionFieldLayout-button' )
10649 .append( this.buttonWidget
.$element
);
10651 .addClass( 'oo-ui-actionFieldLayout-input' )
10652 .append( this.fieldWidget
.$element
);
10654 .append( this.$input
, this.$button
);
10659 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
10662 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
10663 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
10664 * configured with a label as well. For more information and examples,
10665 * please see the [OOjs UI documentation on MediaWiki][1].
10668 * // Example of a fieldset layout
10669 * var input1 = new OO.ui.TextInputWidget( {
10670 * placeholder: 'A text input field'
10673 * var input2 = new OO.ui.TextInputWidget( {
10674 * placeholder: 'A text input field'
10677 * var fieldset = new OO.ui.FieldsetLayout( {
10678 * label: 'Example of a fieldset layout'
10681 * fieldset.addItems( [
10682 * new OO.ui.FieldLayout( input1, {
10683 * label: 'Field One'
10685 * new OO.ui.FieldLayout( input2, {
10686 * label: 'Field Two'
10689 * $( 'body' ).append( fieldset.$element );
10691 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
10694 * @extends OO.ui.Layout
10695 * @mixins OO.ui.mixin.IconElement
10696 * @mixins OO.ui.mixin.LabelElement
10697 * @mixins OO.ui.mixin.GroupElement
10700 * @param {Object} [config] Configuration options
10701 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
10702 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
10703 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
10704 * For important messages, you are advised to use `notices`, as they are always shown.
10705 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
10707 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
10708 // Configuration initialization
10709 config
= config
|| {};
10711 // Parent constructor
10712 OO
.ui
.FieldsetLayout
.parent
.call( this, config
);
10714 // Mixin constructors
10715 OO
.ui
.mixin
.IconElement
.call( this, config
);
10716 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: $( '<div>' ) } ) );
10717 OO
.ui
.mixin
.GroupElement
.call( this, config
);
10720 this.$header
= $( '<div>' );
10721 if ( config
.help
) {
10722 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
10723 $overlay
: config
.$overlay
,
10727 classes
: [ 'oo-ui-fieldsetLayout-help' ],
10731 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
10732 this.popupButtonWidget
.getPopup().$body
.html( config
.help
.toString() );
10734 this.popupButtonWidget
.getPopup().$body
.text( config
.help
);
10736 this.$help
= this.popupButtonWidget
.$element
;
10738 this.$help
= $( [] );
10743 .addClass( 'oo-ui-fieldsetLayout-header' )
10744 .append( this.$icon
, this.$label
, this.$help
);
10745 this.$group
.addClass( 'oo-ui-fieldsetLayout-group' );
10747 .addClass( 'oo-ui-fieldsetLayout' )
10748 .prepend( this.$header
, this.$group
);
10749 if ( Array
.isArray( config
.items
) ) {
10750 this.addItems( config
.items
);
10756 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
10757 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.IconElement
);
10758 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.LabelElement
);
10759 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.GroupElement
);
10761 /* Static Properties */
10767 OO
.ui
.FieldsetLayout
.static.tagName
= 'fieldset';
10770 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
10771 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
10772 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
10773 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
10775 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
10776 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
10777 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
10778 * some fancier controls. Some controls have both regular and InputWidget variants, for example
10779 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
10780 * often have simplified APIs to match the capabilities of HTML forms.
10781 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
10783 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
10784 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
10787 * // Example of a form layout that wraps a fieldset layout
10788 * var input1 = new OO.ui.TextInputWidget( {
10789 * placeholder: 'Username'
10791 * var input2 = new OO.ui.TextInputWidget( {
10792 * placeholder: 'Password',
10795 * var submit = new OO.ui.ButtonInputWidget( {
10799 * var fieldset = new OO.ui.FieldsetLayout( {
10800 * label: 'A form layout'
10802 * fieldset.addItems( [
10803 * new OO.ui.FieldLayout( input1, {
10804 * label: 'Username',
10807 * new OO.ui.FieldLayout( input2, {
10808 * label: 'Password',
10811 * new OO.ui.FieldLayout( submit )
10813 * var form = new OO.ui.FormLayout( {
10814 * items: [ fieldset ],
10815 * action: '/api/formhandler',
10818 * $( 'body' ).append( form.$element );
10821 * @extends OO.ui.Layout
10822 * @mixins OO.ui.mixin.GroupElement
10825 * @param {Object} [config] Configuration options
10826 * @cfg {string} [method] HTML form `method` attribute
10827 * @cfg {string} [action] HTML form `action` attribute
10828 * @cfg {string} [enctype] HTML form `enctype` attribute
10829 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
10831 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
10834 // Configuration initialization
10835 config
= config
|| {};
10837 // Parent constructor
10838 OO
.ui
.FormLayout
.parent
.call( this, config
);
10840 // Mixin constructors
10841 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
10844 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
10846 // Make sure the action is safe
10847 action
= config
.action
;
10848 if ( action
!== undefined && !OO
.ui
.isSafeUrl( action
) ) {
10849 action
= './' + action
;
10854 .addClass( 'oo-ui-formLayout' )
10856 method
: config
.method
,
10858 enctype
: config
.enctype
10860 if ( Array
.isArray( config
.items
) ) {
10861 this.addItems( config
.items
);
10867 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
10868 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.mixin
.GroupElement
);
10873 * A 'submit' event is emitted when the form is submitted.
10878 /* Static Properties */
10884 OO
.ui
.FormLayout
.static.tagName
= 'form';
10889 * Handle form submit events.
10892 * @param {jQuery.Event} e Submit event
10895 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
10896 if ( this.emit( 'submit' ) ) {
10902 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
10903 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
10906 * // Example of a panel layout
10907 * var panel = new OO.ui.PanelLayout( {
10911 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
10913 * $( 'body' ).append( panel.$element );
10916 * @extends OO.ui.Layout
10919 * @param {Object} [config] Configuration options
10920 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
10921 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
10922 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
10923 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
10925 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
10926 // Configuration initialization
10927 config
= $.extend( {
10934 // Parent constructor
10935 OO
.ui
.PanelLayout
.parent
.call( this, config
);
10938 this.$element
.addClass( 'oo-ui-panelLayout' );
10939 if ( config
.scrollable
) {
10940 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
10942 if ( config
.padded
) {
10943 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
10945 if ( config
.expanded
) {
10946 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
10948 if ( config
.framed
) {
10949 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
10955 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
10960 * Focus the panel layout
10962 * The default implementation just focuses the first focusable element in the panel
10964 OO
.ui
.PanelLayout
.prototype.focus = function () {
10965 OO
.ui
.findFocusable( this.$element
).focus();
10969 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
10970 * items), with small margins between them. Convenient when you need to put a number of block-level
10971 * widgets on a single line next to each other.
10973 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
10976 * // HorizontalLayout with a text input and a label
10977 * var layout = new OO.ui.HorizontalLayout( {
10979 * new OO.ui.LabelWidget( { label: 'Label' } ),
10980 * new OO.ui.TextInputWidget( { value: 'Text' } )
10983 * $( 'body' ).append( layout.$element );
10986 * @extends OO.ui.Layout
10987 * @mixins OO.ui.mixin.GroupElement
10990 * @param {Object} [config] Configuration options
10991 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
10993 OO
.ui
.HorizontalLayout
= function OoUiHorizontalLayout( config
) {
10994 // Configuration initialization
10995 config
= config
|| {};
10997 // Parent constructor
10998 OO
.ui
.HorizontalLayout
.parent
.call( this, config
);
11000 // Mixin constructors
11001 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
11004 this.$element
.addClass( 'oo-ui-horizontalLayout' );
11005 if ( Array
.isArray( config
.items
) ) {
11006 this.addItems( config
.items
);
11012 OO
.inheritClass( OO
.ui
.HorizontalLayout
, OO
.ui
.Layout
);
11013 OO
.mixinClass( OO
.ui
.HorizontalLayout
, OO
.ui
.mixin
.GroupElement
);